text
stringlengths 28
881k
|
---|
from ..base.event import BaseEventNEWLINENEWLINENEWLINEclass ItemPurchase(BaseEvent):NEWLINE amount: floatNEWLINE username: strNEWLINE item_id: strNEWLINE |
r"""NEWLINEModule for some integrators.NEWLINENEWLINE - IRK3: Implicit third order Runge-KuttaNEWLINE - RK4: Runge-Kutta fourth orderNEWLINE - ETD: Exponential time differencing Euler methodNEWLINE - ETDRK4: Exponential time differencing Runge-Kutta fourth orderNEWLINENEWLINESee, e.g.,NEWLINEH. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINEIntegrators are set up to solve equations likeNEWLINENEWLINE.. math::NEWLINENEWLINE \frac{\partial u}{\partial t} = L u + N(u)NEWLINENEWLINEwhere :math:`u` is the solution, :math:`L` is a linear operator andNEWLINE:math:`N(u)` is the nonlinear part of the right hand side.NEWLINENEWLINENoteNEWLINE----NEWLINE`RK4`, `ETD` and `ETDRK4` can only be used with Fourier function spaces,NEWLINEas they assume all matrices are diagonal.NEWLINENEWLINE"""NEWLINEimport typesNEWLINEimport numpy as npNEWLINEfrom shenfun import Function, TPMatrix, TrialFunction, TestFunction,\NEWLINE inner, la, Expr, CompositeSpace, BlockMatrix, extract_bc_matrices,\NEWLINE SparseMatrix, get_simplified_tpmatrices, ScipyMatrixNEWLINENEWLINE__all__ = ('IRK3', 'BackwardEuler', 'RK4', 'ETDRK4', 'ETD')NEWLINENEWLINE#pylint: disable=unused-variableNEWLINENEWLINEclass IntegratorBase:NEWLINE """Abstract base class for integratorsNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINENEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE _p = {'dt': 0}NEWLINE _p.update(params)NEWLINE self.params = _pNEWLINE self.T = TNEWLINE if L is not None:NEWLINE self.LinearRHS = types.MethodType(L, self)NEWLINE if N is not None:NEWLINE self.NonlinearRHS = types.MethodType(N, self)NEWLINE if update is not None:NEWLINE self.update = types.MethodType(update, self)NEWLINENEWLINE def update(self, u, u_hat, t, tstep, **par):NEWLINE passNEWLINENEWLINE def LinearRHS(self, *args, **kwargs):NEWLINE return 0NEWLINENEWLINE def NonlinearRHS(self, *args, **kwargs):NEWLINE return 0NEWLINENEWLINE def setup(self, dt):NEWLINE """Set up solver"""NEWLINE passNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE passNEWLINENEWLINENEWLINEclass IRK3(IntegratorBase):NEWLINE """Third order implicit Runge KuttaNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : function of TrialFunction(T)NEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.dU1 = Function(T)NEWLINE self.a = (8./15., 5./12., 3./4.)NEWLINE self.b = (0.0, -17./60., -5./12.)NEWLINE self.c = (0.0, 8./15., 2./3., 1)NEWLINE self.solver = NoneNEWLINE self.bm = NoneNEWLINE self.rhs_mats = NoneNEWLINE self.w0 = Function(self.T)NEWLINE self.mask = NoneNEWLINE if hasattr(T, 'get_mask_nyquist'):NEWLINE self.mask = T.get_mask_nyquist()NEWLINENEWLINE def setup(self, dt):NEWLINE if isinstance(self.T, CompositeSpace):NEWLINE assert self.T.tensor_rank > 0, 'IRK3 only works for tensors, not generic CompositeSpaces'NEWLINENEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINENEWLINE # Note that we are here assembling implicit left hand side matrices,NEWLINE # as well as matrices that can be used to assemble the right hand sideNEWLINE # much faster through matrix-vector productsNEWLINENEWLINE a, b = self.a, self.bNEWLINE self.solver = []NEWLINE self.rhs_mats = []NEWLINE u0 = self.LinearRHS(u)NEWLINE for rk in range(3):NEWLINE if u0:NEWLINE mats = inner(v, u-((a[rk]+b[rk])*dt/2)*u0)NEWLINE else:NEWLINE mats = inner(v, u)NEWLINE if self.T.dimensions == 1:NEWLINE self.solver.append(la.Solver(mats))NEWLINENEWLINE elif self.T.tensor_rank == 0:NEWLINE if len(mats[0].naxes) == 1:NEWLINE self.solver.append(la.SolverGeneric1ND(mats))NEWLINE elif len(mats[0].naxes) == 2:NEWLINE self.solver.append(la.SolverGeneric2ND(mats))NEWLINE else:NEWLINE raise NotImplementedErrorNEWLINE else:NEWLINE self.solver.append(BlockMatrixSolver(mats))NEWLINENEWLINE if u0:NEWLINE rhs_mats = inner(v, u+((a[rk]+b[rk])*dt/2)*u0)NEWLINE else:NEWLINE rhs_mats = inner(v, u)NEWLINE mat = ScipyMatrix if self.T.dimensions == 1 else BlockMatrixNEWLINE self.rhs_mats.append(mat(rhs_mats))NEWLINENEWLINE def compute_rhs(self, u, u_hat, dU, dU1, rk):NEWLINE a = self.a[rk]NEWLINE b = self.b[rk]NEWLINE dt = self.params['dt']NEWLINE dU = self.NonlinearRHS(u, u_hat, dU, **self.params)NEWLINE if self.mask:NEWLINE dU.mask_nyquist(self.mask)NEWLINE w1 = dU*a*dt + dU1*b*dtNEWLINE dU1[:] = dUNEWLINE if isinstance(dU, np.ndarray):NEWLINE dU[:] = w1NEWLINE return dUNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE if self.solver is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = self.tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE self.tstep = tstepNEWLINE for rk in range(3):NEWLINE self.params['ti'] = t+self.c[rk]*dtNEWLINE dU = self.compute_rhs(u, u_hat, self.dU, self.dU1, rk)NEWLINE dU += self.rhs_mats[rk].matvec(u_hat, self.w0)NEWLINE u_hat = self.solver[rk](dU, u=u_hat)NEWLINE if self.mask:NEWLINE u_hat.mask_nyquist(self.mask)NEWLINENEWLINE t += dtNEWLINE tstep += 1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINENEWLINEclass BackwardEuler(IntegratorBase):NEWLINE """First order backward EulerNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : function of TrialFunction(T)NEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.dU1 = Function(T)NEWLINE self.solver = NoneNEWLINE self.rhs_mats = NoneNEWLINE self.w0 = Function(self.T)NEWLINE self.mask = NoneNEWLINE if hasattr(T, 'get_mask_nyquist'):NEWLINE self.mask = T.get_mask_nyquist()NEWLINENEWLINE def setup(self, dt):NEWLINE if isinstance(self.T, CompositeSpace):NEWLINE assert self.T.tensor_rank > 0, 'BackwardEuler only works for tensors, not generic CompositeSpaces'NEWLINENEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE mats = inner(u-dt*self.LinearRHS(u), v)NEWLINE M = inner(u, v)NEWLINENEWLINE if self.T.dimensions == 1:NEWLINE self.solver = la.Solve(mats)NEWLINE self.rhs_mats = MNEWLINE returnNEWLINENEWLINE if self.T.tensor_rank == 0:NEWLINE if len(mats[0].naxes) == 1:NEWLINE self.solver = la.SolverGeneric1ND(mats)NEWLINE elif len(mats[0].naxes) == 2:NEWLINE self.solver = la.SolverGeneric2ND(mats)NEWLINE else:NEWLINE raise NotImplementedErrorNEWLINE else:NEWLINE self.solver = BlockMatrixSolver(mats)NEWLINE self.rhs_mats = BlockMatrix(M if isinstance(M, list) else [M])NEWLINENEWLINE def compute_rhs(self, u, u_hat, dU, dU1):NEWLINE dt = self.params['dt']NEWLINE dU = self.NonlinearRHS(u, u_hat, dU, **self.params)NEWLINE if self.mask:NEWLINE dU.mask_nyquist(self.mask)NEWLINE w1 = dU*2*dt - dU1*dtNEWLINE dU1[:] = dUNEWLINE return w1NEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE if self.solver is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = self.tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE self.params['ti'] = tNEWLINE self.tstep = tstepNEWLINE dU = self.compute_rhs(u, u_hat, self.dU, self.dU1)NEWLINE dU += self.rhs_mats.matvec(u_hat, self.w0)NEWLINE u_hat = self.solver(dU, u=u_hat)NEWLINE if self.mask:NEWLINE u_hat.mask_nyquist(self.mask)NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINENEWLINENEWLINEclass ETD(IntegratorBase):NEWLINE """Exponential time differencing Euler methodNEWLINENEWLINE H. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE 3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINENEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.psi = NoneNEWLINE self.ehL = NoneNEWLINENEWLINE def setup(self, dt):NEWLINE """Set up ETD ODE solver"""NEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE L = self.LinearRHS(u, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(v, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE L = np.atleast_1d(L)NEWLINE hL = L*dtNEWLINE self.ehL = np.exp(hL)NEWLINE M = 50NEWLINE psi = self.psi = np.zeros(hL.shape, dtype=float)NEWLINE for k in range(1, M+1):NEWLINE ll = hL+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi += ((np.exp(ll)-1.)/ll).realNEWLINE psi /= MNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.psi is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE u_hat[:] = self.ehL*u_hat + dt*self.psi*self.dUNEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINENEWLINENEWLINEclass ETDRK4(IntegratorBase):NEWLINE """Exponential time differencing Runge-Kutta 4'th order methodNEWLINENEWLINE H. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE 3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.U_hat0 = Function(T)NEWLINE self.U_hat1 = Function(T)NEWLINE self.dU = Function(T)NEWLINE self.dU0 = Function(T)NEWLINE self.V2 = Function(T)NEWLINE self.psi = np.zeros((4,)+self.U_hat0.shape, dtype=float)NEWLINE self.a = NoneNEWLINE self.b = [0.5, 0.5, 0.5]NEWLINE self.ehL = NoneNEWLINE self.ehL_h = NoneNEWLINENEWLINE def setup(self, dt):NEWLINE """Set up ETDRK4 ODE solver"""NEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE L = self.LinearRHS(u, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(v, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE L = np.atleast_1d(L)NEWLINE hL = L*dtNEWLINE self.ehL = np.exp(hL)NEWLINE self.ehL_h = np.exp(hL/2.)NEWLINE M = 50NEWLINE psi = self.psi = np.zeros((4,) + hL.shape, dtype=float)NEWLINE for k in range(1, M+1):NEWLINE ll = hL+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi[0] += ((np.exp(ll)-1.)/ll).realNEWLINE psi[1] += ((np.exp(ll)-ll-1.)/ll**2).realNEWLINE psi[2] += ((np.exp(ll)-0.5*ll**2-ll-1.)/ll**3).realNEWLINE ll2 = hL/2.+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi[3] += ((np.exp(ll2)-1.)/(ll2)).realNEWLINENEWLINE psi /= MNEWLINE a = [psi[0]-3*psi[1]+4*psi[2]]NEWLINE a.append(2*psi[1]-4*psi[2])NEWLINE a.append(2*psi[1]-4*psi[2])NEWLINE a.append(-psi[1]+4*psi[2])NEWLINE self.a = aNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.a is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINENEWLINE self.U_hat0[:] = u_hat*self.ehL_hNEWLINE self.U_hat1[:] = u_hat*self.ehLNEWLINE for rk in range(4):NEWLINE self.dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE if rk < 2:NEWLINE u_hat[:] = self.U_hat0 + self.b[rk]*dt*self.psi[3]*self.dUNEWLINE elif rk == 2:NEWLINE u_hat[:] = self.ehL_h*self.V2 + self.b[rk]*dt*self.psi[3]*(2*self.dU-self.dU0)NEWLINENEWLINE if rk == 0:NEWLINE self.dU0[:] = self.dUNEWLINE self.V2[:] = u_hatNEWLINENEWLINE self.U_hat1 += self.a[rk]*dt*self.dUNEWLINE u_hat[:] = self.U_hat1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINENEWLINENEWLINEclass RK4(IntegratorBase):NEWLINE """Regular 4'th order Runge-Kutta integratorNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.U_hat0 = Function(T)NEWLINE self.U_hat1 = Function(T)NEWLINE self.dU = Function(T)NEWLINE self.a = np.array([1./6., 1./3., 1./3., 1./6.])NEWLINE self.b = np.array([0.5, 0.5, 1.])NEWLINENEWLINE def setup(self, dt):NEWLINE """Set up RK4 ODE solver"""NEWLINE self.params['dt'] = dtNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in end_timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.a is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE ut = TrialFunction(self.T)NEWLINE vt = TestFunction(self.T)NEWLINE L = self.LinearRHS(ut, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(vt, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.U_hat0[:] = self.U_hat1[:] = u_hatNEWLINE for rk in range(4):NEWLINE dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE if isinstance(L, np.ndarray):NEWLINE dU += L*u_hatNEWLINE if rk < 3:NEWLINE u_hat[:] = self.U_hat0 + self.b[rk]*dt*dUNEWLINE self.U_hat1 += self.a[rk]*dt*dUNEWLINE u_hat[:] = self. U_hat1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINE |
import osNEWLINENEWLINEfrom aiogram import Bot, DispatcherNEWLINEfrom aiogram.contrib.fsm_storage.memory import MemoryStorageNEWLINENEWLINEAPI_TOKEN = os.getenv('API_TOKEN')NEWLINETIMEOUT = int(os.getenv('TIMEOUT'))NEWLINEDATABASE_URI = os.getenv('DATABASE_URI')NEWLINENEWLINEbot = Bot(token=API_TOKEN)NEWLINEstorage = MemoryStorage()NEWLINEdp = Dispatcher(bot, storage=storage)NEWLINE |
#NEWLINE# PySNMP MIB module DES-1210-28MEbx (http://snmplabs.com/pysmi)NEWLINE# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DES-1210-28MEbxNEWLINE# Produced by pysmi-0.3.4 at Wed May 1 12:38:52 2019NEWLINE# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4NEWLINE# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) NEWLINE#NEWLINEInteger, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")NEWLINENamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")NEWLINEConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint")NEWLINEdot1dBasePort, dot1dBasePortEntry, dot1dBridge = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePort", "dot1dBasePortEntry", "dot1dBridge")NEWLINEAddressFamilyNumbers, = mibBuilder.importSymbols("IANA-ADDRESS-FAMILY-NUMBERS-MIB", "AddressFamilyNumbers")NEWLINEInterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero")NEWLINEInetAddress, = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress")NEWLINEVlanId, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "VlanId")NEWLINESnmpSecurityLevel, SnmpEngineID, SnmpAdminString = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpSecurityLevel", "SnmpEngineID", "SnmpAdminString")NEWLINEModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")NEWLINEBits, ObjectIdentity, ModuleIdentity, Unsigned32, NotificationType, MibIdentifier, iso, Gauge32, Integer32, enterprises, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Counter32, IpAddress, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "ObjectIdentity", "ModuleIdentity", "Unsigned32", "NotificationType", "MibIdentifier", "iso", "Gauge32", "Integer32", "enterprises", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Counter32", "IpAddress", "Counter64")NEWLINETruthValue, MacAddress, RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "MacAddress", "RowStatus", "DisplayString", "TextualConvention")NEWLINEdes_1210_28mebx = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2)).setLabel("des-1210-28mebx")NEWLINEdes_1210_28mebx.setRevisions(('2015-06-03 00:00', '2015-04-16 00:00', '2014-03-06 00:00',))NEWLINENEWLINEif getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):NEWLINE if mibBuilder.loadTexts: des_1210_28mebx.setRevisionsDescriptions((' In order to pass the web www.simpleweb.org to verify severity level 3, which must be change the SYNTAX of mib file.', 'Add trafficCtrlAutoRecoverTime object.', 'Initial version, published as D-Link des-1210 28ME mib.',))NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setLastUpdated('201506030000Z')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setOrganization('DES-1210-28-BX-6-07-017.mib')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setContactInfo('')NEWLINEif mibBuilder.loadTexts: des_1210_28mebx.setDescription(' In order to pass the web www.simpleweb.org to verify severity level 3, which must be change the SYNTAX of mib file.')NEWLINEd_link = MibIdentifier((1, 3, 6, 1, 4, 1, 171)).setLabel("d-link")NEWLINEdlink_products = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10)).setLabel("dlink-products")NEWLINEdlink_DES1210SeriesProd = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75)).setLabel("dlink-DES1210SeriesProd")NEWLINEdes_1210_28me = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15)).setLabel("des-1210-28me")NEWLINEclass VlanIndex(TextualConvention, Unsigned32):NEWLINE description = 'A value used to index per-VLAN tables: values of 0 and 4095 are not permitted; if the value is between 1 and 4094 inclusive, it represents an IEEE 802.1Q VLAN-ID with global scope within a given bridged domain (see VlanId textual convention). If the value is greater than 4095 then it represents a VLAN with scope local to the particular agent, i.e. one without a global VLAN-ID assigned to it. Such VLANs are outside the scope of IEEE 802.1Q but it is convenient to be able to manage them in the same way using this MIB.'NEWLINE status = 'current'NEWLINENEWLINEclass PortList(TextualConvention, OctetString):NEWLINE description = "Each octet within this value specifies a set of eight ports, with the first octet specifying ports 1 through 8, the second octet specifying ports 9 through 16, etc. Within each octet, the most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port. Thus, each port of the bridge is represented by a single bit within the value of this object. If that bit has a value of '1' then that port is included in the set of ports; the port is not included if its bit has a value of '0'."NEWLINE status = 'current'NEWLINENEWLINEclass BridgeId(TextualConvention, OctetString):NEWLINE description = "The Bridge-Identifier as used in the Spanning Tree Protocol to uniquely identify a bridge. Its first two octets (in network byte order) contain a priority value and its last 6 octets contain the MAC address used to refer to a bridge in a unique fashion (typically, the numerically smallest MAC address of all ports on the bridge). Several objects in this MIB module represent values of timers used by the Spanning Tree Protocol. In this MIB, these timers have values in units of hundreths of a second (i.e. 1/100 secs). These timers, when stored in a Spanning Tree Protocol's BPDU, are in units of 1/256 seconds. Note, however, that 802.1D-1990 specifies a settable granularity of no more than 1 second for these timers. To avoid ambiguity, a data type is defined here as a textual convention and all representation of these timers in this MIB module are defined using this data type. An algorithm is also defined for converting between the different units, to ensure a timer's value is not distorted by multiple conversions."NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8)NEWLINE fixedLength = 8NEWLINENEWLINEclass Timeout(TextualConvention, Integer32):NEWLINE description = 'A STP timer in units of 1/100 seconds To convert a Timeout value into a value in units of 1/256 seconds, the following algorithm should be used: b = floor( (n * 256) / 100) where: floor = quotient [ignore remainder] n is the value in 1/100 second units b is the value in 1/256 second units To convert the value from 1/256 second units back to 1/100 seconds, the following algorithm should be used: n = ceiling( (b * 100) / 256) where: ceiling = quotient [if remainder is 0], or quotient + 1 [if remainder is non-zero] n is the value in 1/100 second units b is the value in 1/256 second units Note: it is important that the arithmetic operations are done in the order specified (i.e., multiply first, divide second).'NEWLINE status = 'current'NEWLINE displayHint = 'd4'NEWLINENEWLINEclass LldpManAddress(TextualConvention, OctetString):NEWLINE description = 'The value of a management address associated with the LLDP agent that may be used to reach higher layer entities to assist discovery by network management. It should be noted that appropriate security credentials, such as SNMP engineId, may be required to access the LLDP agent using a management address. These necessary credentials should be known by the network management and the objects associated with the credentials are not included in the LLDP agent.'NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 31)NEWLINENEWLINEclass OwnerString(TextualConvention, OctetString):NEWLINE description = "This data type is used to model an administratively assigned name of the owner of a resource. Implementations must accept values composed of well-formed NVT ASCII sequences. In addition, implementations should accept values composed of well-formed UTF-8 sequences. It is suggested that this name contain one or more of the following: IP address, management station name, network manager's name, location, or phone number. In some cases the agent itself will be the owner of an entry. In these cases, this string shall be set to a string starting with 'monitor'. SNMP access control is articulated entirely in terms of the contents of MIB views; access to a particular SNMP object instance depends only upon its presence or absence in a particular MIB view and never upon its value or the value of related object instances. Thus, objects of this type afford resolution of resource contention only among cooperating managers; they realize no access control function with respect to uncooperative parties."NEWLINE status = 'current'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 127)NEWLINENEWLINEclass RmonStatus(TextualConvention, Integer32):NEWLINE description = 'The status of a table entry. Setting this object to the value invalid(4) has the effect of invalidating the corresponding entry. That is, it effectively disassociates the mapping identified with said entry. It is an implementation-specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries currently not in use. Proper interpretation of such entries requires examination of the relevant RmonStatus object. An existing instance of this object cannot be set to createRequest(2). This object may only be set to createRequest(2) when this instance is created. When this object is created, the agent may wish to create supplemental object instances with default values to complete a conceptual row in this table. Because the creation of these default objects is entirely at the option of the agent, the manager must not assume that any will be created, but may make use of any that are created. Immediately after completing the create operation, the agent must set this object to underCreation(3). When in the underCreation(3) state, an entry is allowed to exist in a possibly incomplete, possibly inconsistent state, usually to allow it to be modified in multiple PDUs. When in this state, an entry is not fully active. Entries shall exist in the underCreation(3) state until the management station is finished configuring the entry and sets this object to valid(1) or aborts, setting this object to invalid(4). If the agent determines that an entry has been in the underCreation(3) state for an abnormally long time, it may decide that the management station has crashed. If the agent makes this decision, it may set this object to invalid(4) to reclaim the entry. A prudent agent will understand that the management station may need to wait for human input and will allow for that possibility in its determination of this abnormally long period. An entry in the valid(1) state is fully configured and consistent and fully represents the configuration or operation such a row is intended to represent. For example, it could be a statistical function that is configured and active, or a filter that is available in the list of filters processed by the packet capture process. A manager is restricted to changing the state of an entry in the following ways: To: valid createRequest underCreation invalid From: valid OK NO OK OK createRequest N/A N/A N/A N/A underCreation OK NO OK OK invalid NO NO NO OK nonExistent NO OK NO OK In the table above, it is not applicable to move the state from the createRequest state to any other state because the manager will never find the variable in that state. The nonExistent state is not a value of the enumeration, rather it means that the entryStatus variable does not exist at all. An agent may allow an entryStatus variable to change state in additional ways, so long as the semantics of the states are followed. This allowance is made to ease the implementation of the agent and is made despite the fact that managers should never exercise these additional state transitions.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))NEWLINE namedValues = NamedValues(("valid", 1), ("createRequest", 2), ("underCreation", 3), ("invalid", 4))NEWLINENEWLINEclass Ipv6Address(TextualConvention, OctetString):NEWLINE description = 'This data type is used to model IPv6 addresses. This is a binary string of 16 octets in network byte-order.'NEWLINE status = 'current'NEWLINE displayHint = '2x:'NEWLINE subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(16, 16)NEWLINE fixedLength = 16NEWLINENEWLINEcompanySystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1))NEWLINEcompanyIpifGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2))NEWLINEcompanyTftpGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3))NEWLINEcompanyMiscGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4))NEWLINEcompanySNMPV3 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5))NEWLINEcompanySTP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6))NEWLINEcompanyDot1qVlanGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7))NEWLINEcompanyLA = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8))NEWLINEcompanyStaticMAC = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9))NEWLINEcompanyIgsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10))NEWLINEcompanyGVRPGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11))NEWLINEcompanyQoSGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12))NEWLINEcompanyTrafficMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13))NEWLINEcompanySecurity = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14))NEWLINEcompanyACLGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15))NEWLINEcompanySyslog = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16))NEWLINEcompanyLBD = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17))NEWLINEcompanyMirror = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18))NEWLINEcompanyStaticMcast = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19))NEWLINEcompanySNTPSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20))NEWLINEcompanyRMON = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22))NEWLINEcompanyAuthGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23))NEWLINEcompanyGuestVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24))NEWLINEcompanyMacNotify = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25))NEWLINEcompanyISMVLAN = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27))NEWLINEcompanyDHCPRelay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28))NEWLINEcompanyDHCPLocalRelay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29))NEWLINEcompanyTrapSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30))NEWLINEsysFirmwareInfomation = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31))NEWLINEcompanyLLDPSetting = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32))NEWLINEcompanyCPUInterfaceFilterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33))NEWLINEcompanyStaticARP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34))NEWLINEcompanyCableDiagnostic = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35))NEWLINEcompanyVLANTrunk = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36))NEWLINEcompanyQinQ = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37))NEWLINEcompanyTimeRangeMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38))NEWLINEcompanySMTP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40))NEWLINEcompanyLimitIp = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45))NEWLINEcompanyGratuitousARP = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48))NEWLINEcompanyMulticastFilter = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49))NEWLINEcompanyNeighbor = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50))NEWLINEcompanyEoam = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51))NEWLINEcompanyDuld = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52))NEWLINEcompanyMacBasedVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70))NEWLINEcompanyBPDUAttack = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77))NEWLINEcompanyDHCPv6Relay = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86))NEWLINEcompanyMldsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88))NEWLINEcompanyPPPoE = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98))NEWLINEcompanyDoSCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99))NEWLINEcompanyAgentBasicInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100))NEWLINEcompanyProtocolVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101))NEWLINEcompanyL2PT = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102))NEWLINEcompanySfpVendorInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104))NEWLINEcompanyDDM = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105))NEWLINEcompanyFTPGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107))NEWLINEcompanyTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120))NEWLINEsysSwitchName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSwitchName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSwitchName.setDescription('System name used for identification of the device. The following characters are allowed to input. 0 ~ 9 / a ~ z / A ~ Z Special character: ( ) V + _ = .')NEWLINEsysHardwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysHardwareVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysHardwareVersion.setDescription('Version number of the Hardware.')NEWLINEsysFirmwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysFirmwareVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysFirmwareVersion.setDescription('Version number of the Firmware.')NEWLINEsysLoginTimeoutInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(3, 30)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLoginTimeoutInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLoginTimeoutInterval.setDescription('This time interval is used to count the time and logout web interface automatically.')NEWLINEsysLocationName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLocationName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLocationName.setDescription("The location name of this node (e.g., `telephone closet, 3rd floor'). If the location is unknown, the value is the zero-length string.")NEWLINEsysGroupInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(120, 1225), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGroupInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGroupInterval.setDescription('Group Interval is used to send D-link Discover packet to D-link SmartConsole Utility frequency. The timer in units of seconds. Set value 0 to disable group Interval.')NEWLINEsysSafeGuardEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSafeGuardEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSafeGuardEnable.setDescription('This object is used to set Safeguard Enable\\Disable.')NEWLINEsysRestart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 9), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysRestart.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysRestart.setDescription("This object allows the user to restart the Switch (i.e)the entire switch will operationally go down and start again. Setting a value of 'true' causes the switch to be restarted. When the switch operationally goes down, configuration save operation is initiated based on the configuration save option chosen. When the switch operationally come up, the saved configurations are restored based on the restore option chosen. Once the switch is restarted, the value of this object reverts to 'false'.")NEWLINEsysSave = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("true", 1), ("false", 2), ("config-1", 3), ("config-2", 4))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSave.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSave.setDescription('This object is used to save Configuration , value 1 save config_1 , value 2 is not in process , value 3 is save config_1 and value 4 is save config_2.')NEWLINEsysJumboFrameEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysJumboFrameEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysJumboFrameEnable.setDescription('Gigabit Web Smart Switches support jumbo frames (frames larger than the Ethernet frame size of 1522 bytes) of up to 10,000 bytes (tagged). Default jumbo frame is disabled.')NEWLINEsysPortCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13), )NEWLINEif mibBuilder.loadTexts: sysPortCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlTable.setDescription('A table to control the port specific parameters of the device like speed, duplex mode, etc.')NEWLINEsysPortCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortCtrlIndex"), (0, "DES-1210-28MEbx", "sysPortCtrlMediumType"))NEWLINEif mibBuilder.loadTexts: sysPortCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlEntry.setDescription('An entry appears in this table for each interface in the system. Index to the table is the interface index of the port.')NEWLINEsysPortCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEsysPortCtrlMediumType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlMediumType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlMediumType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortCtrlSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("rate1000M-Full", 1), ("rate100M-Full", 2), ("rate100M-Half", 3), ("rate10M-Full", 4), ("rate10M-Half", 5), ("auto", 6), ("disable", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlSpeed.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlSpeed.setDescription('Configures interface speed.')NEWLINEsysPortCtrlOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("down", 1), ("rate1000M-Full", 2), ("rate100M-Full", 3), ("rate100M-Half", 4), ("rate10M-Full", 5), ("rate10M-Half", 6), ("rate10G-Full", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlOperStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlOperStatus.setDescription("The port's operating speed state.")NEWLINEsysPortCtrlMDI = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("auto", 1), ("mdi", 2), ("mdix", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlMDI.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlMDI.setDescription('Configures interface auto/mdi/mdix mode. The default setting is Auto.')NEWLINEsysPortCtrlFlowControl = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControl.setDescription('Enables / disables flow control for the interface.')NEWLINEsysPortCtrlFlowControlOper = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControlOper.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlFlowControlOper.setDescription("The link parner negotiate port's operating flow control state.")NEWLINEsysPortCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("fastethernet", 1), ("gigabitethernet", 2), ("fiberwith100Base-and-1000BaseSFPModule", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlType.setDescription("The port's media type.")NEWLINEsysPortCtrlCapability = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 13, 1, 9), Bits().clone(namedValues=NamedValues(("rate10-half", 0), ("rate10-full", 1), ("rate100-half", 2), ("rate100-full", 3), ("reserve", 4), ("rate1000-full", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortCtrlCapability.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortCtrlCapability.setDescription("The port's capability advertised.")NEWLINEsysPortDescriptionTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14), )NEWLINEif mibBuilder.loadTexts: sysPortDescriptionTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescriptionTable.setDescription('The port description table.')NEWLINEsysPortDescriptionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortDescIndex"), (0, "DES-1210-28MEbx", "sysPortDescMediumType"))NEWLINEif mibBuilder.loadTexts: sysPortDescriptionEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescriptionEntry.setDescription('The port description entry.')NEWLINEsysPortDescIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortDescIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescIndex.setDescription('This object indicates the port index.')NEWLINEsysPortDescMediumType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortDescMediumType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescMediumType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortDescString = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysPortDescString.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortDescString.setDescription('This object indicates the port description.')NEWLINEsysPortUpLinkTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 14, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortUpLinkTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortUpLinkTime.setDescription('This object indicates the port link up time.')NEWLINEsysPortErrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15), )NEWLINEif mibBuilder.loadTexts: sysPortErrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrTable.setDescription('The port error table.')NEWLINEsysPortErrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortErrPortIndex"))NEWLINEif mibBuilder.loadTexts: sysPortErrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrEntry.setDescription('A list of information for the err port of the device.')NEWLINEsysPortErrPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortIndex.setDescription("This object indicates the module's port number.(1..Max port number in the module)")NEWLINEsysPortErrPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortState.setDescription('This object decides whether the port state is enabled or disabled.')NEWLINEsysPortErrPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("err-disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortStatus.setDescription('This object decides whether the PortStatus is err-disabled.')NEWLINEsysPortErrPortReason = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 15, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("lbd", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortErrPortReason.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortErrPortReason.setDescription('This object decides whether the PortStatus is LBD.')NEWLINEsysDhcpAutoConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfiguration.setDescription('This object indicates auto config is enabled or disabled.')NEWLINEsysWebState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysWebState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysWebState.setDescription('This object is for Enabled(1) or Disabled(2) Web state in the system.')NEWLINEsysWebPortNumber = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(80)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysWebPortNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysWebPortNumber.setDescription('Web Server Port Number.')NEWLINEsysARPAgingTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysARPAgingTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysARPAgingTime.setDescription('This object is for ARP aging time.')NEWLINEsysMACAgingTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 1000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMACAgingTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMACAgingTime.setDescription('This object is for MAC aging time.')NEWLINEbaudRateConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(9600, 19200, 38400, 115200))).clone(namedValues=NamedValues(("baudrate9600", 9600), ("baudrate19200", 19200), ("baudrate38400", 38400), ("baudrate115200", 115200)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: baudRateConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: baudRateConfiguration.setDescription('To set SerialPort baud-rate configuration.')NEWLINEautologoutConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(120, 300, 600, 900, 0))).clone(namedValues=NamedValues(("logouttime2mins", 120), ("logouttime5mins", 300), ("logouttime10mins", 600), ("logouttime15mins", 900), ("logouttimenever", 0)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autologoutConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: autologoutConfiguration.setDescription('To set SerialPort auto-logout-time configuration.')NEWLINEtelnetsettingManagementOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: telnetsettingManagementOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: telnetsettingManagementOnOff.setDescription('Enable/Disable management Telnetsetting mechanism.')NEWLINEtelnetUDPPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 24), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(23)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: telnetUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: telnetUDPPort.setDescription("The value is for setting telnet's UDP Port.")NEWLINEautoRefreshConfiguration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("refreshimenever", 0), ("refreshtime10secs", 1), ("refreshtime30secs", 2), ("refreshtime1min", 3), ("refreshtime5mins", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autoRefreshConfiguration.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoRefreshConfiguration.setDescription('To set the WEB panel auto refresh timer.')NEWLINEfloodfdbOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: floodfdbOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: floodfdbOnOff.setDescription('To set enable status for flood fdb.')NEWLINEsysContactName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 27), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysContactName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysContactName.setDescription('To set system contact name.')NEWLINEsysDhcpAutoConfigTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfigTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoConfigTimeout.setDescription('To set dhcp auto config timeout.')NEWLINEsysCommandLogging = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysCommandLogging.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysCommandLogging.setDescription('To set enable status for CommandLogging.')NEWLINEsysSerialNumber = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 30), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 13))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysSerialNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSerialNumber.setDescription('To get the serial number.')NEWLINEsysVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysVersion.setDescription('The version of firmware information.')NEWLINEsysSize = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSize.setDescription('The size of firmware information.')NEWLINEsysUpdateTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysUpdateTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysUpdateTime.setDescription('The Update Time of firmware information.')NEWLINEsysFromIP = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 4), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysFromIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysFromIP.setDescription('The IP address of firmware information.')NEWLINEsysUser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 9))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysUser.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysUser.setDescription('The user of firmware infomation.')NEWLINEsysType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 31, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, -1))).clone(namedValues=NamedValues(("console", 1), ("telnet", 2), ("ssh", 3), ("web", 4), ("unknown", -1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysType.setDescription('The type of firmware infomation.')NEWLINEsysBootupConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 33), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBootupConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBootupConfigID.setDescription('To get/set bootup config ID.')NEWLINEsysDhcpAutoImage = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 34), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysDhcpAutoImage.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysDhcpAutoImage.setDescription('This object indicates auto image is enabled or disabled.')NEWLINEsysPortMediaTypeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36), )NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeTable.setDescription('A table to control the port specific parameters of the device like speed, Vendor name, etc.')NEWLINEsysPortMediaTypeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysPortMediaTypeIndex"), (0, "DES-1210-28MEbx", "sysPortMediaType"))NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeEntry.setDescription('An entry appears in this table for each interface in the system. Index to the table is the interface index of the port.')NEWLINEsysPortMediaTypeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEsysPortMediaType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(100, 101))).clone(namedValues=NamedValues(("copper", 100), ("fiber", 101)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaType.setDescription('This object indicates the port type: fiber 1G/100M or copper.')NEWLINEsysPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("rate100M", 1), ("rate1000M", 2), ("rate10G", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortType.setDescription('Configures interface speed.')NEWLINEsysPortMediaTypeVendorName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeVendorName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeVendorName.setDescription("The port's VendorName.")NEWLINEsysPortMediaTypeOui = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeOui.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeOui.setDescription("The port's Oui.")NEWLINEsysPortMediaTypePn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypePn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypePn.setDescription("The port's Pn.")NEWLINEsysPortMediaTypeRev = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeRev.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeRev.setDescription("The port's Rev.")NEWLINEsysPortMediaTypeSn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeSn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeSn.setDescription("The port's Sn.")NEWLINEsysPortMediaTypeDateCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 1, 36, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeDateCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysPortMediaTypeDateCode.setDescription("The port's DateCode.")NEWLINEipv4sysIpAddrCfgMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("manual", 1), ("dynamic", 2))).clone('manual')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddrCfgMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddrCfgMode.setDescription("Specifies the means by which the default interface in the device gets the IP address. If 'manual' mode is selected, the default interface takes the 'sysDefaultIpAddr' configured in the system. If 'dynamic' mode is selected, the default interface gets the IP address through dynamic IP address configuration protocols such as RARP client, BootP client, DHCP Client, etc. If the system fails to get the IP address dynamically through all the above protocols, the default interface uses the 'sysDefaultIpAddr' configured in the system.")NEWLINEipv4sysIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpAddr.setDescription('Default IP Address of the system. This IP address, if modified, will take effect only when the configuration is stored & restored.')NEWLINEipv4sysIpSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIpSubnetMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIpSubnetMask.setDescription('IP subnet mask for the default IP address. This subnet mask, if modified, will take effect only when the configuration is stored & restored.')NEWLINEipv4sysGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysGateway.setDescription('Gateway')NEWLINEipv4dhcpOption12Status = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12Status.setDescription('Status of DHCP Option12')NEWLINEipv4dhcpOption12HostName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12HostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4dhcpOption12HostName.setDescription('Host name in DHCP option 12')NEWLINEipifSupportV4V6Info = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7))NEWLINEsysIpAddrCfgMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("manual", 1), ("dynamic", 2))).clone('manual')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpAddrCfgMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpAddrCfgMode.setDescription("Specifies the means by which the default interface in the device gets the IP address. If 'manual' mode is selected, the default interface takes the 'sysDefaultIpAddr' configured in the system. If 'dynamic' mode is selected, the default interface gets the IP address through dynamic IP address configuration protocols such as RARP client, BootP client, DHCP Client, etc. If the system fails to get the IP address dynamically through all the above protocols, the default interface uses the 'sysDefaultIpAddr' configured in the system.")NEWLINEsysIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpAddr.setDescription('Default IP Address of the system. This IP address, if modified, will take effect only when the configuration is stored & restored.')NEWLINEsysIpSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysIpSubnetMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysIpSubnetMask.setDescription('IP subnet mask for the default IP address. This subnet mask, if modified, will take effect only when the configuration is stored & restored.')NEWLINEsysGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGateway.setDescription('Gateway')NEWLINEdhcpOption12Status = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpOption12Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpOption12Status.setDescription('Status of DHCP Option12')NEWLINEdhcpOption12HostName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpOption12HostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpOption12HostName.setDescription('Host name in DHCP option 12')NEWLINEipifName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 7), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifName.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifName.setDescription('The Description for the interface.')NEWLINEipifVLANname = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 8), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifVLANname.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifVLANname.setDescription('The vlan name for the interface.')NEWLINEipifv6GlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6GlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6GlobalStatus.setDescription('The ID of VLAN that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6DHCPStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6DHCPStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6DHCPStatus.setDescription('The state of DHCPv6 that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6AutolinkloStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6AutolinkloStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6AutolinkloStatus.setDescription('The global state of link local that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifv6NSRetransmitTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6NSRetransmitTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6NSRetransmitTime.setDescription("The NS's retransmit time that you want this interface to be in. It must be a exist vlan id (1~3600).")NEWLINEipifv6DefaultGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 13), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipifv6DefaultGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifv6DefaultGateway.setDescription('The ipv6 default gateway that you want this interface to be in. It must be a exist vlan id.')NEWLINEipifV6AddressTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14), )NEWLINEif mibBuilder.loadTexts: ipifV6AddressTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressTable.setDescription('A list of interface entries.')NEWLINEipifV6AddressEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipifV6AddressMainIndex"), (0, "DES-1210-28MEbx", "ipifV6AddressIpAddr"), (0, "DES-1210-28MEbx", "ipifV6AddressIpPrefix"))NEWLINEif mibBuilder.loadTexts: ipifV6AddressEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressEntry.setDescription('An entry containing management information applicable to a particular interface.')NEWLINEipifV6AddressMainIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressMainIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressMainIndex.setDescription('The index of this IPv6 entry.')NEWLINEipifV6AddressIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 2), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpAddr.setDescription('The ip address of this IPv6 entry.')NEWLINEipifV6AddressIpPrefix = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpPrefix.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpPrefix.setDescription('The ip prefix of this IPv6 entry.')NEWLINEipifV6AddressIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unicast", 1), ("anycast", 2), ("linklocal", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressIpType.setDescription('The ip type of this IPv6 entry.')NEWLINEipifV6AddressRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 7, 14, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipifV6AddressRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipifV6AddressRowStatus.setDescription('The status of an entry in the Multi Interface Table. Only a subset of the rowstatus variables (active, createAndWait, destroy) are available.')NEWLINEipv4sysIprouteGateway = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteGateway.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteGateway.setDescription('IProute Gateway of the system.')NEWLINEipv4sysIprouteHops = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 2, 9), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteHops.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4sysIprouteHops.setDescription('IProute Hops of the system.')NEWLINEtftpFwServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 1), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download firmware.")NEWLINEtftpFwImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwImageFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwImageFileName.setDescription('Configure firmware filename to download.')NEWLINEtftpFwTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperation.setDescription('The tftp operates to perform downloading the firmware image to the unit. This object is used in conjunction with configBootTftpServerIp and configBootImageFileName.')NEWLINEtftpFwTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpFwTftpOperationStatus.setDescription('The tftp operation status represent firmware backup or upgrade status.')NEWLINEtftpCfgServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 5), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpCfgServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download configuration file.")NEWLINEtftpConfigFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpConfigFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigFileName.setDescription('The configuration filename is used to store or retrieve config from the tftp server.')NEWLINEtftpConfigTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("download", 1), ("upload", 2), ("progressing", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperation.setDescription('The tftp operates to perform either downloading the configuration file to the unit or uploading the current configuration file to the tftp server. This object is used in conjunction with configTftpServerIpAddress and configTftpServerFileName.')NEWLINEtftpConfigTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: tftpConfigTftpOperationStatus.setDescription('The tftp operation status represent configuration file backup or restore status.')NEWLINEtftpFwTargetGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9))NEWLINEtftpFwTargetServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 1), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download firmware.")NEWLINEtftpFwTargetServerIpType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetServerIpType.setDescription('Type of IP interface.')NEWLINEtftpFwTargetInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetInterfaceName.setDescription('Specifies the interface name when the tftpFwTargetServerIpAddress is linklocal address.')NEWLINEtftpFwTargetImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetImageFileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetImageFileName.setDescription('Configure firmware filename to download.')NEWLINEtftpFwTargetTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperation.setDescription('The tftp operates to perform downloading the firmware image to the unit. This object is used in conjunction with configBootTftpServerIp and configBootImageFileName.')NEWLINEtftpFwTargetTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 9, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperationStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpFwTargetTftpOperationStatus.setDescription('The tftp operation status represent firmware backup or upgrade status.')NEWLINEtftpCfgTargetGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10))NEWLINEtftpCfgTargetServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 1), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpAddress.setDescription("The TFTP server's IP address is used to upload or download configuration file.")NEWLINEtftpCfgTargetServerIpType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetServerIpType.setDescription('Type of IP interface.')NEWLINEtftpCfgTargetInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetInterfaceName.setDescription('Specifies the interface name when the tftpCfgTargetServerIpAddress is linklocal address.')NEWLINEtftpCfgTargetImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetImageFileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetImageFileName.setDescription('The configuration filename is used to store or retrieve config from the tftp server.')NEWLINEtftpCfgTargetTftpOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("download", 1), ("upload", 2), ("progressing", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperation.setDescription('The tftp operates to perform either downloading the configuration file to the unit or uploading the current configuration file to the tftp server. This object is used in conjunction with configTftpServerIpAddress and configTftpServerFileName.')NEWLINEtftpCfgTargetTftpOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperationStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpOperationStatus.setDescription('The tftp operation status represent configuration file backup or restore status.')NEWLINEtftpCfgTargetTftpConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("configId-1", 1), ("configId-2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpConfigID.setDescription('The tftp config ID determine which config what you need.')NEWLINEtftpCfgTargetTftpIncrement = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 3, 10, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("false", 0), ("true", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpIncrement.setStatus('current')NEWLINEif mibBuilder.loadTexts: tftpCfgTargetTftpIncrement.setDescription('The tftp increment determine download config behavior.')NEWLINEmiscReset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("reset", 1), ("noop", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: miscReset.setStatus('current')NEWLINEif mibBuilder.loadTexts: miscReset.setDescription('Physically resets the unit - use with care. A (1) resets the unit, a (2) does nothing.')NEWLINEmiscStatisticsReset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 4, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("reset", 1), ("noop", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: miscStatisticsReset.setStatus('current')NEWLINEif mibBuilder.loadTexts: miscStatisticsReset.setDescription('Resets the units statistics. A (1) resets the statistics count, a (2) does nothing.')NEWLINEsecurityIpMacPortBinding = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10))NEWLINEimpbSettingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1), )NEWLINEif mibBuilder.loadTexts: impbSettingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbSettingTable.setDescription('A table to control IP-MAC-Port Binding Setting features of the device.')NEWLINEimpbSettingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbPortIndex"))NEWLINEif mibBuilder.loadTexts: impbSettingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbSettingEntry.setDescription('An entry appears in IP-MAC-Port Binding Setting table for each interface in the system.')NEWLINEimpbPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortIndex.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEimpbPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortState.setDescription('Disable / enable IP-MAC-Port Binding admin state for the interface.')NEWLINEimpbPortDHCPSnoopingState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPSnoopingState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPSnoopingState.setDescription('Disable / enable IP-MAC-Port Binding DHCP snooping state for the interface.')NEWLINEimpbPortArpInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("disabled", 0), ("strict", 1), ("loose", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortArpInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortArpInspectionState.setDescription('Set IP-MAC-Port Binding ARP Inspection state for the interface.')NEWLINEimpbPortIpInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortIpInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortIpInspectionState.setDescription('Set IP-MAC-Port Binding IP Inspection state for the interface.')NEWLINEimpbPortAllowZeroIPState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortAllowZeroIPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortAllowZeroIPState.setDescription('Disable / enable IP-MAC-Port Binding Allow-Zero-IP state for the interface.')NEWLINEimpbPortForwardDHCPPktState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortForwardDHCPPktState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortForwardDHCPPktState.setDescription('Disable / enable IP-MAC-Port Binding Forward-DHCP-Packet state for the interface.')NEWLINEimpbPortDHCPMaxEntryIPv4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv4.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv4.setDescription('Set the maximum number of IPv4 entries that can be learned for the interface.')NEWLINEimpbPortDHCPMaxEntryIPv6 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv6.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPMaxEntryIPv6.setDescription('Set the maximum number of IPv6 entries that can be learned for the interface.')NEWLINEimpbPortNDInspectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortNDInspectionState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortNDInspectionState.setDescription('Set IP-MAC-Port Binding ND Inspection state for the interface.')NEWLINEimpbPortProtocolState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("ipv4", 0), ("ipv6", 1), ("all", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortProtocolState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortProtocolState.setDescription('Set IP-MAC-Port Binding protocol state for the interface.')NEWLINEimpbPortDHCPv4SetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4SetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4SetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEimpbPortDHCPv4VlanList1k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 14), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCP snooping, the bit corresponding to that VLAN is set to '1'. ")NEWLINEimpbPortDHCPv4VlanList2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 15), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv4VlanList3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 16), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv4VlanList4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 17), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv4VlanList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv4 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6SetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 18), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6SetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6SetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEimpbPortDHCPv6VlanList1k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 19), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCP snooping, the bit corresponding to that VLAN is set to '1'. ")NEWLINEimpbPortDHCPv6VlanList2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 20), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6VlanList3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 21), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbPortDHCPv6VlanList4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 1, 1, 22), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbPortDHCPv6VlanList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this DHCPv6 snooping, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4094.")NEWLINEimpbAutoScanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2), )NEWLINEif mibBuilder.loadTexts: impbAutoScanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanTable.setDescription('A table to control auto scan features of the device.')NEWLINEimpbAutoScanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbAutoScanMacAddress"), (0, "DES-1210-28MEbx", "impbAutoScanPort"), (0, "DES-1210-28MEbx", "impbAutoScanIpAddress"))NEWLINEif mibBuilder.loadTexts: impbAutoScanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanEntry.setDescription('An entry appears in auto scan table for each interface in the system.')NEWLINEimpbAutoScanMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanMacAddress.setDescription('The MAC address associated of the auto scan entry.')NEWLINEimpbAutoScanPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanPort.setDescription('The port number of the auto scan entry. For all machines give maximum port number.')NEWLINEimpbAutoScanIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 3), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddress.setDescription('The IP address associated of the auto scan entry.')NEWLINEimpbAutoScanVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanVlanId.setDescription('The VLAN ID of the auto scan entry.')NEWLINEimpbAutoScanBinding = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanBinding.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanBinding.setDescription('Disable / enable IP-MAC-Port Binding for the entry.')NEWLINEimpbBindingListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3), )NEWLINEif mibBuilder.loadTexts: impbBindingListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListTable.setDescription('A table to control Manual IP-MAC-Port Binding white list features of the device.')NEWLINEimpbBindingListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbBindingListIpAddress"), (0, "DES-1210-28MEbx", "impbBindingListMacAddress"))NEWLINEif mibBuilder.loadTexts: impbBindingListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListEntry.setDescription('An entry appears in Manual IP-MAC-Port Binding white list table for each interface in the system.')NEWLINEimpbBindingListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 1), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBindingListIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListIpAddress.setDescription('The IP address associated of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBindingListMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListMacAddress.setDescription('The MAC address associated of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBindingListPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListPort.setDescription('The port number of the Manual IP-MAC-PORT Binding white list entry.')NEWLINEimpbBindingListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: impbBindingListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingListRowStatus.setDescription('The status of a row in impbBindingListTable. By setting this object, new entries can be created in impbBindingListTable and existing entries can be removed from impbBindingListTable. It can be used as specified in the SNMP v2 standard.')NEWLINEimpbBlockListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4), )NEWLINEif mibBuilder.loadTexts: impbBlockListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListTable.setDescription('A table to control IP-MAC-Port Binding black list of the device.')NEWLINEimpbBlockListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbBlockListMacAddress"), (0, "DES-1210-28MEbx", "impbBlockListVlanId"), (0, "DES-1210-28MEbx", "impbBlockListPort"))NEWLINEif mibBuilder.loadTexts: impbBlockListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListEntry.setDescription('An entry appears in Manual IP-MAC-Port Binding black list table for each interface in the system.')NEWLINEimpbBlockListMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListMacAddress.setDescription('The MAC address associated of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListVlanId.setDescription('The VLAN ID of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListPort.setDescription('The port number of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 4), DisplayString().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbBlockListIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListIpAddress.setDescription('The IP address associated of the IP-MAC-PORT Binding black list entry.')NEWLINEimpbBlockListStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 4, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("nothing", 0), ("deleted", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBlockListStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBlockListStatus.setDescription('nothing/delete IP-MAC-Port Binding for the interface.')NEWLINEimpbAutoScanIpAddressFrom = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 5), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressFrom.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressFrom.setDescription('The begin for IP address associated of the IP-MAC-PORT Binding auto scan entry.')NEWLINEimpbAutoScanIpAddressTo = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 6), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressTo.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanIpAddressTo.setDescription('The end for IP address associated of the IP-MAC-PORT Binding auto scan entry.')NEWLINEimpbAutoScanStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("nothing", 0), ("scan", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbAutoScanStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanStatus.setDescription('Nothing / scan IP-MAC-Port Binding auto scan for the interface.')NEWLINEimpbDhcpSnoopingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8), )NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingTable.setDescription('A table to display DHCP snooping entries of the device.')NEWLINEimpbDhcpSnoopingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1), ).setIndexNames((0, "DES-1210-28MEbx", "impbDhcpSnoopingMacAddress"), (0, "DES-1210-28MEbx", "impbDhcpSnoopingIpAddress"))NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingEntry.setDescription('An entry appears in DHCP snooping table for each interface in the system.')NEWLINEimpbDhcpSnoopingMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 1), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingMacAddress.setDescription('The MAC address associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 2), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingIpAddress.setDescription('The IP address associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingLeaseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingLeaseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingLeaseTime.setDescription('The lease time associated of the DHCP snooping entry.')NEWLINEimpbDhcpSnoopingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 8, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDhcpSnoopingPort.setDescription('The port number associated of the DHCP snooping entry.')NEWLINEimpbRoamingState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbRoamingState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbRoamingState.setDescription('Disable / enable IP-MAC-Port Binding roaming state.')NEWLINEimpbVlanModeState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbVlanModeState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbVlanModeState.setDescription('Disable / enable IP-MAC-Port Binding vlan mode state.')NEWLINEimpbVlanModeVlanList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 11), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbVlanModeVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbVlanModeVlanList.setDescription('IP-MAC-Port Binding vlan mode VID list.')NEWLINEimpbLogState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("disabled", 0), ("ipv4", 1), ("ipv6", 2), ("all", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbLogState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbLogState.setDescription('Configure IP-MAC-Port Binding log state.')NEWLINEimpbDHCPv6PrefixDelegationSnoopState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbDHCPv6PrefixDelegationSnoopState.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbDHCPv6PrefixDelegationSnoopState.setDescription('Configure DHCPv6 PD snooping state.')NEWLINEimpbBindingtraplog = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 1))).clone(namedValues=NamedValues(("disabled", 2), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: impbBindingtraplog.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingtraplog.setDescription('This object is for enabling or disabling topology change event trap in the system.')NEWLINEimpbBindingtrap = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 15))NEWLINEimpbBindingtrapsign = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 15, 1))NEWLINEif mibBuilder.loadTexts: impbBindingtrapsign.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbBindingtrapsign.setDescription('The object is for IMPB trap sign in the system.')NEWLINEimpbAutoScanCurrentStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 10, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("stop", 0), ("scanning", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: impbAutoScanCurrentStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: impbAutoScanCurrentStatus.setDescription('Show Auto scan status')NEWLINEstpBridgeGlobal = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1))NEWLINEstpModuleStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpModuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpModuleStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEstpProtocolVersion = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("stp", 1), ("rstp", 2), ("mstp", 3))).clone('mstp')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpProtocolVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpProtocolVersion.setDescription("The version of Spanning Tree Protocol the bridge is currently running. The value 'stpCompatible(0)' indicates the Spanning Tree Protocol specified in IEEE 802.1D and 'rstp(2)' indicates the Rapid Spanning Tree Protocol specified in IEEE 802.1w and 'mstp(3)' indicates the Multiple Spanning Tree Protocol Specified in IEEE 802.1s.")NEWLINEstpBridgePriority = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgePriority.setDescription('The Value of the writable portion of the Bridge Identifier comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEstpTxHoldCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(3)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpTxHoldCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpTxHoldCount.setDescription('The value used by the Port Transmit state machine to limit the maximum transmission rate.')NEWLINEstpBridgeMaxAge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 5), Timeout().subtype(subtypeSpec=ValueRangeConstraint(600, 4000)).clone(2000)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeMaxAge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeMaxAge.setDescription('The value that all bridges use for MaxAge when this bridge is acting as the root. The granularity of this timer is specified to be 1 second. An agent may return a badValue error if a set is attempted to a value which is not a whole number of seconds.')NEWLINEstpBridgeHelloTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 6), Timeout().subtype(subtypeSpec=ValueRangeConstraint(100, 1000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeHelloTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeHelloTime.setDescription('The amount of time between the transmission of Configuration bridge PDUs by this node in units of hundredths of a second.')NEWLINEstpBridgeForwardDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 7), Timeout().subtype(subtypeSpec=ValueRangeConstraint(400, 3000)).clone(1500)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpBridgeForwardDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpBridgeForwardDelay.setDescription('The value that all bridges use for ForwardDelay when this bridge is acting as the root. Note that 802.1D specifies that the range for this parameter is related to the value of BridgeMaxAge. The granularity of this timer is specified to be 1 second. An agent may return a badValue error if a set is attempted to a value which is not a whole number of seconds.')NEWLINEstpFowardBPDU = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpFowardBPDU.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpFowardBPDU.setDescription('This object is for enabling or disabling forward BPDU.')NEWLINEstpRootBridge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 9), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootBridge.setDescription('The bridge identifier of the Root of the common spanning tree as determined by the Spanning Tree Protocol as executed by this node. This value is used as the CIST Root Identifier parameter in all Configuration Bridge PDUs originated by this node.')NEWLINEstpRootCost = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 10), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootCost.setDescription('The Cost of the path to the CIST Root as seen from this bridge.')NEWLINEstpMaxAge = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 11), Timeout()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpMaxAge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpMaxAge.setDescription('The maximum age of Spanning Tree Protocol information learned from the network on any port before it is discarded, in units of hundredths of a second. This is the actual value that this bridge is currently using.')NEWLINEstpForwardDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 12), Timeout()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpForwardDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpForwardDelay.setDescription('This time value, measured in units of hundredths of a second, controls how fast a port changes its spanning state when moving towards the Forwarding state. The value determines how long the port stays in a particular state before moving to the next state.')NEWLINEstpRootPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 13), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpRootPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpRootPort.setDescription('The Port Number of the Port which offers the lowest path cost from this bridge to the CIST Root Bridge.')NEWLINEstpTopologyChangeTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpTopologyChangeTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpTopologyChangeTrapStatus.setDescription('This object is for enabling or disabling topology change event trap in the system.')NEWLINEstpNewRootTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpNewRootTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpNewRootTrapStatus.setDescription('This object is for enabling or disabling new root event trap in the system.')NEWLINEstpNewRootTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16))NEWLINEbrgAddress = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 1))NEWLINEif mibBuilder.loadTexts: brgAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: brgAddress.setDescription('The MAC address used by this bridge when it must be referred to in a unique fashion.')NEWLINEoldDesignatedRoot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 2))NEWLINEif mibBuilder.loadTexts: oldDesignatedRoot.setStatus('current')NEWLINEif mibBuilder.loadTexts: oldDesignatedRoot.setDescription('The bridge identifier of the old root of the spanning tree instance as determined by the Spanning Tree Protocol as executed by this node.')NEWLINEmstiBridgeRegionalRoot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 1, 16, 3))NEWLINEif mibBuilder.loadTexts: mstiBridgeRegionalRoot.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiBridgeRegionalRoot.setDescription('MSTI Regional Root Identifier value for the Instance.')NEWLINEstpPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2), )NEWLINEif mibBuilder.loadTexts: stpPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortTable.setDescription('A table that contains port-specific information for the Spanning Tree Protocol.')NEWLINEstpPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "stpPort"))NEWLINEif mibBuilder.loadTexts: stpPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortEntry.setDescription('A list of information maintained by every port about the Spanning Tree Protocol state for that port.')NEWLINEstpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEstpPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 0)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortStatus.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for ALL spanning tree instances. Setting this object will override the port's status in any of the MSTI contexts")NEWLINEstpPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortPriority.setDescription('The four most significant bits of the Port Identifier of the Spanning Tree instance can be modified by setting the CistPortPriority value. The values that are set for Port Priority must be in steps of 16.')NEWLINEstpAdminPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setReference('IEEE 802.1D-2004')NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpAdminPortPathCost.setDescription("The contribution of this port to the path cost of paths towards the spanning tree root which include this port. Writing a value of '0' assigns the automatically calculated default Path Cost value to the ohter object stpPortPathCost. If the default Path Cost is being used,this object returns '0' when read.")NEWLINEstpPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the CIST Root which include this port.')NEWLINEstpPortProtocolMigration = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("false", 0), ("true", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortProtocolMigration.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortProtocolMigration.setDescription('Indicates the Protocol migration state of this Port. When operating in RSTP/MSTP (version >= 2) mode, writing TRUE(1) to this object forces this port to transmit MSTP BPDUs without instance information. Any other operation on this object has no effect and it always returns FALSE(2) when read.')NEWLINEstpPortEdge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 0), ("auto", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortEdge.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortEdge.setDescription(' This parameter when TRUE(1) indicates that detection of a port as Edge Port happens automatically and FALSE(2) indicates that this feature is disabled.')NEWLINEstpPortAdminP2P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("forceTrue", 0), ("forceFalse", 1), ("auto", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortAdminP2P.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortAdminP2P.setDescription('The administrative point-to-point status of the LAN segment attached to this port. A value of forceTrue(0) indicates that this port should always be treated as if it is connected to a point-to-point link. A value of forceFalse(1) indicates that this port should be treated as having a shared media connection. A value of auto(2) indicates that this port is considered to have a point-to-point link if it is an Aggregator and all of its members are aggregatable, or if the MAC entity is configured for full duplex operation, either through auto-negotiation or by management means.')NEWLINEstpPortRestrictedRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 9), TruthValue()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortRestrictedRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortRestrictedRole.setDescription("A Boolean value set by management. If TRUE causes the Port not to be selected as Root Port for the CIST or any MSTI, even it has the best spanning tree priority vector. Such a Port will be selected as an Alternate Port after the Root Port has been selected. This parameter should be FALSE by default. If set it can cause lack of spanning tree connectivity. It is set by a network administrator to prevent bridges external to a core region of the network influencing the spanning tree active topology, possibly because those bridges are not under the full control of the administrator. This administrator configuration is also known as 'Root Guard'.")NEWLINEstpPortRestrictedTCN = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 10), TruthValue()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortRestrictedTCN.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortRestrictedTCN.setDescription('A Boolean value set by management. If TRUE causes the Port not to propagate received topology change notifications and topology changes to other Ports. This parameter should be FALSE by default. If set it can cause temporary loss of connectivity after changes in a spanning trees active topology as a result of persistent incorrectly learnt station location information. It is set by a network administrator to prevent bridges external to a core region of the network causing address flushing in that region, possibly because those bridges are not under the full control of the administrator or MAC_Operational for the attached LANs transitions frequently.')NEWLINEstpPortHelloTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 11), Timeout().subtype(subtypeSpec=ValueRangeConstraint(100, 1000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortHelloTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortHelloTime.setDescription('The amount of time between the transmission of Configuration bridge PDUs by this node in units of hundredths of a second.')NEWLINEstpPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 4, 5))).clone(namedValues=NamedValues(("disabled", 1), ("discarding", 2), ("learning", 4), ("forwarding", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: stpPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortState.setDescription('Current state of the Port as defined by the Common spanning tree protocol.')NEWLINEstpPortFowardBPDU = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setReference('IEEE 802.1D-2004')NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setStatus('current')NEWLINEif mibBuilder.loadTexts: stpPortFowardBPDU.setDescription('This object is for enabling or disabling forward BPDU.')NEWLINEmstConfigurationIdentification = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3))NEWLINEmstiConfigurationName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstiConfigurationName.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiConfigurationName.setDescription("The Name for the Region's configuration. By Default Region Name will be equal to the Bridge Mac Address.")NEWLINEmstiRevisionLevel = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstiRevisionLevel.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstiRevisionLevel.setDescription('Version of the MST Region.')NEWLINEmstCistVlanMapped = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'.")NEWLINEmstCistVlanMapped2k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1024 through 2047. The first octet corresponds to VLANs with VlanIndex values 1024 through 1031; the second octet to VLANs 1032 through 1039 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstCistVlanMapped3k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2048 through 3071. The first octet corresponds to VLANs with VlanIndex values of 2048 through 2055; the second octet to VLANs 2056 through 2063 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstCistVlanMapped4k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistVlanMapped4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3072 through 4095. The first octet corresponds to VLANs with VlanIndex values 3072 through 3079; the second octet to VLANs 3080 through 3087 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstVlanMstiMappingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7), )NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingTable.setDescription('This table contains one entry for each instance of MSTP. This table maintains context ID as one more index to support Multiple Instances.')NEWLINEmstVlanMstiMappingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstVlanMstiMappingEntry.setDescription('A conceptual row containing the status of the MSTP instance.')NEWLINEmstInstanceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceIndex.setDescription('An arbitrary integer within the range from 1 to the value of Max Instance Number that uniquely identifies an instance.')NEWLINEmstSetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstSetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstSetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to map for this Instance. If the VlanId to Instance Mapping has to be known then any one of the VlanMapped object should be used.If a vlan is already mapped to this Instance, it may not be mapped again. This object is used only for SET operation. GET Operation returns null values.')NEWLINEmstResetVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstResetVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstResetVlanList.setDescription('A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. The set of vlans configured by management to unmap from this Instance. A vlan may not be unmapped from this instance if it is not already mapped to this Instance. This object is used only for SET operation.GET Operation returns null values.')NEWLINEmstInstanceVlanMapped = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'.")NEWLINEmstInstanceVlanMapped2k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped2k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1024 through 2047. The first octet corresponds to VLANs with VlanIndex values 1024 through 1031; the second octet to VLANs 1032 through 1039 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstInstanceVlanMapped3k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2048 through 3071. The first octet corresponds to VLANs with VlanIndex values of 2048 through 2055; the second octet to VLANs 2056 through 2063 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEmstInstanceVlanMapped4k = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 3, 7, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstInstanceVlanMapped4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3072 through 4095. The first octet corresponds to VLANs with VlanIndex values 3072 through 3079; the second octet to VLANs 3080 through 3087 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this MSTP instance, the bit corresponding to that VLAN is set to '1'. This object is only instantiated on devices with support for VlanIndex values up to 4095.")NEWLINEstpInstance = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4))NEWLINEmstCistBridgePriority = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistBridgePriority.setDescription('The writable portion of the MSTI Bridge Identifier. comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEmstCistStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEmstMstiBridgeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3), )NEWLINEif mibBuilder.loadTexts: mstMstiBridgeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgeTable.setDescription('Table containing Bridge Information specific to Spanning Tree Instance. This table maintains context ID as one more index to support Multiple Instances.')NEWLINEmstMstiBridgeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstMstiInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstMstiBridgeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgeEntry.setDescription('Entry indicating the Bridge Information.')NEWLINEmstMstiInstanceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiInstanceIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiInstanceIndex.setDescription('Spanning Tree Instance to which the information belongs.')NEWLINEmstMstiBridgePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 61440)).clone(32768)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiBridgePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiBridgePriority.setDescription('The writable portion of the MSTI Bridge Identifier. comprising of the first two octets. The values that are set for Bridge Priority must be in steps of 4096.')NEWLINEmstMstiStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 4, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiStatus.setDescription('The administrative status requested by management for the MST feature. The value enabled(1) indicates that Mst should be enabled in the device on all ports. The value disabled(2) indicates that Mst should be disabled in the device on all ports. The object can be set to enabled(1) if and only if, fsMIMstSystemControl set to start.')NEWLINEstpInstancePortTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5))NEWLINEmstCistPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1), )NEWLINEif mibBuilder.loadTexts: mstCistPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortTable.setDescription('This table contains Common Spanning Tree Port Information.')NEWLINEmstCistPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstCistPort"))NEWLINEif mibBuilder.loadTexts: mstCistPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortEntry.setDescription('A list of information maintained by every port for Common Spanning tree.')NEWLINEmstCistPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))NEWLINEif mibBuilder.loadTexts: mstCistPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEmstCistPortDesignatedBridge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 2), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistPortDesignatedBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortDesignatedBridge.setDescription("The unique Bridge Identifier of the bridge which this port considers to be the Designated Bridge for the port's segment.")NEWLINEmstCistPortAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortAdminPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortAdminPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstCistPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstCistPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstCistPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistPortPriority.setDescription('The four most significant bits of the Port Identifier for a given Spanning Tree instance can be modified independently for each Spanning Tree instance supported by the Bridge. The values that are set for Port Priority must be in steps of 16.')NEWLINEmstCistForcePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistForcePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistForcePortState.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for the specific spanning tree instance. This object can be set to enabled only if the 'fsMIMstCistForcePortState' is set to 'enabled' for this port")NEWLINEmstCistCurrentPortRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("disabled", 0), ("alternate", 1), ("backup", 2), ("root", 3), ("designated", 4), ("master", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstCistCurrentPortRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstCistCurrentPortRole.setDescription('Current Port Role of the port for this spanning tree instance.')NEWLINEmstMstiPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2), )NEWLINEif mibBuilder.loadTexts: mstMstiPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortTable.setDescription('This table contains Spanning Tree Instance Specific Port Information.')NEWLINEmstMstiPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mstMstiPort"), (0, "DES-1210-28MEbx", "mstInstanceIndex"))NEWLINEif mibBuilder.loadTexts: mstMstiPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortEntry.setDescription('A list of information maintained by every port for each and every spanning tree instance.')NEWLINEmstMstiPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))NEWLINEif mibBuilder.loadTexts: mstMstiPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPort.setDescription('The Port number of the port for which this entry contains spanning tree information.')NEWLINEmstMstiPortDesignatedBridge = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 2), BridgeId()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiPortDesignatedBridge.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortDesignatedBridge.setDescription("The unique Bridge Identifier of the bridge which this port considers to be the Designated Bridge for the port's segment.")NEWLINEmstMstiPortAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortAdminPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortAdminPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstMstiPortPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 200000000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortPathCost.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortPathCost.setDescription('The contribution of this port to the path cost of paths towards the MSTI Root which include this port.')NEWLINEmstMstiPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 240)).clone(128)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mstMstiPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiPortPriority.setDescription('The four most significant bits of the Port Identifier for a given Spanning Tree instance can be modified independently for each Spanning Tree instance supported by the Bridge. The values that are set for Port Priority must be in steps of 16.')NEWLINEmstMstiForcePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiForcePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiForcePortState.setDescription("Current state of the Port which can be changed to either Disabled or Enabled for the specific spanning tree instance. This object can be set to enabled only if the 'fsMIMstCistForcePortState' is set to 'enabled' for this port")NEWLINEmstMstiCurrentPortRole = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 6, 5, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("disabled", 0), ("alternate", 1), ("backup", 2), ("root", 3), ("designated", 4), ("master", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mstMstiCurrentPortRole.setStatus('current')NEWLINEif mibBuilder.loadTexts: mstMstiCurrentPortRole.setDescription('Current Port Role of the port for this spanning tree instance.')NEWLINEstaticMcastTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1), )NEWLINEif mibBuilder.loadTexts: staticMcastTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastTable.setDescription('A list of the Static MACs')NEWLINEstaticMcastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticMcastVlanID"), (0, "DES-1210-28MEbx", "staticMcastMac"), (0, "DES-1210-28MEbx", "staticMcastEgressPorts"), (0, "DES-1210-28MEbx", "staticMcastIpAddr"))NEWLINEif mibBuilder.loadTexts: staticMcastEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticMcastVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastVlanID.setDescription('The VLAN ID of the static MAC entry.')NEWLINEstaticMcastMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastMac.setDescription('The MAC address associated of the static MAC entry.')NEWLINEstaticMcastEgressPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 3), PortList().subtype(subtypeSpec=ValueSizeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastEgressPorts.setDescription('The set of ports to which frames received from a specific port and destined for a specific Multicast or Broadcast MAC address must be forwarded, regardless of any dynamic information e.g. from GMRP. A port may not be added in this set if it is already a member of the set of ports in dot1qStaticMulticastForbiddenEgressPorts. The default value of this object is a string of ones of appropriate length.')NEWLINEstaticMcastIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 4), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMcastIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastIpAddr.setDescription('Static Multicast IP Address.')NEWLINEstaticMcastStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 19, 1, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticMcastStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMcastStatus.setDescription('The status of an entry in the Static Mcast Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEdot1qVlanManagementOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementOnOff.setDescription('Enable/Disable management VLAN mechanism.')NEWLINEdot1qVlanManagementid = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 3), Integer32().clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementid.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanManagementid.setDescription('The management VLAN ID, which will allow to forward packets of that VLAN to CPU.')NEWLINEdot1qVlanAsyOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanAsyOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanAsyOnOff.setDescription('Enable/Disable IEEE 802.1Q Asymmetric VLAN')NEWLINEdot1qVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6), )NEWLINEif mibBuilder.loadTexts: dot1qVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanTable.setDescription('A table containing static configuration information for each VLAN configured into the device by (local or network) management. All entries are permanent and will be restored after the device is reset.')NEWLINEdot1qVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dot1qVlanName"))NEWLINEif mibBuilder.loadTexts: dot1qVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanEntry.setDescription('Information for a VLAN configured into the device by (local or network) management.')NEWLINEdot1qVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setReference('IEEE 802.1Q/D11 Section 12.10.2.1')NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanName.setDescription('An administratively assigned string, which may be used to identify the VLAN.')NEWLINEdot1qVlanEgressPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 2), PortList()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanEgressPorts.setDescription('The set of ports which are permanently assigned to the egress list for this VLAN by management. Changes to a bit in this object affect the per-port per-VLAN Registrar control for Registration Fixed for the relevant GVRP state machine on each port. A port may not be added in this set if it is already a member of the set of ports in dot1qVlanForbiddenEgressPorts. The default value of this object is a string of zeros of appropriate length, indicating not fixed.')NEWLINEdot1qVlanForbiddenPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setReference('IEEE 802.1Q/D11 Section 12.7.7.3, 11.2.3.2.3')NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanForbiddenPorts.setDescription('The set of ports which are prohibited by management from being included in the egress list for this VLAN. Changes to this object that cause a port to be included or excluded affect the per-port per-VLAN Registrar control for Registration Forbidden for the relevant GVRP state machine on each port. A port may not be added in this set if it is already a member of the set of ports in dot1qVlanEgressPorts. The default value of this object is a string of zeros of appropriate length, excluding all ports from the forbidden set.')NEWLINEdot1qVlanUntaggedPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 4), PortList()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setReference('IEEE 802.1Q/D11 Section 12.10.2.1')NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanUntaggedPorts.setDescription('The set of ports which should transmit egress packets for this VLAN as untagged. The default value of this object for the default VLAN (dot1qVlanIndex = 1) is a string of appropriate length including all ports. There is no specified default for other VLANs. If a device agent cannot support the set of ports being set then it will reject the set operation with an error. An example might be if a manager attempts to set more than one VLAN to be untagged on egress where the device does not support this IEEE 802.1Q option.')NEWLINEdot1qVlanAdvertisementStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanAdvertisementStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanAdvertisementStatus.setDescription('Enable/Disable Advertisement Status of the IEEE 802.1Q VLAN.')NEWLINEdot1qVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 6, 1, 6), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dot1qVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanRowStatus.setDescription('The status of a row in dot1qVlanTable. By setting this object, new entries can be created in dot1qVlanTable and existing entries can be removed from dot1qVlanTable. It can be used as specified in the SNMP v2 standard.')NEWLINEdot1qVlanPVIDAutoAssignOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 7, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dot1qVlanPVIDAutoAssignOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: dot1qVlanPVIDAutoAssignOnOff.setDescription('Enable/Disable VLAN PVID auto assignment')NEWLINEgvrpGVRPGlobalSettingsOnOff = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpGVRPGlobalSettingsOnOff.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpGVRPGlobalSettingsOnOff.setDescription('Enable/Disable GVRP mechanism.')NEWLINEgvrpSettingsJoinTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsJoinTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsJoinTime.setDescription('The Join Time value assigned to this Join Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsLeaveTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveTime.setDescription('The Leave Time value assigned to this Leave Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsLeaveAllTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 100000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveAllTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsLeaveAllTime.setDescription('The Leave_All Time value assigned to this Leave_All Time field. This 16-bit value is read-write.')NEWLINEgvrpSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5), )NEWLINEif mibBuilder.loadTexts: gvrpSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsTable.setDescription('A table containing static configuration information for each GVRP configured into the device by (local or network) management. All entries are permanent and will be restored after the device is reset.')NEWLINEgvrpSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "gvrpSettingsPortControlIndex"))NEWLINEif mibBuilder.loadTexts: gvrpSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsEntry.setDescription('Information for a GVRP configured into the device by (local or network) management.')NEWLINEgvrpSettingsPortControlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: gvrpSettingsPortControlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsPortControlIndex.setDescription('The index of the port.')NEWLINEgvrpSettingsPVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsPVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsPVID.setDescription('The PVID value assigned to this Aggregation Port. This 16-bit value is read-write.')NEWLINEgvrpSettingsGVRPState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsGVRPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsGVRPState.setDescription('Enable/Disable GVRP State to this Aggregation Port.')NEWLINEgvrpSettingsIngressChecking = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsIngressChecking.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsIngressChecking.setDescription('Enable/Disable Ingress Checking mechanism of GVRP to this Aggregation Port.')NEWLINEgvrpSettingsAcceptableFrameType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 11, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allFrames", 1), ("taggedOnly", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: gvrpSettingsAcceptableFrameType.setStatus('current')NEWLINEif mibBuilder.loadTexts: gvrpSettingsAcceptableFrameType.setDescription('Chose types All Frames/Tagged to this Aggregation Port.')NEWLINEdhcpBOOTPRelayControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1))NEWLINEdhcpBOOTPRelayManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2))NEWLINEdhcpBOOTPRelayManagementOption82 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2))NEWLINEdhcpBOOTPRelayState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayState.setDescription('This object indicates DHCP relay function is enabled or disabled.')NEWLINEdhcpBOOTPRelayHopCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayHopCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayHopCount.setDescription('This object indicates the maximum number of router hops that the BOOTP packets can cross.')NEWLINEdhcpBOOTPRelayTimeThreshold = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayTimeThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayTimeThreshold.setDescription('This object indicates the minimum time in seconds within which the switch must relay the DHCP request. If this time is exceeded, the switch will drop the DHCP packet.')NEWLINEdhcpBOOTPRelayEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayEnablePortlist.setDescription('This object indicates DHCP relay function is enabled or disabled by portlist.')NEWLINEdhcpRelayVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5), )NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpRelayVlanTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpRelayVlanSettingsVLANID"))NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTableEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanTableEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpRelayVlanSettingsVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsVLANID.setDescription('This object displays the current VLAN ID of the device.')NEWLINEdhcpRelayVlanSettingsState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 1, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpRelayVlanSettingsState.setDescription('This object indicates DHCP relay function of VLAN is enabled or disabled.')NEWLINEdhcpBOOTPRelayInterfaceSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1), )NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpBOOTPRelayInterfaceSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpBOOTPRelayInterface"), (0, "DES-1210-28MEbx", "dhcpBOOTPRelayServerIP"))NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpBOOTPRelayInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterface.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterface.setDescription('This object indicates the name of the IP interface.')NEWLINEdhcpBOOTPRelayServerIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayServerIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayServerIP.setDescription('This object indicates the DHCP server IP address.')NEWLINEdhcpBOOTPRelayInterfaceSettingsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayInterfaceSettingsRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEdhcpBOOTPRelayOption82State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82State.setDescription('This object indicates DHCP relay option 82 function is enabled or disabled.')NEWLINEdhcpBOOTPRelayOption82CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CheckState.setDescription('This object indicates DHCP relay option 82 Check function is enabled or disabled.')NEWLINEdhcpBOOTPRelayOption82Policy = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("replace", 1), ("drop", 2), ("keep", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82Policy.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82Policy.setDescription('This object indicates DHCP relay option 82 policy.')NEWLINEdhcpBOOTPRelayOption82RemoteIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("default", 1), ("userdefined", 2), ("userdefinedhex", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteIDType.setDescription('This object indicates the type of remote ID. If the type is default, the remote ID will be the MAC address of the device, otherwise, the remote ID can be defined by writing to the swDHCPRelayOption82RemoteID object.')NEWLINEdhcpBOOTPRelayOption82RemoteID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 5), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82RemoteID.setDescription('This object displays the current remote ID of the device. If swDHCPRelayOption82RemoteIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If swDHCPRelayOption82RemoteIDType is set to user-defined or user-defined-hex, a new value can be written to this object.')NEWLINEdhcpBOOTPRelayOption82CircuitIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("default", 1), ("userdefined", 2), ("userdefinedhex", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitIDType.setDescription('This object indicates the type of remote ID. If the type is default, the circuit ID will be blank, otherwise, the circuit ID can be defined by writing to the dhcpBOOTPRelayOption82CircuitID object.')NEWLINEdhcpBOOTPRelayOption82CircuitID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 28, 2, 2, 8), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpBOOTPRelayOption82CircuitID.setDescription('This object displays the current remote ID of the device. If dhcpBOOTPRelayOption82CircuitIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If dhcpBOOTPRelayOption82CircuitIDType is set to user-defined or user-defined-hex, a new value can be written to this object.')NEWLINEdhcpLocalRelayGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayGlobalState.setDescription('This object indicates DHCP local relay function of VLAN is enabled or disabled.')NEWLINEdhcpLocalRelayTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2), )NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTable.setDescription('This table indicates the IP address as a destination to forward (local relay) DHCP packets to.')NEWLINEdhcpLocalRelayTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpLocalRelaySettingsVLANID"))NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTableEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayTableEntry.setDescription('A list of information indicates the IP address as a destination to forward (local relay) DHCP packets to.')NEWLINEdhcpLocalRelaySettingsVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsVLANID.setDescription('This object displays the current VLAN ID of the device.')NEWLINEdhcpLocalRelaySettingsState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelaySettingsState.setDescription('This object indicates DHCP local relay function of VLAN is enabled or disabled.')NEWLINEdhcpLocalRelayEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 29, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpLocalRelayEnablePortlist.setDescription('This object indicates DHCP local relay function is enabled or disabled by portlist.')NEWLINElaSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1))NEWLINElaPortControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2))NEWLINEclass PortLaMode(TextualConvention, Integer32):NEWLINE description = 'Defines how a Port Channel does channeling. lacp(1) - place the port into passive negotiation state, in which the port waits for its peer to initiate negotiation. static(2) - force the port to enable channeling. disable(3) - channeling is disabled.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))NEWLINE namedValues = NamedValues(("lacp", 1), ("static", 2), ("disable", 3))NEWLINENEWLINEclass LacpKey(TextualConvention, Integer32):NEWLINE description = 'The Actor or Partner Key value (0..65535).'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 65535)NEWLINENEWLINElaStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: laStatus.setDescription('Sets the Link Aggregation Module administrative status as enabled or disabled.')NEWLINElaPortChannelTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3), )NEWLINEif mibBuilder.loadTexts: laPortChannelTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelTable.setDescription('A Port-channel is created through ifMain table. After the creation of the port-channel, corresponding logical interface will be created in the ifMain table. This Port-channel table is indexed through Key values and allows to configure link selection policy and the Mac address for the port-channel. All other objects in this table displays the details of the port-channel.')NEWLINElaPortChannelEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "laPortChannelIfIndex"))NEWLINEif mibBuilder.loadTexts: laPortChannelEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelEntry.setDescription('There is one entry in this table for each created port-channel port.')NEWLINElaPortChannelIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: laPortChannelIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelIfIndex.setDescription("The index of the port-channel(Aggregator's interface index). ")NEWLINElaPortChannelMemberList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMemberList.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMemberList.setDescription('Member Port list of the port channel. Add the ports as a aggregation member associated of a port-channel.')NEWLINElaPortChannelMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 3), PortLaMode()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMode.setDescription('Current Operating Channel Mode of the port channel Lacp(1) - forcing the port to negotiate with the partner. manual(2) - force the port to enable channeling (Manual). disable(3) - channeling is disabled.')NEWLINElaPortChannelMasterPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 3, 1, 4), InterfaceIndex()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortChannelMasterPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortChannelMasterPort.setDescription('The master port of the port-channel. ')NEWLINElaAlgorithm = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sourceMAC", 1), ("destMAC", 2), ("sourceAndDestMAC", 3), ("sourceIP", 4), ("destIP", 5), ("sourceAndDestIP", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laAlgorithm.setStatus('current')NEWLINEif mibBuilder.loadTexts: laAlgorithm.setDescription('Sets the Link Aggregation load balance algorithm.')NEWLINElaPortControlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1), )NEWLINEif mibBuilder.loadTexts: laPortControlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlTable.setDescription('A table that contains Link Aggregation Control configuration information about every Aggregation Port associated with this device. A row appears in this table for each physical port.')NEWLINElaPortControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "laPortControlIndex"))NEWLINEif mibBuilder.loadTexts: laPortControlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlEntry.setDescription('A list of Link Aggregation Control configuration parameters for each Aggregation Port on this device.')NEWLINElaPortControlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: laPortControlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortControlIndex.setDescription('The index of the port.')NEWLINElaPortActorPortPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorPortPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorPortPriority.setDescription('The priority value assigned to this Aggregation Port. This 16-bit value is read-write.')NEWLINElaPortActorActivity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("passive", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorActivity.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorActivity.setDescription('This object indicates LACP_Activity to this Aggregation Port. LACP can be configured in one of two modes: active or passive. In active mode it will always send frames along the configured links. If the actor and partner are both in passive mode, they do not exchange LACP packets.')NEWLINElaPortActorTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 8, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("short", 1), ("long", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: laPortActorTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: laPortActorTimeout.setDescription('This object indicates LACP_Timeout to this Aggregation Port. short(1) - LACP Timeout 3 seconds. long (2) - LACP Timeout 90 seconds.')NEWLINEstaticVlanBaseTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5))NEWLINEstaticDisableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("on", 1), ("off", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticDisableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticDisableAutoLearn.setDescription('Set on to disable Auto Learning Excluding Uplink Port and set off to enable Auto Learning.')NEWLINEstaticAutoLearningList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticAutoLearningList.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticAutoLearningList.setDescription("The set of the device's member ports that belong to the Static MAC auto learning enable/disable. For example, when Disable Auto Learning is enable, the octet value set up as '# 0x0F 0xFF 0xFF 0xFF' means from port 1 to port 4 are not in auto learning state, the other ports are in auto learning state. It can be set up when Disable Auto Learning is enable.")NEWLINEstaticTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3), )NEWLINEif mibBuilder.loadTexts: staticTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticTable.setDescription('A list of the Static MACs')NEWLINEstaticEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticVlanID"), (0, "DES-1210-28MEbx", "staticMac"), (0, "DES-1210-28MEbx", "staticPort"))NEWLINEif mibBuilder.loadTexts: staticEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanID.setDescription('The VLAN ID of the static MAC entry.')NEWLINEstaticMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 2), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticMac.setDescription('The MAC address associated of the static MAC entry.')NEWLINEstaticPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticPort.setDescription('The forwarding port of the static MAC entry. For all machines give maximum port number.')NEWLINEstaticStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 3, 1, 4), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticStatus.setDescription('The status of an entry in the Static MAC Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available. The trunk member port can not set up static MAC.')NEWLINEautoFdbTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4), )NEWLINEif mibBuilder.loadTexts: autoFdbTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbTable.setDescription('A list of the Auto Fdb')NEWLINEautoFdbEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "autoFdbIPAddress"))NEWLINEif mibBuilder.loadTexts: autoFdbEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbEntry.setDescription('A auto fdb entry containing the ipaddress')NEWLINEautoFdbIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbIPAddress.setDescription('The IpAddress of the autoFdbEntry.')NEWLINEautoFdbVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbVlanID.setDescription('The VlanID of the autoFdbEntry.')NEWLINEautoFdbMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbMacAddress.setDescription('The Mac Address of the autoFdbEntry.')NEWLINEautoFdbPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbPort.setDescription('The Port of the autoFdbEntry.')NEWLINEautoFdbTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: autoFdbTimeStamp.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbTimeStamp.setDescription('The Time Stamp of the autoFdbEntry.')NEWLINEautoFdbStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 4, 1, 6), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: autoFdbStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: autoFdbStatus.setDescription('The status of an entry in the Auto Fdb Table. Only a subset of the rowstatus variables (createAndGo, createAndWait,destroy) are available.')NEWLINEstaticVlanBaseAutoLearnList1k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList1k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList1k.setDescription("A string of octets containing one bit per VLAN. The first octet corresponds to VLANs with VlanIndex values 1 through 8; the second octet to VLANs 9 through 16 etc. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn, the bit corresponding to that VLAN is set to '1'. Write AutoLearnList1k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseAutoLearnList2k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList2k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList2k.setDescription('A string of octets containing one bit per VLAN for VLANS with VlanIndex values 1025 through 2048. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn. Write AutoLearnList2k use 256 character, and conform to the foregoing rules.')NEWLINEstaticVlanBaseAutoLearnList3k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList3k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList3k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 2049 through 3072. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn the bit corresponding to that VLAN is set to '1'. Write AutoLearnList3k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseAutoLearnList4k = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList4k.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseAutoLearnList4k.setDescription("A string of octets containing one bit per VLAN for VLANS with VlanIndex values 3073 through 4094. The most significant bit of each octet corresponds to the lowest VlanIndex value in that octet. For each VLAN that is mapped to this Auto Learn the bit corresponding to that VLAN is set to '1'. Write AutoLearnList4k use 256 character, and conform to the foregoing rules.")NEWLINEstaticVlanBaseEnableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseEnableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseEnableAutoLearn.setDescription('Set enable vlan list to auto learn, and range 1-4094.')NEWLINEstaticVlanBaseDisableAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 9, 5, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 512))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticVlanBaseDisableAutoLearn.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticVlanBaseDisableAutoLearn.setDescription('Set disable vlan list to auto learn, and range 1-4094.')NEWLINEigsSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1))NEWLINEigsVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3))NEWLINEigsHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6))NEWLINEigsStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsStatus.setDescription("Enables or disables IGMP snooping in the system. When set to 'enabled', the IGS module starts protocol operations. When set to 'disabled', the IGS module stops performing protocol operations.")NEWLINEigsRouterPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsRouterPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsRouterPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt router port entry will be purged. For each router port learnt, this timer runs for 'RouterPortPurgeInterval' seconds.When the timer expires, the learnt router port entry is purged. However if control messages are received from the router before the timer expiry, then the timer is restarted.")NEWLINEigsHostPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(130, 153025)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsHostPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt port entry will be purged. For each port on which report has been received this timer runs for 'PortPurgeInterval' seconds. This timer will be restarted whenever a report message is received from a host on the specific port. If the timer expires, then , the learnt port entry will be purged from the multicast group.")NEWLINEigsDataDrivenLearningMaxLearnedEntryVlaue = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024)).clone(64)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsDataDrivenLearningMaxLearnedEntryVlaue.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsDataDrivenLearningMaxLearnedEntryVlaue.setDescription('The maximum data driven learning entry value.')NEWLINEigsReportToAllPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsReportToAllPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsReportToAllPort.setDescription("Enables or disables IGMP snooping in the system. When set to 'enabled', the IGS module forwards packets to report to all port. When set to 'disabled', the IGS module forwards packets to router port only.")NEWLINEigsVlanRouterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3), )NEWLINEif mibBuilder.loadTexts: igsVlanRouterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterTable.setDescription('This table contains the list of ports through which a router, in a particular VLAN is reachable.')NEWLINEigsVlanRouterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanRouterVlanId"))NEWLINEif mibBuilder.loadTexts: igsVlanRouterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterEntry.setDescription('Contains the VLAN ID and list of ports on which routers are present in the VLAN.')NEWLINEigsVlanRouterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanRouterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterVlanId.setDescription('VLAN ID of the ports through which router is reachable.')NEWLINEigsVlanRouterPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 3, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanRouterPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRouterPortList.setDescription('List of ports on which routers are present. These router ports are learnt through control messages received from routers, and can also be configured statically.')NEWLINEigsVlanFilterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4), )NEWLINEif mibBuilder.loadTexts: igsVlanFilterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterTable.setDescription('This table contains configuration of snooping on specific Vlans. This Table is valid only when VLAN is enabled in the system.')NEWLINEigsVlanFilterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanFilterVlanId"))NEWLINEif mibBuilder.loadTexts: igsVlanFilterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterEntry.setDescription('Contains snooping status , version and fast leave configuration for a specific VLAN.')NEWLINEigsVlanFilterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanFilterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFilterVlanId.setDescription('Index of IgsVlanFilterEntry. This object indicates the VLAN ID for which the snooping configurations in IgsVlanFilterEntry is to be done.')NEWLINEigsVlanSnoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanSnoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanSnoopStatus.setDescription('This object allows you to enable/disable IGS function on a specific VLAN.')NEWLINEigsVlanQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQuerier.setDescription('Indicates whether the switch is configured as a querier in the VLAN')NEWLINEigsVlanCfgQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanCfgQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanCfgQuerier.setDescription("The snooping switch can be configured as a querier via this object to send out IGMP general queries when IGMP routers are not present in the VLAN. When set to 'enabled', the switch will generate general queries.")NEWLINEigsVlanQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(125)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQueryInterval.setDescription('This is the interval (in seconds) for which the switch sends general queries when it is configured as a querier for the VLAN. A switch should be configured as a querier for a VLAN only when there is no queriers in the network.')NEWLINEigsVlanRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRtrPortList.setDescription('List of ports which are configured statically as router ports')NEWLINEigsVlanFbdRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanFbdRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFbdRtrPortList.setDescription('List of ports which can be configured statically as forbidden router ports.')NEWLINEigsVlanFastLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanFastLeave.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanFastLeave.setDescription("Enables or disables fast leave for the VLAN. When it is 'disabled',on reception of a leave message, the switch checks if they are any interested receivers for the group by sending a group specific query before removing the port from the forwarding table. If set to 'enabled', the switch does not send a group specific query and immediately removes the port from the forwarding table.")NEWLINEigsVlanDataDrivenLearningStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningStatus.setDescription('This object allows you to enable/disable Data Driven Learning function on a specific VLAN.')NEWLINEigsVlanQuerierVersionStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(3, 2))).clone(namedValues=NamedValues(("igmp-v3", 3), ("igmp-v2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQuerierVersionStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQuerierVersionStatus.setDescription('This object allows you to enable/disable Querier Version function on a specific VLAN.')NEWLINEigsVlanDataDrivenLearningAgeOutStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningAgeOutStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanDataDrivenLearningAgeOutStatus.setDescription('This object allows you to enable/disable Data Driven Learning Age Out State on a specific VLAN.')NEWLINEigsVlanReportSuppression = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanReportSuppression.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanReportSuppression.setDescription('Enables or disables Report suppression in the system.')NEWLINEigsVlanRobustnessValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanRobustnessValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanRobustnessValue.setDescription("When the switch receives leave message on a port, it sends group specific query to check if there are any other interested receivers for the group. This attribute defines the maximum number of queries sent by the switch before deleting the port from the group membership information in the forwarding database. If the maximum retry count exceeds 'igsRobustnessValue', then the port will be deleted from the multicast group membership information in the forwarding database and received leave message will be forwarded onto the router ports if there are no interested receivers for the group.")NEWLINEigsVlanGrpQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanGrpQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanGrpQueryInterval.setDescription("The value of this attribute defines the time period with which the switch will send group specific queries on a port to check if there is any intersted receivers. The switch will send 'igsRobustnessValue' queries before removing the port from the group membership information in the forwarding database.")NEWLINEigsVlanQueryMaxResponseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 4, 1, 15), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 25)).clone(10)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igsVlanQueryMaxResponseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanQueryMaxResponseTime.setDescription('The maximum query response time advertised in IGMPv2 general queries on this interface.')NEWLINEigsVlanMulticastGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5), )NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupTable.setDescription('This table contains MAC based multicast forwarding information.')NEWLINEigsVlanMulticastGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsVlanMulticastGroupVlanId"), (0, "DES-1210-28MEbx", "igsVlanMulticastGroupIpAddress"))NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupEntry.setDescription('This table contains VLAN ID, multicast group MAC address and the list of ports onto which the multicast data packets for group should be forwarded.')NEWLINEigsVlanMulticastGroupVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupVlanId.setDescription('VLAN ID pertaining to the Multicast forwarding entry')NEWLINEigsVlanMulticastGroupIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupIpAddress.setDescription('Multicast group IP address. This object indicates that a multicast group address was learned in the switch and be represented as IP address format.')NEWLINEigsVlanMulticastGroupMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupMacAddress.setDescription('Multicast group MAC address. This object indicates that a multicast group address was learned in the switch and be represented as MAC address format.')NEWLINEigsVlanMulticastGroupPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 3, 5, 1, 4), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsVlanMulticastGroupPortList.setDescription('List of ports onto which the multicast data packets destined for this group will be forwarded.')NEWLINEigsHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1), )NEWLINEif mibBuilder.loadTexts: igsHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTable.setDescription('This table is used to manage the IGMP Host based Fast Leave function of the switch.')NEWLINEigsHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igsHostTableVLANID"), (0, "DES-1210-28MEbx", "igsHostTableGroupAddress"), (0, "DES-1210-28MEbx", "igsHostTablePort"), (0, "DES-1210-28MEbx", "igsHostTableHostIPAddress"))NEWLINEif mibBuilder.loadTexts: igsHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostEntry.setDescription('Contains management entities for IGMP Host based fast leave function.')NEWLINEigsHostTableVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableVLANID.setDescription('VLAN ID of Host table entry.')NEWLINEigsHostTableGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableGroupAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableGroupAddress.setDescription('Group address of Host table entry.')NEWLINEigsHostTablePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTablePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTablePort.setDescription('Port number of Host table entry. For all machines give maximum port number.')NEWLINEigsHostTableHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 10, 6, 1, 1, 4), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igsHostTableHostIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: igsHostTableHostIPAddress.setDescription('Host IP address of Group in Host table entry.')NEWLINEmldsSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1))NEWLINEmldsVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3))NEWLINEmldsHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4))NEWLINEmldsStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsStatus.setDescription("Enables or disables MLD snooping in the system. When set to 'enabled', the MLDS module starts protocol operations. When set to 'disabled', the MLDS module stops performing protocol operations.")NEWLINEmldsRouterPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsRouterPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsRouterPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt router port entry will be purged. For each router port learnt, this timer runs for 'RouterPortPurgeInterval' seconds.When the timer expires, the learnt router port entry is purged. However if control messages are received from the router before the timer expiry, then the timer is restarted.")NEWLINEmldsHostPortPurgeInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(130, 153025)).clone(260)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsHostPortPurgeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostPortPurgeInterval.setDescription("This is the interval (in seconds) after which a learnt port entry will be purged. For each port on which report has been received this timer runs for 'PortPurgeInterval' seconds. This timer will be restarted whenever a report message is received from a host on the specific port. If the timer expires, then , the learnt port entry will be purged from the multicast group.")NEWLINEmldsDataDrivenLearningMaxLearnedEntryVlaue = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024)).clone(64)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsDataDrivenLearningMaxLearnedEntryVlaue.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsDataDrivenLearningMaxLearnedEntryVlaue.setDescription('The maximum data driven learning entry value.')NEWLINEmldsVlanRouterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3), )NEWLINEif mibBuilder.loadTexts: mldsVlanRouterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterTable.setDescription('This table contains the list of ports through which a router, in a particular VLAN is reachable.')NEWLINEmldsVlanRouterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanRouterVlanId"))NEWLINEif mibBuilder.loadTexts: mldsVlanRouterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterEntry.setDescription('Contains the VLAN ID and list of ports on which routers are present in the VLAN.')NEWLINEmldsVlanRouterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanRouterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterVlanId.setDescription('VLAN ID of the ports through which router is reachable.')NEWLINEmldsVlanRouterPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 3, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanRouterPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRouterPortList.setDescription('List of ports on which routers are present. These router ports are learnt through control messages received from routers, and can also be configured statically.')NEWLINEmldsVlanFilterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4), )NEWLINEif mibBuilder.loadTexts: mldsVlanFilterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterTable.setDescription('This table contains configuration of snooping on specific Vlans. This Table is valid only when VLAN is enabled in the system.')NEWLINEmldsVlanFilterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanFilterVlanId"))NEWLINEif mibBuilder.loadTexts: mldsVlanFilterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterEntry.setDescription('Contains snooping status , version and fast leave configuration for a specific VLAN.')NEWLINEmldsVlanFilterVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanFilterVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFilterVlanId.setDescription('Index of MldsVlanFilterEntry. This object indicates the VLAN ID for which the snooping configurations in MldsVlanFilterEntry is to be done.')NEWLINEmldsVlanSnoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanSnoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanSnoopStatus.setDescription('This object allows you to enable/disable MLDS function on a specific VLAN.')NEWLINEmldsVlanQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQuerier.setDescription('Indicates whether the switch is configured as a querier in the VLAN')NEWLINEmldsVlanCfgQuerier = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanCfgQuerier.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanCfgQuerier.setDescription("The snooping switch can be configured as a querier via this object to send out MLD general queries when IGMP routers are not present in the VLAN. When set to 'enabled', the switch will generate general queries.")NEWLINEmldsVlanQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 600)).clone(125)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQueryInterval.setDescription('This is the interval (in seconds) for which the switch sends general queries when it is configured as a querier for the VLAN. A switch should be configured as a querier for a VLAN only when there is no queriers in the network.')NEWLINEmldsVlanRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRtrPortList.setDescription('List of ports which are configured statically as router ports')NEWLINEmldsVlanFbdRtrPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanFbdRtrPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFbdRtrPortList.setDescription('List of ports which can be configured statically as forbidden router ports.')NEWLINEmldsVlanFastLeave = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanFastLeave.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanFastLeave.setDescription("Enables or disables fast leave for the VLAN. When it is 'disabled',on reception of a leave message, the switch checks if they are any interested receivers for the group by sending a group specific query before removing the port from the forwarding table. If set to 'enabled', the switch does not send a group specific query and immediately removes the port from the forwarding table.")NEWLINEmldsVlanDataDrivenLearningStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanDataDrivenLearningStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanDataDrivenLearningStatus.setDescription('This object allows you to enable/disable Data Driven Learning function on a specific VLAN.')NEWLINEmldsVlanReportSuppression = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanReportSuppression.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanReportSuppression.setDescription('Enables or disables Report suppression in the system.')NEWLINEmldsVlanRobustnessValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanRobustnessValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanRobustnessValue.setDescription("When the switch receives leave message on a port, it sends group specific query to check if there are any other interested receivers for the group. This attribute defines the maximum number of queries sent by the switch before deleting the port from the group membership information in the forwarding database. If the maximum retry count exceeds 'mldsRobustnessValue', then the port will be deleted from the multicast group membership information in the forwarding database and received leave message will be forwarded onto the router ports if there are no interested receivers for the group.")NEWLINEmldsVlanGrpQueryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 25)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanGrpQueryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanGrpQueryInterval.setDescription("The value of this attribute defines the time period with which the switch will send group specific queries on a port to check if there is any intersted receivers. The switch will send 'mldsRobustnessValue' queries before removing the port from the group membership information in the forwarding database.")NEWLINEmldsVlanQueryMaxResponseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 4, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 25)).clone(10)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mldsVlanQueryMaxResponseTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanQueryMaxResponseTime.setDescription('The maximum query response time advertised in MLDv1 general queries on this interface.')NEWLINEmldsVlanMulticastGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5), )NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupTable.setDescription('This table contains MAC based multicast forwarding information.')NEWLINEmldsVlanMulticastGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsVlanMulticastGroupVlanId"), (0, "DES-1210-28MEbx", "mldsVlanMulticastGroupIpAddress"))NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupEntry.setDescription('This table contains VLAN ID, multicast group MAC address and the list of ports onto which the multicast data packets for group should be forwarded.')NEWLINEmldsVlanMulticastGroupVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupVlanId.setDescription('VLAN ID pertaining to the Multicast forwarding entry')NEWLINEmldsVlanMulticastGroupIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 2), InetAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupIpAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupIpAddress.setDescription('Multicast group IP address. This object indicates that a multicast group address was learned in the switch and be represented as IP address format.')NEWLINEmldsVlanMulticastGroupMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupMacAddress.setDescription('Multicast group MAC address. This object indicates that a multicast group address was learned in the switch and be represented as MAC address format.')NEWLINEmldsVlanMulticastGroupPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 3, 5, 1, 4), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsVlanMulticastGroupPortList.setDescription('List of ports onto which the multicast data packets destined for this group will be forwarded.')NEWLINEmldsHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1), )NEWLINEif mibBuilder.loadTexts: mldsHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTable.setDescription('This table is used to manage the IGMP Host based Fast Leave function of the switch.')NEWLINEmldsHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mldsHostTableVLANID"), (0, "DES-1210-28MEbx", "mldsHostTableGroupAddress"), (0, "DES-1210-28MEbx", "mldsHostTablePort"), (0, "DES-1210-28MEbx", "mldsHostTableHostIPAddress"))NEWLINEif mibBuilder.loadTexts: mldsHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostEntry.setDescription('Contains management entities for IGMP Host based fast leave function.')NEWLINEmldsHostTableVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableVLANID.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableVLANID.setDescription('VLAN ID of IPv6 Host table entry.')NEWLINEmldsHostTableGroupAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableGroupAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableGroupAddress.setDescription('Group address of IPv6 Host table entry.')NEWLINEmldsHostTablePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTablePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTablePort.setDescription('Port number of IPv6 Host table entry. For all machines give maximum port number.')NEWLINEmldsHostTableHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 88, 4, 1, 1, 4), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: mldsHostTableHostIPAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: mldsHostTableHostIPAddress.setDescription('Host IP address of Group in IPv6 Host table entry.')NEWLINEswAuthenCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1))NEWLINEswAuthStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthStatus.setDescription('Enable/Disable Static 802.1x.')NEWLINEswAuthMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("portBase", 1), ("macBase", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthMode.setDescription('This object indicates the authentication mode of the device.')NEWLINEauthProtocol = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authProtocolRadiusEap", 1), ("authProtocolLocal", 2))).clone('authProtocolRadiusEap')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: authProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: authProtocol.setDescription('The authentication method used to authenticate users.')NEWLINEswAuthCtrlPktFwdMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authForwardEap", 1), ("authDropEap", 2))).clone('authForwardEap')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthCtrlPktFwdMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthCtrlPktFwdMode.setDescription('When 802.1x disable, this item can decided eap packet be forward or drop.')NEWLINEswAuthPortAccessCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2))NEWLINEswAuthPortAccessControlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1), )NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthPortAccessControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthAuthConfigPortNumber"))NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthPortAccessControlEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthAuthConfigPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortNumber.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortNumber.setDescription('A unique value for each port that correlates to port index. Its value ranges between 1 and the value of port number. For all machines give maximum port number.')NEWLINEswAuthAuthQuietPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setReference('9.4.1, quietPeriod.')NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthQuietPeriod.setDescription('The value, in seconds, of the quietPeriod constant currently in use by the Authenticator PAE state machine.')NEWLINEswAuthAuthSuppTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(12)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setReference('9.4.1, suppTimeout.')NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthSuppTimeout.setDescription('The value, in seconds, of the suppTimeout constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(16)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setReference('9.4.1, serverTimeout.')NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthServerTimeout.setDescription('The value, in seconds, of the serverTimeout constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthMaxReq = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setReference('9.4.1, maxReq.')NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthMaxReq.setDescription('The value of the maxReq constant currently in use by the Backend Authentication state machine.')NEWLINEswAuthAuthTxPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(24)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setReference('9.4.1, txPeriod.')NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthTxPeriod.setDescription('The value, in seconds, of the txPeriod constant currently in use by the Authenticator PAE state machine.')NEWLINEswAuthAuthReAuthPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(3600)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setReference('9.4.1, reAuthPerio.')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthPeriod.setDescription('The value, in seconds, of the reAuthPeriod constant currently in use by the Reauthentication Timer state machine.')NEWLINEswAuthAuthReAuthentication = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setReference('9.4.1, reAuthEnable.')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthReAuthentication.setDescription('The enable/disable control used by the Reauthentication Timer state machine (8.5.5.1).')NEWLINEswAuthAuthConfigPortControl = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("forceUnauthorized", 1), ("auto", 2), ("forceAuthorized", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setReference('9.4.1, AuthControlledPortControl.')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthConfigPortControl.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthAuthCapability = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("authenticator", 1), ("none", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setReference('AuthCapability.')NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthCapability.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthAuthDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("both", 0), ("in", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setReference('AuthDirection.')NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthAuthDirection.setDescription('The current value of the controlled Port control parameter for the Port.')NEWLINEswAuthUser = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3))NEWLINEswAuthUserTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1), )NEWLINEif mibBuilder.loadTexts: swAuthUserTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthUserEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthUserName"))NEWLINEif mibBuilder.loadTexts: swAuthUserEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthUserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserName.setDescription('The unique index value of a row in this table. This object is used to set 802.1X Local user name, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthUserPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthUserPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserPassword.setDescription('This object is used to set 802.1X Local user Password, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthUserStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 3, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthUserStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthUserStatus.setDescription('The status of this conceptual row in the swAuthUserTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthUserName objects must be explicitly set.')NEWLINEswAuthRadiusServer = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4))NEWLINEiPv4swAuthRadiusServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1), )NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEiPv4swAuthRadiusServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "iPv4swAuthRadiusServerIndex"))NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEiPv4swAuthRadiusServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerIndex.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerIndex.setDescription('A unique value for Authentication RADIUS Server index. Its value ranges between 1 and 3.')NEWLINEiPv4swAuthRadiusServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAddress.setDescription('The IP address of the RADIUS server referred to in this table entry.')NEWLINEiPv4swAuthRadiusServerAuthenticationPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1812)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAuthenticationPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAuthenticationPort.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1813)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAccountingPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerAccountingPort.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTimeout.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerTimeout.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerRetransmit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerRetransmit.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerRetransmit.setDescription('The value is for setting UDP Port.')NEWLINEiPv4swAuthRadiusServerKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerKey.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerKey.setDescription('This object is used to set 802.1X Radius Server Key, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEiPv4swAuthRadiusServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4swAuthRadiusServerStatus.setDescription('The status of this conceptual row in the swAuthRadiusServerTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthRadiusServerIndex objects must be explicitly set.')NEWLINEswAuthRadiusServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2), )NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTable.setDescription('A table that contains the configuration objects for the Authenticator PAE associated with each port. An entry appears in this table for each port that may authenticate access to itself.')NEWLINEswAuthRadiusServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swAuthRadiusServerIndex"))NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerEntry.setDescription('The configuration information for an Authenticator Port.')NEWLINEswAuthRadiusServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerIndex.setDescription('A unique value for Authentication RADIUS Server index. Its value ranges between 1 and 3.')NEWLINEswAuthRadiusIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusIPType.setDescription('The IP address of the RADIUS server IP type referred to in this table entry.')NEWLINEswAuthRadiusServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 3), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAddress.setDescription('The IP address of the RADIUS server referred to in this table entry.')NEWLINEswAuthRadiusServerInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerInterfaceName.setDescription('Specifies the interface name when the swAuthRadiusServerAddress is linklocal address.')NEWLINEswAuthRadiusServerAuthenticationPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1812)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAuthenticationPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAuthenticationPort.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1813)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAccountingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerAccountingPort.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(5)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerTimeout.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerRetransmit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerRetransmit.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerRetransmit.setDescription('The value is for setting UDP Port.')NEWLINEswAuthRadiusServerKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerKey.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerKey.setDescription('This object is used to set 802.1X Radius Server Key, The following characters are allowed to input: semicolon, question mark, space, and double quotation mark.')NEWLINEswAuthRadiusServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 23, 4, 2, 1, 10), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swAuthRadiusServerStatus.setDescription('The status of this conceptual row in the swAuthRadiusServerTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The swAuthRadiusServerIndex objects must be explicitly set.')NEWLINEcosScheduleMechanism = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("strictPriority", 1), ("wrr", 2), ("strict3wrr", 3), ("strict2wrr", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosScheduleMechanism.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosScheduleMechanism.setDescription('Queuing mechanism. strictPriority(1) : Strict Priority wrr(2) : Weighted Round Robin Strict-priority scheduling is implemented with a special strict-priority scheduler node that is stacked directly above the port. Queues stacked on top of the strict-priority scheduler node always get bandwidth before other queues. Weighted round-robin scheduling is designed to better handle queues with different processing capacities. Each queue has a weight : Low is 1, Medium is 2, High is 4 and Highest is 8 for WS3 spec. Queues with higher weights get bandwidth before than other queues with less weights. ')NEWLINEcosOutputSchedule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2))NEWLINEcosClassTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1), )NEWLINEif mibBuilder.loadTexts: cosClassTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassTable.setDescription('A list of cosOutputSchedule.')NEWLINEcosClassEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cosClassIndex"))NEWLINEif mibBuilder.loadTexts: cosClassEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassEntry.setDescription('A list of cosOutputClass Weight.')NEWLINEcosClassIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosClassIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosClassIndex.setDescription('A index of class 0 ~ 3.')NEWLINEcosWeight = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 55))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosWeight.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosWeight.setDescription('cos weight ')NEWLINEcosBandwidthCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9))NEWLINEcosBandwidthCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1), )NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlTable.setDescription('A list of cosBandwidthCtrlEntry default priority Entries.')NEWLINEcosBandwidthCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cosBandwidthCtrlPortIndex"), (0, "DES-1210-28MEbx", "cosBandwidthCtrlClassIndex"))NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlEntry.setDescription('A list of cosBandwidthCtrlEntry default priority priorities.')NEWLINEcosBandwidthCtrlPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEcosBandwidthCtrlClassIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlClassIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthCtrlClassIndex.setDescription('A BandwidthCtrlClassIndex identifier that is in the range of 1 to ifNumber.')NEWLINEcosBandwidthValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cosBandwidthValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthValue.setDescription('The BandwidthValue return value.')NEWLINEcosBandwidthEffectiveRX = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveRX.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveRX.setDescription('A speed rate of Effective RX.')NEWLINEcosBandwidthEffectiveTX = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 9, 1, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveTX.setStatus('current')NEWLINEif mibBuilder.loadTexts: cosBandwidthEffectiveTX.setDescription('A speed value of Effective TX.')NEWLINEqosDefaultUserPri = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4))NEWLINEqosDefaultUserPriTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1), )NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriTable.setDescription('A list of 802.1p port default priority Entries.')NEWLINEqosDefaultUserPriEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosDefaultUserPriPortIndex"))NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriEntry.setDescription('A list of 802.1p port default priority priorities.')NEWLINEqosDefaultUserPriPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultUserPriPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEqosDefaultPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("priority0", 0), ("priority1", 1), ("priority2", 2), ("priority3", 3), ("priority4", 4), ("priority5", 5), ("priority6", 6), ("priority7", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDefaultPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDefaultPriority.setDescription("For ingress untagged packets, the per port 'Default Priority' setting will be applied to packets of each port to provide port-based traffic prioritization when 802.1p is enabled.")NEWLINEqosEffectiveDefaultPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("priority0", 0), ("priority1", 1), ("priority2", 2), ("priority3", 3), ("priority4", 4), ("priority5", 5), ("priority6", 6), ("priority7", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosEffectiveDefaultPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosEffectiveDefaultPriority.setDescription("For ingress untagged packets, the per port 'Effective Default Priority' setting will be applied to packets of each port to provide port-based traffic prioritization when 802.1p is enabled.")NEWLINEqosUserPriority = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5))NEWLINEqosUserPriorityTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1), )NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setReference('ISO/IEC 15802-3 Table 7-2')NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriorityTable.setDescription('A table mapping evaluated User Priority to Traffic Class, for forwarding by the bridge. Traffic class is a number in the range (0..3).')NEWLINEqosUserPriEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosUserPriIndex"))NEWLINEif mibBuilder.loadTexts: qosUserPriEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriEntry.setDescription('User Priority to Traffic Class mapping.')NEWLINEqosUserPriIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosUserPriIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriIndex.setDescription('For ingress tagged packets, D-Link Smart Switches will refer to these information and prioritize them with 4 different priority queues. If 802.1p is enabled.')NEWLINEqosUserPriClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 5, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosUserPriClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosUserPriClass.setDescription('The User Class the received frame is mapped to.')NEWLINEqosPriSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7))NEWLINEqosPriSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1), )NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setReference('ISO/IEC 15802-3 Table 7-2')NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSettingsTable.setDescription('A list of port priority settings.')NEWLINEqosPriSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qosPriSetPortIndex"))NEWLINEif mibBuilder.loadTexts: qosPriSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSettingsEntry.setDescription('A list of port priority settings Entries.')NEWLINEqosPriSetPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qosPriSetPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSetPortIndex.setDescription('A port identifier that is in the range of 1 to ifNumber.')NEWLINEqosPriSetPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 7, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 4, 6))).clone(namedValues=NamedValues(("none", 0), ("ieee8021P", 2), ("dscp-tos", 4), ("ieee8021P-dscp-tos", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosPriSetPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosPriSetPortType.setDescription('The port priority setting type. (ex. none = 0, 802.1p = 2, DSCP = 4. If you want enable 802.1p & DSCP, the value is 2 + 4 = 6. ')NEWLINEqosDiffServTOS = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6))NEWLINEqosDSCPTOSMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tos", 1), ("dscp", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDSCPTOSMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDSCPTOSMode.setDescription('Settings of Qos mode: DSCP QoS or TOS Qos. IEEE 802.1p : It specifies a priority(0~7) value to four queues in WS3 : Low(1,2), Medium(0,3), High(4,5) and Highest(6,7), inclusive that can be used by Quality of Service (QoS) disciplines to differentiate traffic. DSCP : Differentiated services enhancements to the Internet protocol are intended to enable scalable service discrimination in the Internet without the need for per-flow state and signaling at every hop. ')NEWLINEqosDiffServTypeGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2))NEWLINEqosDiffServType00 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType00.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType00.setDescription('DiffServ Type 0 : IP ToS value = 0')NEWLINEqosDiffServType01 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType01.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType01.setDescription('DiffServ Type 01 : IP ToS value = 4')NEWLINEqosDiffServType02 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType02.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType02.setDescription('DiffServ Type 02 : IP ToS value = 8')NEWLINEqosDiffServType03 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType03.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType03.setDescription('DiffServ Type 03 : IP ToS value = 12')NEWLINEqosDiffServType04 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType04.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType04.setDescription('DiffServ Type 04 : IP ToS value = 16')NEWLINEqosDiffServType05 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType05.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType05.setDescription('DiffServ Type 05 : IP ToS value = 20')NEWLINEqosDiffServType06 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType06.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType06.setDescription('DiffServ Type 06 : IP ToS value = 24')NEWLINEqosDiffServType07 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType07.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType07.setDescription('DiffServ Type 07 : IP ToS value = 28')NEWLINEqosDiffServType08 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType08.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType08.setDescription('DiffServ Type 08 : IP ToS value = 32')NEWLINEqosDiffServType09 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType09.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType09.setDescription('DiffServ Type 09 : IP ToS value = 36')NEWLINEqosDiffServType10 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType10.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType10.setDescription('DiffServ Type 10 : IP ToS value = 40')NEWLINEqosDiffServType11 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType11.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType11.setDescription('DiffServ Type 11 : IP ToS value = 44')NEWLINEqosDiffServType12 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType12.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType12.setDescription('DiffServ Type 12 : IP ToS value = 48')NEWLINEqosDiffServType13 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType13.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType13.setDescription('DiffServ Type 13 : IP ToS value = 52')NEWLINEqosDiffServType14 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType14.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType14.setDescription('DiffServ Type 14 : IP ToS value = 56')NEWLINEqosDiffServType15 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType15.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType15.setDescription('DiffServ Type 15 : IP ToS value = 60')NEWLINEqosDiffServType16 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType16.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType16.setDescription('DiffServ Type 16 : IP ToS value = 64')NEWLINEqosDiffServType17 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType17.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType17.setDescription('DiffServ Type 17 : IP ToS value = 68')NEWLINEqosDiffServType18 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType18.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType18.setDescription('DiffServ Type 18 : IP ToS value = 72')NEWLINEqosDiffServType19 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType19.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType19.setDescription('DiffServ Type 19 : IP ToS value = 76')NEWLINEqosDiffServType20 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType20.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType20.setDescription('DiffServ Type 20 : IP ToS value = 80')NEWLINEqosDiffServType21 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType21.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType21.setDescription('DiffServ Type 21 : IP ToS value = 84')NEWLINEqosDiffServType22 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType22.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType22.setDescription('DiffServ Type 22 : IP ToS value = 88')NEWLINEqosDiffServType23 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType23.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType23.setDescription('DiffServ Type 23 : IP ToS value = 92')NEWLINEqosDiffServType24 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType24.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType24.setDescription('DiffServ Type 24 : IP ToS value = 96')NEWLINEqosDiffServType25 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType25.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType25.setDescription('DiffServ Type 25 : IP ToS value = 100')NEWLINEqosDiffServType26 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType26.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType26.setDescription('DiffServ Type 26 : IP ToS value = 104')NEWLINEqosDiffServType27 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType27.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType27.setDescription('DiffServ Type 27 : IP ToS value = 108')NEWLINEqosDiffServType28 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType28.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType28.setDescription('DiffServ Type 28 : IP ToS value = 112')NEWLINEqosDiffServType29 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType29.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType29.setDescription('DiffServ Type 29 : IP ToS value = 116')NEWLINEqosDiffServType30 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType30.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType30.setDescription('DiffServ Type 30 : IP ToS value = 120')NEWLINEqosDiffServType31 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType31.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType31.setDescription('DiffServ Type 31 : IP ToS value = 124')NEWLINEqosDiffServType32 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType32.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType32.setDescription('DiffServ Type 32 : IP ToS value = 128')NEWLINEqosDiffServType33 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 34), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType33.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType33.setDescription('DiffServ Type 33 : IP ToS value = 132')NEWLINEqosDiffServType34 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 35), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType34.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType34.setDescription('DiffServ Type 34 : IP ToS value = 136')NEWLINEqosDiffServType35 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 36), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType35.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType35.setDescription('DiffServ Type 35 : IP ToS value = 140')NEWLINEqosDiffServType36 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType36.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType36.setDescription('DiffServ Type 36 : IP ToS value = 144')NEWLINEqosDiffServType37 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 38), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType37.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType37.setDescription('DiffServ Type 37 : IP ToS value = 148')NEWLINEqosDiffServType38 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 39), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType38.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType38.setDescription('DiffServ Type 38 : IP ToS value = 152')NEWLINEqosDiffServType39 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 40), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType39.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType39.setDescription('DiffServ Type 39 : IP ToS value = 156')NEWLINEqosDiffServType40 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 41), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType40.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType40.setDescription('DiffServ Type 40 : IP ToS value = 160')NEWLINEqosDiffServType41 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 42), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType41.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType41.setDescription('DiffServ Type 41 : IP ToS value = 164')NEWLINEqosDiffServType42 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 43), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType42.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType42.setDescription('DiffServ Type 42 : IP ToS value = 168')NEWLINEqosDiffServType43 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 44), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType43.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType43.setDescription('DiffServ Type 43 : IP ToS value = 172')NEWLINEqosDiffServType44 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 45), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType44.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType44.setDescription('DiffServ Type 44 : IP ToS value = 176')NEWLINEqosDiffServType45 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 46), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType45.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType45.setDescription('DiffServ Type 45 : IP ToS value = 180')NEWLINEqosDiffServType46 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 47), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType46.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType46.setDescription('DiffServ Type 46 : IP ToS value = 184')NEWLINEqosDiffServType47 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 48), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType47.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType47.setDescription('DiffServ Type 47 : IP ToS value = 188')NEWLINEqosDiffServType48 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 49), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType48.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType48.setDescription('DiffServ Type 48 : IP ToS value = 192')NEWLINEqosDiffServType49 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType49.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType49.setDescription('DiffServ Type 49 : IP ToS value = 196')NEWLINEqosDiffServType50 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 51), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType50.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType50.setDescription('DiffServ Type 50 : IP ToS value = 200')NEWLINEqosDiffServType51 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 52), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType51.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType51.setDescription('DiffServ Type 51 : IP ToS value = 204')NEWLINEqosDiffServType52 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 53), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType52.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType52.setDescription('DiffServ Type 52 : IP ToS value = 208')NEWLINEqosDiffServType53 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 54), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType53.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType53.setDescription('DiffServ Type 53 : IP ToS value = 212')NEWLINEqosDiffServType54 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 55), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType54.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType54.setDescription('DiffServ Type 54 : IP ToS value = 216')NEWLINEqosDiffServType55 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 56), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType55.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType55.setDescription('DiffServ Type 55 : IP ToS value = 220')NEWLINEqosDiffServType56 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 57), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType56.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType56.setDescription('DiffServ Type 56 : IP ToS value = 224')NEWLINEqosDiffServType57 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 58), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType57.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType57.setDescription('DiffServ Type 57 : IP ToS value = 228')NEWLINEqosDiffServType58 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 59), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType58.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType58.setDescription('DiffServ Type 58 : IP ToS value = 232')NEWLINEqosDiffServType59 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 60), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType59.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType59.setDescription('DiffServ Type 59 : IP ToS value = 236')NEWLINEqosDiffServType60 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 61), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType60.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType60.setDescription('DiffServ Type 60 : IP ToS value = 240')NEWLINEqosDiffServType61 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 62), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType61.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType61.setDescription('DiffServ Type 61 : IP ToS value = 244')NEWLINEqosDiffServType62 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 63), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType62.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType62.setDescription('DiffServ Type 62 : IP ToS value = 248')NEWLINEqosDiffServType63 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 2, 64), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosDiffServType63.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosDiffServType63.setDescription('DiffServ Type 63 : IP ToS value = 252')NEWLINEqosTOSGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3))NEWLINEqosTOSType00 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType00.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType00.setDescription('TOS 0')NEWLINEqosTOSType01 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType01.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType01.setDescription('TOS 01')NEWLINEqosTOSType02 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType02.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType02.setDescription('TOS 02')NEWLINEqosTOSType03 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType03.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType03.setDescription('TOS 03')NEWLINEqosTOSType04 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType04.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType04.setDescription('TOS 04')NEWLINEqosTOSType05 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType05.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType05.setDescription('TOS 05')NEWLINEqosTOSType06 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType06.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType06.setDescription('TOS 06')NEWLINEqosTOSType07 = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 6, 3, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("low", 0), ("medium", 1), ("high", 2), ("highest", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qosTOSType07.setStatus('current')NEWLINEif mibBuilder.loadTexts: qosTOSType07.setDescription('TOS 07')NEWLINEqosAclPrioritySettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8))NEWLINEipv4aclQosTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1), )NEWLINEif mibBuilder.loadTexts: ipv4aclQosTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosTable.setDescription('A list of priority by acl setting.')NEWLINEipv4aclQosEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4aclQosIndex"))NEWLINEif mibBuilder.loadTexts: ipv4aclQosEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosEntry.setDescription('A list of priority by acl setting entry.')NEWLINEipv4aclQosIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclQosIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosIndex.setDescription('Index of priority by acl setting.')NEWLINEipv4aclQosType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("mac", 0), ("ip", 1), ("tcp", 2), ("udp", 3), ("vlanid", 4), ("protocol", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosType.setDescription('Type of priority by acl setting.')NEWLINEipv4aclQosMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosMACAddr.setDescription('Dst MAC of priority by acl setting.')NEWLINEipv4aclQosIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosIPAddr.setDescription('Dst IP of priority by acl setting')NEWLINEipv4aclQosTCPUDPPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosTCPUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosTCPUDPPort.setDescription('Dst TCP/UDP port of priority by acl setting')NEWLINEipv4aclQosVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosVlanID.setDescription('VLAN ID of priority by acl setting')NEWLINEipv4aclQosProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosProtocol.setDescription('Ip protocol number of priority by acl setting')NEWLINEipv4aclQosAssignClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("class0", 0), ("class1", 1), ("class2", 2), ("class3", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosAssignClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosAssignClass.setDescription('Be mapped class of priority by acl setting.')NEWLINEipv4aclQosStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 1, 1, 9), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclQosStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4aclQosStatus.setDescription('Status of priority by acl setting.')NEWLINEaclQosTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2), )NEWLINEif mibBuilder.loadTexts: aclQosTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosTable.setDescription('A list of priority by acl setting.')NEWLINEaclQosEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclQosIndex"))NEWLINEif mibBuilder.loadTexts: aclQosEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosEntry.setDescription('A list of priority by acl setting entry.')NEWLINEaclQosIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclQosIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIndex.setDescription('Index of priority by acl setting.')NEWLINEaclQosType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("mac", 0), ("ip", 1), ("tcp", 2), ("udp", 3), ("vlanid", 4), ("protocol", 5), ("ipv6", 6), ("ipv6traffic-class", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosType.setDescription('Type of priority by acl setting.')NEWLINEaclQosMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosMACAddr.setDescription('Dst MAC of priority by acl setting.')NEWLINEaclQosIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 4), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIPAddr.setDescription('Dst IP of priority by acl setting')NEWLINEaclQosIPv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 5), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIPv6Addr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIPv6Addr.setDescription('Dst IP of priority by acl setting. ')NEWLINEaclQosTCPUDPPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosTCPUDPPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosTCPUDPPort.setDescription('Dst TCP/UDP port of priority by acl setting')NEWLINEaclQosVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosVlanID.setDescription('VLAN ID of priority by acl setting')NEWLINEaclQosProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosProtocol.setDescription('Ip protocol number of priority by acl setting')NEWLINEaclQosIP6TC = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosIP6TC.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosIP6TC.setDescription('Ipv6 Traffic Class number of priority by acl setting')NEWLINEaclQosAssignClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 98), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("class0", 0), ("class1", 1), ("class2", 2), ("class3", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosAssignClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosAssignClass.setDescription('Be mapped class of priority by acl setting.')NEWLINEaclQosStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 12, 8, 2, 1, 99), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclQosStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclQosStatus.setDescription('Status of priority by acl setting.')NEWLINEbandwidthCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1))NEWLINEbandwidthCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2), )NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTable.setDescription('A table to control the rate limiting parameters either for the entire switch or for each interface in the switch.')NEWLINEbandwidthCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "bandwidthCtrlIndex"))NEWLINEif mibBuilder.loadTexts: bandwidthCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlEntry.setDescription('An entry appears in this table for each physical interface in the switch.')NEWLINEbandwidthCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEbandwidthCtrlTxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(64, 1024000), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlTxThreshold.setDescription("Configures interface Rate Limit (Packet that can be transferred on a port at a particular second). This object's value will take effect on the interface speed. Based on the operating speed of the port, the rate limit will be applied. This value can also be affected by the metering. A value of zero(0) disable rate limiting i.e. sets the port to full speed. The value can be set between 64~102400(Kbits per second) in FE port, 64~1024000 (Kbits per second) in GE port.")NEWLINEbandwidthCtrlRxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(64, 1024000), ))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: bandwidthCtrlRxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthCtrlRxThreshold.setDescription('Allows to configure the limiting value for the maximum number of receive packets that can be transmitted per second over this interface. Setting this object to the value zero disables rate limiting for receive packets on this interface. The value that can be set for this object is limited by the underlying hardware. The value can be set between 64~102400(Kbits per second) in FE port, 64~1024000(Kbits per second) in GE port.')NEWLINEbandwidthEffecTxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthEffecTxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthEffecTxThreshold.setDescription("This object's value will take effect on the interface speed. Based on the operating speed of the port, the rate limit will be applied. This value can also be affected by the metering. A value of zero(0) disable rate limiting i.e. sets the port to full speed. ")NEWLINEbandwidthEffecRxThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: bandwidthEffecRxThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: bandwidthEffecRxThreshold.setDescription('Allows to configure the limiting value for the maximum number of receive packets that can be transmitted per second over this interface. Setting this object to the value zero disables rate limiting for receive packets on this interface. The value that can be set for this object is limited by the underlying hardware. ')NEWLINEtrafficCtrlSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4))NEWLINEtrafficCtrlTrap = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("stormOccurred", 1), ("stormCleared", 2), ("both", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlTrap.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTrap.setDescription('The trap setting of traffic control.')NEWLINEtrafficCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2), )NEWLINEif mibBuilder.loadTexts: trafficCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTable.setDescription('The traffic control table.')NEWLINEtrafficCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trafficCtrlIndex"))NEWLINEif mibBuilder.loadTexts: trafficCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlEntry.setDescription('The traffic control entry.')NEWLINEtrafficCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trafficCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlIndex.setDescription('The traffic control index.')NEWLINEtrafficCtrlActionMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("drop", 0), ("shutdown", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlActionMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlActionMode.setDescription('The action mode of traffic control.')NEWLINEtrafficCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 0), ("b", 1), ("m", 2), ("mb", 3), ("u", 4), ("ub", 5), ("um", 6), ("umb", 7)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlType.setDescription('The control type of traffic control. (b: Broadcast, m: Multicast, u: Unknown Unicast)')NEWLINEtrafficCtrlThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 102400))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlThreshold.setDescription('The threshold of traffic control.')NEWLINEtrafficCtrlCountDown = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 30))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlCountDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlCountDown.setDescription('The count down value of traffic control.')NEWLINEtrafficCtrlTimeInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 30))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlTimeInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlTimeInterval.setDescription('The time interval of traffic control.')NEWLINEtrafficCtrlAutoRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 13, 4, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficCtrlAutoRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficCtrlAutoRecoverTime.setDescription('The recover time of traffic control.')NEWLINEsecurityTrustedHost = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1))NEWLINEtrustedHostStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trustedHostStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostStatus.setDescription('This object indicates trusted host function is enabled or disabled. When trusted host function is enabled, D-Link Smart Switches will only allow hosts which you trust to access and control the switch. Your local host IP Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEipv4trustedHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2), )NEWLINEif mibBuilder.loadTexts: ipv4trustedHostTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostTable.setDescription('A table to configure trusted host in the system.')NEWLINEipv4trustedHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4trustedHostIpAddr"), (0, "DES-1210-28MEbx", "ipv4trustedHostIpMask"))NEWLINEif mibBuilder.loadTexts: ipv4trustedHostEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostEntry.setDescription('Each entry in this table represents rules for particular trusted host.')NEWLINEipv4trustedHostIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpAddr.setDescription('The IP address of host you allow to access to D-Link Smart Switch. Your local host IP Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEipv4trustedHostIpMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostIpMask.setDescription('Used to mask with IP address, it allow you set a subnet as a trusted host entry.')NEWLINEipv4trustedHostRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4trustedHostRowStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4trustedHostRowStatus.setDescription('The status of an entry in the Trusted Host Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEtrustedHostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3), )NEWLINEif mibBuilder.loadTexts: trustedHostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostTable.setDescription('A table to configure trusted host for in the system.')NEWLINEtrustedHostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trustedHostIPType"), (0, "DES-1210-28MEbx", "trustedHostIpAddr"), (0, "DES-1210-28MEbx", "trustedHostIpMask"))NEWLINEif mibBuilder.loadTexts: trustedHostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostEntry.setDescription('Each entry in this table represents rules for particular trusted host.')NEWLINEtrustedHostIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIPType.setDescription('Type of IP interface.')NEWLINEtrustedHostIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIpAddr.setDescription('The IP address of host you allow to access to D-Link Smart Switch. Your local host IPv4/6 Addresses must be one of the IP Addresses to avoid disconnection.')NEWLINEtrustedHostIpMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 3), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trustedHostIpMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostIpMask.setDescription('Used to mask with IPv4/6 address, it allow you set a subnet as a trusted host entry.')NEWLINEtrustedHostRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 1, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: trustedHostRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: trustedHostRowStatus.setDescription('The status of an entry in the Trusted Host Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEsecurityARPSpoofPrevent = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3))NEWLINEaRPSpoofPreventTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1), )NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventTable.setDescription('A table to control ARP Spoofing prevention for the entire switch or for each interface in the switch.')NEWLINEaRPSpoofPreventEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aRPSpoofPreventIpAddr"))NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEaRPSpoofPreventIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 1), IpAddress())NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventIpAddr.setDescription("Specifies either the Network or Host address from which the switch can be managed. An address 0.0.0.0 indicates 'Any Manager'.")NEWLINEaRPSpoofPreventMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 2), MacAddress().clone(hexValue="000102030405")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventMacAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventMacAddress.setDescription('Ethernet Mac Address.')NEWLINEaRPSpoofPreventPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventPortList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEaRPSpoofPreventRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 3, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aRPSpoofPreventRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEsecuritySSL = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5))NEWLINEsslSecurityHttpStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sslSecurityHttpStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sslSecurityHttpStatus.setDescription('This object is for enabling or disabling secure HTTP in the system.')NEWLINEsslCiphers = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 2))NEWLINEsslCipherSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 5, 2, 1), Bits().clone(namedValues=NamedValues(("rsa-null-md5", 0), ("rsa-null-sha", 1), ("rsa-des-sha", 2), ("rsa-3des-sha", 3), ("dh-rsa-des-sha", 4), ("dh-rsa-3des-sha", 5), ("rsa-exp1024-des-sha", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sslCipherSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sslCipherSuiteList.setDescription('This object is to configure the cipher-suites list.')NEWLINEsecuritySSH = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8))NEWLINEsshSecurityStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshSecurityStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshSecurityStatus.setDescription('This object is for enabling or disabling ssh in the system.')NEWLINEsshMaxAuthFailAttempts = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMaxAuthFailAttempts.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMaxAuthFailAttempts.setDescription('This object indicates the max auth fail retry attempt times.')NEWLINEsshSessionKeyRekeying = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("never", 0), ("ten-min", 1), ("thirty-min", 2), ("sixty-min", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshSessionKeyRekeying.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshSessionKeyRekeying.setDescription('This object indicates one SSH session rekey time interval.')NEWLINEsshMaxSession = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMaxSession.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMaxSession.setDescription('This object indicates max SSH session number supported in system.')NEWLINEsshConnectionTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(120, 600))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshConnectionTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshConnectionTimeout.setDescription('This object indicates SSH connection timeout value.')NEWLINEsshAuthenMethodPassWordAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPassWordAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPassWordAdmin.setDescription('The object indicates authen method password is enabled or disabled.')NEWLINEsshAuthenMethodPubKeyAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPubKeyAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodPubKeyAdmin.setDescription('The object indicates authen method public-key is enabled or disabled.')NEWLINEsshAuthenMethodHostKeyAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshAuthenMethodHostKeyAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshAuthenMethodHostKeyAdmin.setDescription('The object indicates authen method host-key is enabled or disabled.')NEWLINEsshCipherSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 9), Bits().clone(namedValues=NamedValues(("tripleDESCBC", 0)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshCipherSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshCipherSuiteList.setDescription('This object is to configure the cipher-suites list.')NEWLINEsshMacSuiteList = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 10), Bits().clone(namedValues=NamedValues(("hMAC-SHA1", 0), ("hMAC-MD5", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshMacSuiteList.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshMacSuiteList.setDescription('This object is to configure the MAC-list.')NEWLINEsshPublKeyRSAAdmin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshPublKeyRSAAdmin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshPublKeyRSAAdmin.setDescription('The object indicates Public key generating algorithm RSA is enabled or disabled.')NEWLINEsshUserInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12), )NEWLINEif mibBuilder.loadTexts: sshUserInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoTable.setDescription('A table to configure SSH user auth in the system.')NEWLINEsshUserInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sshUserInfoID"))NEWLINEif mibBuilder.loadTexts: sshUserInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoEntry.setDescription('An entry to configure user auth in the system.')NEWLINEsshUserInfoID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshUserInfoID.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoID.setDescription('The Schedule identifier. The maximum number of Schedule entry is the number of ports supported PoE function. The value must be between 1 and 8.')NEWLINEsshUserInfoUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sshUserInfoUserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoUserName.setDescription("The ssh user name associated with the SSH suer Info. entry (e.g., `admin, user').")NEWLINEsshUserInfoAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 2, 1))).clone(namedValues=NamedValues(("publickey", 4), ("password", 2), ("hostbased", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoAuth.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoAuth.setDescription('The object indicates which auth used by the user.')NEWLINEsshUserInfoHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoHostName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoHostName.setDescription("The ssh host name associated with the SSH suer Info. entry (e.g., `DUT1, DUT2').")NEWLINEsshUserInfoHostIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 8, 12, 1, 5), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sshUserInfoHostIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: sshUserInfoHostIp.setDescription('SSH HostBased IP Address of the system.')NEWLINEsecurityPortSecurity = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2))NEWLINEportSecTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1), )NEWLINEif mibBuilder.loadTexts: portSecTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecTable.setDescription('A table to control port security features of the device.')NEWLINEportSecEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "portSecIndex"))NEWLINEif mibBuilder.loadTexts: portSecEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecEntry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEportSecIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEportSecState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecState.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecState.setDescription("Enable / disable port security admin state for the interface. A given ports' dynamic MAC address learning will be stopped such that the current source MAC addresses entered into the MAC address forwarding table can not be changed once the port security admin state is enabled.")NEWLINEportSecMLA = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecMLA.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecMLA.setDescription("Configures interface port security maximum learning address numbers. When given ports' admin state is enabled, allows forwarding table learning address number. The number can be set 0 to 64. Note: Set value 0 means cannot learn MAC address.")NEWLINEportSecLockAddrMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("deleteOnReset", 1), ("deleteOnTimeout", 2), ("permanent", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: portSecLockAddrMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecLockAddrMode.setDescription('Configures port security lock address mode for the interface. deleteOnReset : The locked addresses will not age out until the Switch has been reset. deleteOnTimeout : The locked addresses will age out after the aging timer expires. Permanent : The locked addresses will not age out after the aging timer expires.')NEWLINEportSecFDBPermanentTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2), )NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentTable.setDescription('A table to control port security FDB Permanent of the device.')NEWLINEportSecFDBPermanentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "portSecFDBPermPort"), (0, "DES-1210-28MEbx", "portSecFDBPermIndex"))NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermanentEntry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEportSecFDBPermIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermIndex.setDescription('The index of the port security MAC entry. For all machines give maximum port number.')NEWLINEportSecFDBPermVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermVlanID.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermVlanID.setDescription('The VLAN ID of the port security MAC entry.')NEWLINEportSecFDBPermMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermMac.setDescription('The MAC address associated of the port security MAC entry.')NEWLINEportSecFDBPermPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 2, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: portSecFDBPermPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: portSecFDBPermPort.setDescription('The forwarding port of the port security MAC entry. For all machines give maximum port number.')NEWLINEcableDiagTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1), )NEWLINEif mibBuilder.loadTexts: cableDiagTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagTable.setDescription('A table that contains the cable situation for each port.')NEWLINEcableDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cableDiagPortIndex"))NEWLINEif mibBuilder.loadTexts: cableDiagEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagEntry.setDescription('A list of cable situations for each port on the device.')NEWLINEcableDiagPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPortIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEcableDiagPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("fastEthernet", 0), ("gigaEthernet", 1), ("other", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPortType.setDescription('Indicates the supported port data rate classification.')NEWLINEcableDiagLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("linkdown", 0), ("linkup", 1), ("other", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagLinkStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagLinkStatus.setDescription('This object indicates the link status.')NEWLINEcableDiagPair1Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair1Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair1Status.setDescription('Cable diagnostics pair 1 test result.')NEWLINEcableDiagPair2Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair2Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair2Status.setDescription('Cable diagnostics pair 2 test result.')NEWLINEcableDiagPair3Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair3Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair3Status.setDescription('Cable diagnostics pair 3 test result.')NEWLINEcableDiagPair4Status = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("ok", 0), ("open", 1), ("short", 2), ("open-short", 3), ("crosstalk", 4), ("unknown", 5), ("count", 6), ("no-cable", 7), ("other", 8)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair4Status.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair4Status.setDescription('Cable diagnostics pair 4 test result.')NEWLINEcableDiagPair1Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 8), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair1Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair1Length.setDescription('Cable Diagnostics pair 1 fault distance.')NEWLINEcableDiagPair2Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 9), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair2Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair2Length.setDescription('Cable diagnostics pair 2 fault distance.')NEWLINEcableDiagPair3Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 10), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair3Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair3Length.setDescription('Cable diagnostics pair 3 fault distance.')NEWLINEcableDiagPair4Length = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 11), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagPair4Length.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagPair4Length.setDescription('Cable diagnostics pair 4 fault distance.')NEWLINEcableDiagAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("action", 1), ("processing", 2), ("other", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cableDiagAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagAction.setDescription('Function to run the cable diagnostic on selected port. Can not detect fiber ports')NEWLINEcableDiagStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 35, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("notrun", 1), ("processing", 2), ("lasttestok", 3), ("lasttestfailed", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cableDiagStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cableDiagStatus.setDescription('Indicates the status of cable diagnostics on the port. not-run - cable diagnostics has never been run for this port processing - cable diagnostics is currently running on the port last-test-ok - the last cable diagnostics done on the port was successful last-test-failed - the last cable diagnostics done on the port failed')NEWLINEaclProfile = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1))NEWLINEipv4aclProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1), )NEWLINEif mibBuilder.loadTexts: ipv4aclProfileTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileTable.setDescription(' A table to ACL profile . ')NEWLINEipv4aclProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4aclProfileNo"))NEWLINEif mibBuilder.loadTexts: ipv4aclProfileEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileEntry.setDescription(' Each entry in this table is a ACL profile. Index to the table is ACL profile ID. ')NEWLINEipv4aclProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileNo.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileNo.setDescription('The ACL Profile ID. The ID 1 to 50 is user-defined ACL, and the ID more than 50 is reserved for system-defined ACL. The user only allow to create user-defined ACL ID. And system-defined ACL is read only.')NEWLINEipv4aclProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 8, 9))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("impb", 3), ("arpSP-permit", 4), ("arpSP-deny", 5), ("aclQos", 8), ("userDefined", 9)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileType.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileType.setDescription('The ACL Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, arpSP_permit(4) - for ARP Spoofing prevention entry, arpSP_deny(5) - for ARP Spoofing prevention entry, voiceVlan(6) - for Voice VLAN OUI entry. userDefined(9) - for User Defined entry. Note that only l2, l3 and userDefined could be set by user, other is reserved for system to show information. ')NEWLINEipv4aclProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileRuleCount.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEipv4aclProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 ARP-SP ARP_SENDER_MAC 14 ARP-SP ARP_SENDER_IP 15 L3 TOS 16 UDF UDF1 17 UDF UDF2 18 UDF UDF3 19 UDF UDF4 20 L3v6 TRAFFIC_CLASS 21 L3v6 DST_IPV6 22 L3v6 SRC_IPV6 23 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEipv4aclProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstMacAddrMask.setDescription('The ACL Profile destination MAC address mask. If DST_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4aclProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcMacAddrMask.setDescription('The ACL Profile source MAC address mask. If SRC_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4aclProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 58, 256))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("icmpv6", 58), ("ipProtocolMask", 256)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocol.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEipv4aclProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocolMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileIPProtocolMask.setDescription('The ACL Profile IP protocol mask. If aclProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstIpAddrMask.setDescription("The ACL Profile destination IP address mask. If DST_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4aclProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcIpAddrMask.setDescription("The ACL Profile source IP address mask. If SRC_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4aclProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 11), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstPortMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileDstPortMask.setDescription('The ACL Profile UDP/TCP destination port mask. If DST_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 12), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcPortMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileSrcPortMask.setDescription('The ACL Profile UDP/TCP source port mask. If SRC_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEipv4aclProfileArpSenderMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 13), MacAddress().clone(hexValue="FFFFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderMacAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderMacAddrMask.setDescription("The ACL Profile Sender MAC mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEipv4aclProfileArpSenderIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 14), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderIpAddrMask.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileArpSenderIpAddrMask.setDescription("The ACL Profile Sender IP mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEipv4aclProfileUdfOffsetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 15), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileUdfOffsetMap.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileUdfOffsetMap.setDescription('Indicate which Udf field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ UDF Offset1 0 (LSB) UDF Offset2 1 UDF Offset3 2 UDF Offset4 3 ------------------------------------------- The value is in Hex format. ')NEWLINEipv4aclUdfOffsetBase1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase1.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte1.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 18), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask1.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask1.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase2.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte2.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 21), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask2.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask2.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase3.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 23), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte3.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 24), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask3.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask3.setDescription('The value of offset MAsk.')NEWLINEipv4aclUdfOffsetBase4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetBase4.setDescription('The value of offset Base.')NEWLINEipv4aclUdfOffsetByte4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetByte4.setDescription('The value of offset Byte from base.')NEWLINEipv4aclUdfOffsetMask4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 27), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask4.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclUdfOffsetMask4.setDescription('The value of offset MAsk.')NEWLINEipv4aclProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 1, 1, 28), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4aclProfileStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4aclProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of aclProfileType, aclProfileMask and ProtocolType are not conflicted. ")NEWLINEaclProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2), )NEWLINEif mibBuilder.loadTexts: aclProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileTable.setDescription(' A table to ACL profile . ')NEWLINEaclProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclProfileNo"))NEWLINEif mibBuilder.loadTexts: aclProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileEntry.setDescription(' Each entry in this table is a ACL profile. Index to the table is ACL profile ID. ')NEWLINEaclProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileNo.setDescription('The ACL Profile ID. The ID 1 to 50 is user-defined ACL, and the ID more than 50 is reserved for system-defined ACL. The user only allow to create user-defined ACL ID. And system-defined ACL is read only.')NEWLINEaclProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11, 3, 4, 5, 8, 9))).clone(namedValues=NamedValues(("l2", 1), ("l3v4", 2), ("l3v6", 11), ("impb", 3), ("arpSP-permit", 4), ("arpSP-deny", 5), ("aclQos", 8), ("userDefined", 9)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileType.setDescription('The ACL Profile type, possible value are l2 (1) - for MAC-based rule, l3v4 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule, arpSP_permit(4) - for ARP Spoofing prevention entry, arpSP_deny(5) - for ARP Spoofing prevention entry, voiceVlan(6) - for Voice VLAN OUI entry. userDefined(9) - for User Defined entry. Note that only l2, l3 and userDefined could be set by user, other is reserved for system to show information. ')NEWLINEaclProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEaclProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 ARP-SP ARP_SENDER_MAC 14 ARP-SP ARP_SENDER_IP 15 L3 TRAFFIC_CLASS 21 L3 TOS 16 UDF UDF1 17 UDF UDF2 18 UDF UDF3 19 UDF UDF4 20 L3v6 TRAFFIC_CLASS 21 L3v6 DST_IPV6 22 L3v6 SRC_IPV6 23 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEaclProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstMacAddrMask.setDescription('The ACL Profile destination MAC address mask. If DST_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEaclProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcMacAddrMask.setDescription('The ACL Profile source MAC address mask. If SRC_MAC is turn on in aclProfileMask, it will work with its member rule field,aclL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEaclProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 58, 256))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("icmpv6", 58), ("ipProtocolMask", 256)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEaclProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileIPProtocolMask.setDescription('The ACL Profile IP protocol mask. If aclProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEaclProfileDstIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEaclProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstIpAddrMask.setDescription("The ACL Profile destination IP address mask. If DST_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEaclProfileSrcIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEaclProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 12), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcIpAddrMask.setDescription("The ACL Profile source IP address mask. If SRC_IP is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEaclProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 13), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileDstPortMask.setDescription('The ACL Profile UDP/TCP destination port mask. If DST_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEaclProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileSrcPortMask.setDescription('The ACL Profile UDP/TCP source port mask. If SRC_PORT is turn on in aclProfileMask, it will work with its member rule field,aclL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEaclProfileArpSenderMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 15), MacAddress().clone(hexValue="FFFFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderMacAddrMask.setDescription("The ACL Profile Sender MAC mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEaclProfileArpSenderIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 16), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileArpSenderIpAddrMask.setDescription("The ACL Profile Sender IP mask. This is only for ARP Spoofing Prevention which is System-defined ACL, and it's not allow to modify. The value is in HEX format. ")NEWLINEaclProfileUdfOffsetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 17), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclProfileUdfOffsetMap.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileUdfOffsetMap.setDescription('Indicate which Udf field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ UDF Offset1 0 (LSB) UDF Offset2 1 UDF Offset3 2 UDF Offset4 3 ------------------------------------------- The value is in Hex format. ')NEWLINEaclUdfOffsetBase1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase1.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte1.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 20), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask1.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase2.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte2.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 23), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask2.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase3.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 25), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte3.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 26), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask3.setDescription('The value of offset MAsk.')NEWLINEaclUdfOffsetBase4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2, 3))).clone(namedValues=NamedValues(("l2", 0), ("l3", 2), ("l4", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetBase4.setDescription('The value of offset Base.')NEWLINEaclUdfOffsetByte4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetByte4.setDescription('The value of offset Byte from base.')NEWLINEaclUdfOffsetMask4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 29), OctetString().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclUdfOffsetMask4.setDescription('The value of offset MAsk.')NEWLINEaclProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 1, 2, 1, 30), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of aclProfileType, aclProfileMask and ProtocolType are not conflicted. ")NEWLINEaclL2Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2))NEWLINEaclL2RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1), )NEWLINEif mibBuilder.loadTexts: aclL2RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEaclL2RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclL2ProfileID"), (0, "DES-1210-28MEbx", "aclL2AccessID"))NEWLINEif mibBuilder.loadTexts: aclL2RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEaclL2AccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2AccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2AccessID.setDescription('L2 Filter rule ID. 0 means auto assign.')NEWLINEaclL2ProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50)).clone(1)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2ProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2ProfileID.setDescription('ACL Profile ID which this rule join.')NEWLINEaclL2RuleEtherType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(1501, 65535), )).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleEtherType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleEtherType.setDescription("The value in the Type/Len field of a frame that will be matched to trigger this filter. The default value of this object is '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleDstMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 4), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddr.setDescription("Destination MAC address to be matched with the packet. By Default, the Destination Mac Address will be zero,which means the rule don't care this condition.")NEWLINEaclL2RuleSrcMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddr.setDescription("Source MAC address to be matched with the packet. By Default, the Source Mac Address will be zero, which means the rule don't care this condition.. address")NEWLINEaclL2RuleVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 4094)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanId.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2Rule1pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2Rule1pPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2Rule1pPriority.setDescription("802.1p priority to be matched with the packet. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 8), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleDstMacAddrMask.setDescription("The MAC address Mask work for Destination MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEaclL2RuleSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 9), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleSrcMacAddrMask.setDescription("The MAC address Mask work for Source MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEaclL2RuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 10), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEaclL2RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEaclL2RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 12), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclL2RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclL2RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplace1P.setDescription('Replace DSCP for matched packet.')NEWLINEaclL2RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleReplaceQueue.setDescription('ACL L2 Rule Replace Queue.')NEWLINEaclL2RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 16), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL2RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleFilterTimeRange.setDescription('ACL L2 Filter Time Range')NEWLINEaclL2RuleVlanIdMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 17), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanIdMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleVlanIdMask.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEaclL2RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 2, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL2RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL2RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclL3Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3))NEWLINEaclL3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1), )NEWLINEif mibBuilder.loadTexts: aclL3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEaclL3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclL3RuleProfileNo"), (0, "DES-1210-28MEbx", "aclL3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: aclL3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEaclL3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleAccessID.setDescription('L3 Filter rule ID. 0 means auto assign.')NEWLINEaclL3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProfileNo.setDescription('The Profile ID which this rule join.')NEWLINEaclL3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEaclL3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEaclL3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEaclL3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEaclL3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclL3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 8), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclL3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclL3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dont_care'(-1). which means the rule don't care this condition.")NEWLINEaclL3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclL3RuleDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleDscp.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RuleTos = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleTos.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleTos.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RuleIgmpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 23), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleIgmpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleIgmpType.setDescription(" The IGMP Type to be checked against the packet.A default value is '-1', which means the rule don't care this condition.")NEWLINEaclL3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 24), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEaclL3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEaclL3RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 26), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclL3RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 27), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceDSCP.setDescription('ReplaceDSCP for matched packet.')NEWLINEaclL3RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplace1P.setDescription('ReplaceDSCP for matched packet.')NEWLINEaclL3RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 29), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleReplaceQueue.setDescription('Acl L3 Rule Replace Queue.')NEWLINEaclL3RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 30), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleFilterTimeRange.setDescription('ACL L3 Filter Time Range')NEWLINEaclL3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclL3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclL3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclv6L3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2), )NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEaclv6L3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclv6L3RuleProfileNo"), (0, "DES-1210-28MEbx", "aclv6L3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: aclv6L3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEaclv6L3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAccessID.setDescription('L3 Filter rule ID. 0 means auto assign.')NEWLINEaclv6L3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProfileNo.setDescription('The Profile ID which this rule join.')NEWLINEaclv6L3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(6, 17, 58))).clone(namedValues=NamedValues(("tcp", 6), ("udp", 17), ("icmpv6", 58)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEaclv6L3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,aclL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEaclv6L3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEaclv6L3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in aclL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEaclv6L3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 7), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclv6L3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 8), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEaclv6L3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 9), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEaclv6L3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dont_care'(-1). which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dont-care", -1), ("establish", 1), ("notEstablish", 2))).clone('dont-care')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dont_care'(-1), which means the rule don't care this condition.")NEWLINEaclv6L3RuleTrafficClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTrafficClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleTrafficClass.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEaclv6L3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 23), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEaclv6L3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEaclv6L3RuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 25), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclv6L3RuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclv6L3RuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 27), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplace1P.setDescription('Replace DSCP for matched packet.')NEWLINEaclv6L3RuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 28), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleReplaceQueue.setDescription('Acl IPV6 L3 Rule Replace Queue.')NEWLINEaclv6L3RuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 29), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleFilterTimeRange.setDescription('ACL IPV6 L3 Filter Time Range')NEWLINEaclv6L3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 3, 2, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclv6L3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclv6L3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclPacketRule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4))NEWLINEaclPacketRuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1), )NEWLINEif mibBuilder.loadTexts: aclPacketRuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleTable.setDescription('A table to configure Packet Content filter rules in the system.')NEWLINEaclPacketRuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclPacketProfileID"), (0, "DES-1210-28MEbx", "aclPacketAccessID"))NEWLINEif mibBuilder.loadTexts: aclPacketRuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleEntry.setDescription('Each entry in this table is a Packet filter rule. Index to the table is the Packet filter number and Profile ID.')NEWLINEaclPacketAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclPacketAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketAccessID.setDescription('Packet Filter rule ID. 0 means auto assign.')NEWLINEaclPacketProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclPacketProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketProfileID.setDescription('ACL Profile ID which this rule join.')NEWLINEaclPacketRuleOffsetValue1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 3), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1.setDescription('The filter value of Offset 1.')NEWLINEaclPacketRuleOffsetValue2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2.setDescription('The filter value of Offset 2.')NEWLINEaclPacketRuleOffsetValue3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 5), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3.setDescription('The filter value of Offset 3.')NEWLINEaclPacketRuleOffsetValue4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4.setDescription('The filter value of Offset 4.')NEWLINEaclPacketRuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 7), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEaclPacketRuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 5, 6, 7))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2), ("mirror", 3), ("replaceDSCP", 5), ("replace1P", 6), ("replaceQueue", 7))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEaclPacketRuleRateLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 9), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleRateLimit.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleRateLimit.setDescription('Rate limit for matched packet.')NEWLINEaclPacketRuleReplaceDSCP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceDSCP.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceDSCP.setDescription('Replace DSCP for matched packet.')NEWLINEaclPacketRuleReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplace1P.setDescription('Replace 1p for matched packet.')NEWLINEaclPacketRuleReplaceQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceQueue.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleReplaceQueue.setDescription('Acl Rule Replace Queue.')NEWLINEaclPacketRuleFilterTimeRange = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 13), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclPacketRuleFilterTimeRange.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleFilterTimeRange.setDescription('Acl Filter Time Range')NEWLINEaclPacketRuleOffsetValue1Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue1Mask.setDescription('The filter Mask of Offset 1.')NEWLINEaclPacketRuleOffsetValue2Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 15), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue2Mask.setDescription('The filter Mask of Offset 2.')NEWLINEaclPacketRuleOffsetValue3Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 16), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue3Mask.setDescription('The filter Mask of Offset 3.')NEWLINEaclPacketRuleOffsetValue4Mask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 17), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4Mask.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleOffsetValue4Mask.setDescription('The filter Mask of Offset 4.')NEWLINEaclPacketRuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 4, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclPacketRuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclPacketRuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaclFlowMeterRule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10))NEWLINEaclFlowMeterTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1), )NEWLINEif mibBuilder.loadTexts: aclFlowMeterTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEaclFlowMeterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aclFlowMeterProfileID"), (0, "DES-1210-28MEbx", "aclFlowMeterAccessID"))NEWLINEif mibBuilder.loadTexts: aclFlowMeterEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEaclFlowMeterProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 50))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclFlowMeterProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterProfileID.setDescription('ACL Profile ID which this flow meter join.')NEWLINEaclFlowMeterAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 250))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aclFlowMeterAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterAccessID.setDescription('ACL Access ID which this flow meter join.')NEWLINEaclFlowMeterRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(64, 1024000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterRate.setDescription('The rate limiter of meter.')NEWLINEaclFlowMeterBurstSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1016))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterBurstSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterBurstSize.setDescription('The burst size of meter.')NEWLINEaclFlowMeterReplaceDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 63))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterReplaceDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterReplaceDscp.setDescription('Replace DSCP for matched out-band packets when aclFlowMeterAction is replace DSCP.')NEWLINEaclFlowMeterAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 5))).clone(namedValues=NamedValues(("drop", 2), ("replaceDSCP", 5))).clone('drop')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aclFlowMeterAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterAction.setDescription("Specifies the action to be taken on the out-band packet if the filter rule matches. If the action is 'drop', the packet will be discarded.")NEWLINEaclFlowMeterStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 15, 10, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aclFlowMeterStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aclFlowMeterStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterProfile = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1))NEWLINEipv4cpuFilterProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1), )NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileTable.setDescription(' A table to CPUInterfaceFilter profile . ')NEWLINEipv4cpuFilterProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4cpuFilterProfileNo"))NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileEntry.setDescription(' Each entry in this table is a CPUInterfaceFilter profile. Index to the table is CPUInterfaceFilter profile ID. ')NEWLINEipv4cpuFilterProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileNo.setDescription('The CPUInterfaceFilter Profile ID. The ID 1 to 50 is user-defined CPUInterfaceFilter, and the ID more than 50 is reserved for system-defined CPUInterfaceFilter. The user only allow to create user-defined CPUInterfaceFilter ID. And system-defined CPUInterfaceFilter is read only.')NEWLINEipv4cpuFilterProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("l3v6", 11)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileType.setDescription('The CPUInterfaceFilter Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule ')NEWLINEipv4cpuFilterProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEipv4cpuFilterProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 (MSB) ------------------------------------------- The value is in Hex format. ')NEWLINEipv4cpuFilterProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstMacAddrMask.setDescription('The CPUInterfaceFilter Profile destination MAC address mask. If DST_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4cpuFilterProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcMacAddrMask.setDescription('The CPUInterfaceFilter Profile source MAC address mask. If SRC_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEipv4cpuFilterProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 255))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("ipMask", 255)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEipv4cpuFilterProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileIPProtocolMask.setDescription('The CPUInterfaceFilter Profile IP protocol mask. If cpuFilterProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstIpAddrMask.setDescription("The CPUInterfaceFilter Profile destination IP address mask. If DST_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4cpuFilterProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcIpAddrMask.setDescription("The CPUInterfaceFilter Profile source IP address mask. If SRC_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEipv4cpuFilterProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 11), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileDstPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP destination port mask. If DST_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 12), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileSrcPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP source port mask. If SRC_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEipv4cpuFilterProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 1, 1, 15), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4cpuFilterProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of cpuFilterProfileType, cpuFilterProfileMask and ProtocolType are not conflicted. ")NEWLINEcpuFilterProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2), )NEWLINEif mibBuilder.loadTexts: cpuFilterProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileTable.setDescription(' A table to CPUInterfaceFilter profile . ')NEWLINEcpuFilterProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterProfileNo"))NEWLINEif mibBuilder.loadTexts: cpuFilterProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileEntry.setDescription(' Each entry in this table is a CPUInterfaceFilter profile. Index to the table is CPUInterfaceFilter profile ID. ')NEWLINEcpuFilterProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileNo.setDescription('The CPUInterfaceFilter Profile ID. The ID 1 to 50 is user-defined CPUInterfaceFilter, and the ID more than 50 is reserved for system-defined CPUInterfaceFilter. The user only allow to create user-defined CPUInterfaceFilter ID. And system-defined CPUInterfaceFilter is read only.')NEWLINEcpuFilterProfileType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 11))).clone(namedValues=NamedValues(("l2", 1), ("l3", 2), ("l3v6", 11)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileType.setDescription('The CPUInterfaceFilter Profile type, possible value are l2 (1) - for MAC-based rule, l3 (2) - for IPv4-based rule, l3v6 (11) - for IPv6-based rule ')NEWLINEcpuFilterProfileRuleCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileRuleCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileRuleCount.setDescription('The number of rules in this profile.')NEWLINEcpuFilterProfileMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileMask.setDescription('Indicate which field want to care in the packet. Turn on the following bits to select the following items Type Item BIT ------------------------------------------ L2 DST_MAC 0 (LSB) L2 SRC_MAC 1 L2 VID 2 L2 8021P_PRIORITY 3 L2 ETHER_TYPE 4 L3 DSCP 5 L3 ICMP_TYPE 6 L3 ICMP_CODE 7 L3 IGMP_TYPE 8 L3 DST_IP 9 L3 SRC_IP 10 L3 DST_PORT 11 L3 SRC_PORT 12 L3 TCPFLAG 13 (MSB) L3 TRAFFIC_CLASS 21 ------------------------------------------- The value is in Hex format. ')NEWLINEcpuFilterProfileDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstMacAddrMask.setDescription('The CPUInterfaceFilter Profile destination MAC address mask. If DST_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleDstMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEcpuFilterProfileSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 6), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcMacAddrMask.setDescription('The CPUInterfaceFilter Profile source MAC address mask. If SRC_MAC is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL2RuleSrcMacAddr, to caculate a range of MAC address which is really care. ')NEWLINEcpuFilterProfileIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 6, 17, 255))).clone(namedValues=NamedValues(("none", 0), ("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17), ("ipMask", 255)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocol.setDescription('Indicate which IP Protocol will be care in this profile. Only profile type is l3 can set the IP protocol. For others, this field will be none. ')NEWLINEcpuFilterProfileIPProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 8), OctetString().clone(hexValue="FF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileIPProtocolMask.setDescription('The CPUInterfaceFilter Profile IP protocol mask. If cpuFilterProfileIPProtocol set to ipMask, this field will be refered. It will work with its member rule field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileDstIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEcpuFilterProfileDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstIpAddrMask.setDescription("The CPUInterfaceFilter Profile destination IP address mask. If DST_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleDstIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEcpuFilterProfileSrcIpAddrMaskType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMaskType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMaskType.setDescription('IPv6 Address type.')NEWLINEcpuFilterProfileSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 12), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcIpAddrMask.setDescription("The CPUInterfaceFilter Profile source IP address mask. If SRC_IP is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleSrcIpAddr, to caculate a range of IP address which is really care. The value is in HEX format, for example: '255.255.255.0' is presented to 'FFFFFF00' ")NEWLINEcpuFilterProfileDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 13), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileDstPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP destination port mask. If DST_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpDstPort, to caculate a range of destination port which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 14), OctetString().clone(hexValue="FFFF")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileSrcPortMask.setDescription('The CPUInterfaceFilter Profile UDP/TCP source port mask. If SRC_PORT is turn on in cpuFilterProfileMask, it will work with its member rule field,cpuFilterL3RuleTcpUdpSrcPort, to caculate a range of source port which is really care. The value is in HEX format. ')NEWLINEcpuFilterProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 1, 2, 1, 15), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterProfileStatus.setDescription(" This object indicates the status of this entry, can only be set to 'createAndWait','active' and 'destroy'. When the value of the entry status is 'createAndWait', it could be set to 'active' only if the three values of cpuFilterProfileType, cpuFilterProfileMask and ProtocolType are not conflicted. ")NEWLINEcpuFilterL2Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2))NEWLINEcpuFilterL2RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1), )NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleTable.setDescription('A table to configure L2 filter rules in the system.')NEWLINEcpuFilterL2RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterL2ProfileID"), (0, "DES-1210-28MEbx", "cpuFilterL2AccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEntry.setDescription('Each entry in this table is a L2 filter rule. Index to the table is the L2 filter number and Profile ID.')NEWLINEcpuFilterL2ProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2ProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2ProfileID.setDescription('L2 Filter rule ID.')NEWLINEcpuFilterL2AccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5)).clone(1)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2AccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2AccessID.setDescription('CPUInterfaceFilter Profile ID which this rule join.')NEWLINEcpuFilterL2RuleEtherType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(1501, 65535), )).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEtherType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleEtherType.setDescription("The value in the Type/Len field of a frame that will be matched to trigger this filter. The default value of this object is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleDstMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 4), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddr.setDescription("Destination MAC address to be matched with the packet. By Default, the Destination Mac Address will be zero,which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleSrcMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 5), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddr.setDescription("Source MAC address to be matched with the packet. By Default, the Source Mac Address will be zero, which means the rule don't care this condition.. address")NEWLINEcpuFilterL2RuleVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 4094)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleVlanId.setDescription("Vlan Id to be filtered. In case of Provider bridges, This Vlan Id will be treated as customer Vlan Id. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2Rule1pPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2Rule1pPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2Rule1pPriority.setDescription("802.1p priority to be matched with the packet. By Default, the value will be '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL2RuleDstMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 8), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleDstMacAddrMask.setDescription("The MAC address Mask work for Destination MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEcpuFilterL2RuleSrcMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 9), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleSrcMacAddrMask.setDescription("The MAC address Mask work for Source MAC address. This field is read-only and copy from it's Profile setting.")NEWLINEcpuFilterL2RuleInPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 10), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleInPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleInPortList.setDescription('Specifies the complete set of ports over which this filter is applied for packets ingress at ports in this list.')NEWLINEcpuFilterL2RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleAction.setDescription("Specifies the action to be taken on the packet if the filter rule matches. If the action is 'allow', the packet will be forwarded according to the forwarding rules. If the action is 'drop', the packet will be discarded.")NEWLINEcpuFilterL2RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 2, 1, 1, 14), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL2RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterL3Rule = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3))NEWLINEcpuFilterL3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1), )NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEcpuFilterL3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterL3RuleProfileNo"), (0, "DES-1210-28MEbx", "cpuFilterL3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEcpuFilterL3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProfileNo.setDescription('L3 Filter rule ID.')NEWLINEcpuFilterL3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAccessID.setDescription('The Profile ID which this rule join.')NEWLINEcpuFilterL3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("igmp", 2), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEcpuFilterL3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEcpuFilterL3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEcpuFilterL3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEcpuFilterL3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 7), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 8), IpAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 9), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 10), IpAddress().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterL3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dontcare'(-1). which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDscp.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleDscp.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL3RuleIgmpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 22), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleIgmpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleIgmpType.setDescription(" The IGMP Type to be checked against the packet.A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterL3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 23), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEcpuFilterL3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEcpuFilterL3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 1, 1, 27), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterL3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEcpuFilterv6L3RuleTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2), )NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTable.setDescription(' A table to configure L3 filter rules in the system. ')NEWLINEcpuFilterv6L3RuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "cpuFilterv6L3RuleProfileNo"), (0, "DES-1210-28MEbx", "cpuFilterv6L3RuleAccessID"))NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleEntry.setDescription(' Each entry in this table is a L3 filter rule. Index to the table is L3 filter number and Profile ID.')NEWLINEcpuFilterv6L3RuleProfileNo = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProfileNo.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProfileNo.setDescription('L3 Filter rule ID.')NEWLINEcpuFilterv6L3RuleAccessID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAccessID.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAccessID.setDescription('The Profile ID which this rule join.')NEWLINEcpuFilterv6L3RuleProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 6, 17))).clone(namedValues=NamedValues(("icmp", 1), ("tcp", 6), ("udp", 17)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocol.setDescription(' The type of protocol to be checked against the packet.')NEWLINEcpuFilterv6L3RuleProtocolMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 4), OctetString().clone(hexValue="FF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocolMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleProtocolMask.setDescription("The IP protocol mask. This field is read-only and copy from it's Profile setting. It will work with the other field,cpuFilterL3RuleProtocol, to caculate a range of IP protocol which is really care. The value is in HEX format. ")NEWLINEcpuFilterv6L3RuleICMPMessageType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageType.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageType.setDescription(" The message type to be checked against the packet. If the message type matches with the packet, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1',which means the rule don't care this condition. Some ICMP message types are: echoReply(0), destinationUnreachable(3), sourceQuench(4), redirect(5), echoRequest(8), timeExceeded(11), parameterProblem(12), timestampRequest(13), timestampReply(14), informationRequest(15), informationReply(16), addressMaskRequest(17), addressMaskReply (18), ")NEWLINEcpuFilterv6L3RuleICMPMessageCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleICMPMessageCode.setDescription(" The message code to be checked against the packet. If the packet matches with the message code, then the packet will be dropped / allowed based on the action set in cpuFilterL3RuleAction. The default value is '-1', which means the rule don't care this condition. Some ICMP message codes are : networkUnreachable(0), hostUnreachable(1), protocolUnreachable(2), portUnreachable(3), fragmentNeed(4), sourceRouteFail(5), destNetworkUnknown(6), destHostUnknown(7), srcHostIsolated(8), destNetworkAdminProhibited(9), destHostAdminProhibited(10), networkUnreachableTOS(11), hostUnreachableTOS(12), ")NEWLINEcpuFilterv6L3RuleDstIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 7), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddr.setDescription("Destination IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleSrcIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 8), Ipv6Address().clone(hexValue="00000000")).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddr.setDescription("Source IP address to be matched with the packet. The default value will be zero, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleDstIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 9), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleDstIpAddrMask.setDescription("The IP subnet mask for Destination IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleSrcIpAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 10), Ipv6Address().clone(hexValue="FFFFFFFF")).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleSrcIpAddrMask.setDescription("The IP subnet mask for Source IP address. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpUdpDstPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPort.setDescription("The TCP / UDP destination port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUdpSrcPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 65535)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPort.setDescription("The TCP / UDP source port. The default value is -1, which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUdpDstPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 13), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpDstPortMask.setDescription("The TCP / UDP Destination port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpUdpSrcPortMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 14), OctetString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPortMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUdpSrcPortMask.setDescription("The TCP / UDP Source port Mask. This field is read-only and copy from it's Profile setting. ")NEWLINEcpuFilterv6L3RuleTcpAckBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpAckBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpAckBit.setDescription(" The TCP ACK bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpRstBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpRstBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpRstBit.setDescription(" The TCP RST bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpUrgBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUrgBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpUrgBit.setDescription(" The TCP Urg bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpPshBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpPshBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpPshBit.setDescription(" The TCP Psh bit to be checked against the packet. The default value is 'dontcare'(-1). which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpSynBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpSynBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpSynBit.setDescription(" The TCP Syn bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTcpFinBit = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 1, 2))).clone(namedValues=NamedValues(("dontcare", -1), ("establish", 1), ("notEstablish", 2))).clone('dontcare')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpFinBit.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTcpFinBit.setDescription(" The TCP Fin bit to be checked against the packet. The default value is 'dontcare'(-1), which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RuleTrafficClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63)).clone(-1)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTrafficClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleTrafficClass.setDescription(" The IP Dscp value to be checked against the packet. A default value is '-1', which means the rule don't care this condition.")NEWLINEcpuFilterv6L3RulePortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 22), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RulePortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RulePortList.setDescription('Specifies the complete set of ports over which if the packet arrives this filter rule will be applicable.')NEWLINEcpuFilterv6L3RuleAction = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("drop", 2))).clone('allow')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAction.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleAction.setDescription('Specifies the action to be taken on the packet if the filter rule matches.')NEWLINEcpuFilterv6L3RuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 33, 3, 2, 1, 24), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: cpuFilterv6L3RuleStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEsnmpGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpGlobalState.setDescription('This object is for enabling or disabling SNMP Community function.')NEWLINEsnmpV3User = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2))NEWLINEsnmpV3Group = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3))NEWLINEsnmpV3ViewTree = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4))NEWLINEsnmpV3Community = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5))NEWLINEsnmpV3Host = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6))NEWLINEsnmpV3EngineID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 7), SnmpEngineID()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3EngineID.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3EngineID.setDescription("An SNMP engine's administratively-unique identifier. In a simple agent, this value is always that agent's own snmpEngineID value. The value can also take the value of the snmpEngineID of a remote SNMP engine with which this user can communicate.")NEWLINEsnmpV3Trap = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8))NEWLINEsnmpV3UserTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3UserTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserTable.setDescription('')NEWLINEsnmpV3UserEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3UserName"), (0, "DES-1210-28MEbx", "snmpV3UserVersion"))NEWLINEif mibBuilder.loadTexts: snmpV3UserEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserEntry.setDescription('')NEWLINEsnmpV3UserName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3UserName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserName.setDescription('A human readable string representing the name of the user. This is the (User-based Security) Model dependent security ID. ')NEWLINEsnmpV3UserVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3UserVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserVersion.setDescription('A human readable string representing the name of the user. This is the (User-based Security) Model dependent security ID. ')NEWLINEsnmpV3UserGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserGroupName.setDescription('The name of the group to which this entry (e.g., the combination of securityModel and securityName) belongs. This groupName is used as index into the vacmAccessTable to select an access control policy. However, a value in this table does not imply that an instance with the value exists in table vacmAccesTable. ')NEWLINEsnmpV3UserAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("md5", 2), ("sha", 3)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocol.setDescription("An indication of whether messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, can be authenticated, and if so, the type of authentication protocol which is used. An instance of this object is created concurrently with the creation of any other object instance for the same user (i.e., as part of the processing of the set operation which creates the first object instance in the same conceptual row). If an initial set operation (i.e. at row creation time) tries to set a value for an unknown or unsupported protocol, then a 'wrongValue' error must be returned. The value will be overwritten/set when a set operation is performed on the corresponding instance of UserCloneFrom. Once instantiated, the value of such an instance of this object can only be changed via a set operation to the value of the NoAuthProtocol. If a set operation tries to change the value of an existing instance of this object to any value other than NoAuthProtocol, then an 'inconsistentValue' error must be returned. If a set operation tries to set the value to the NoAuthProtocol while the UserPrivProtocol value in the same row is not equal to NoPrivProtocol, then an 'inconsistentValue' error must be returned. That means that an SNMP command generator application must first ensure that the UserPrivProtocol is set to the NoPrivProtocol value before it can set the UserAuthProtocol value to NoAuthProtocol. ")NEWLINEsnmpV3UserAuthProtocolPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocolPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserAuthProtocolPassword.setDescription('')NEWLINEsnmpV3UserPrivProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("des", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocol.setDescription("An indication of whether messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, can be protected from disclosure, and if so, the type of privacy protocol which is used. An instance of this object is created concurrently with the creation of any other object instance for the same user (i.e., as part of the processing of the set operation which creates the first object instance in the same conceptual row). If an initial set operation (i.e. at row creation time) tries to set a value for an unknown or unsupported protocol, then a 'wrongValue' error must be returned. The value will be overwritten/set when a set operation is performed on the corresponding instance of usmUserCloneFrom. Once instantiated, the value of such an instance of this object can only be changed via a set operation to the value of the NoPrivProtocol. If a set operation tries to change the value of an existing instance of this object to any value other than NoPrivProtocol, then an 'inconsistentValue' error must be returned. Note that if any privacy protocol is used, then you must also use an authentication protocol. In other words, if usmUserPrivProtocol is set to anything else than NoPrivProtocol, then the corresponding instance of usmUserAuthProtocol cannot have a value of usmNoAuthProtocol. If it does, then an 'inconsistentValue' error must be returned. ")NEWLINEsnmpV3UserPrivProtocolPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocolPassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserPrivProtocolPassword.setDescription('')NEWLINEsnmpV3UserStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 2, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3UserStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3UserStatus.setDescription("The status of this conceptual row. Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the usmUserStatus column is 'notReady'. In particular, a newly created row for a user who employs authentication, cannot be made active until the corresponding usmUserCloneFrom and usmUserAuthKeyChange have been set. Further, a newly created row for a user who also employs privacy, cannot be made active until the usmUserPrivKeyChange has been set. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified, except for usmUserOwnAuthKeyChange and usmUserOwnPrivKeyChange. For these 2 objects, the value of usmUserStatus MUST be active. ")NEWLINEsnmpV3GroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3GroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupTable.setDescription('')NEWLINEsnmpV3GroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3GroupName"), (0, "DES-1210-28MEbx", "snmpV3GroupSecurityModel"), (0, "DES-1210-28MEbx", "snmpV3GroupSecurityLevel"))NEWLINEif mibBuilder.loadTexts: snmpV3GroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupEntry.setDescription('')NEWLINEsnmpV3GroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupName.setDescription('The name of the group to which this entry (e.g., the combination of securityModel and securityName) belongs. This groupName is used as index into the vacmAccessTable to select an access control policy. However, a value in this table does not imply that an instance with the value exists in table vacmAccesTable. ')NEWLINEsnmpV3GroupSecurityModel = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3", 3)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityModel.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityModel.setDescription('In order to gain the access rights allowed by this conceptual row, this securityModel must be in use. ')NEWLINEsnmpV3GroupSecurityLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 3), SnmpSecurityLevel()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityLevel.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupSecurityLevel.setDescription('The minimum level of security required in order to gain the access rights allowed by this conceptual row. A securityLevel of noAuthNoPriv is less than authNoPriv which in turn is less than authPriv. If multiple entries are equally indexed except for this vacmAccessSecurityLevel index, then the entry which has the highest value for vacmAccessSecurityLevel is selected. ')NEWLINEsnmpV3GroupReadViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 4), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupReadViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupReadViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes read access. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupWriteViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupWriteViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupWriteViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes write access. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupNotifyViewName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupNotifyViewName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupNotifyViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes access for notifications. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ')NEWLINEsnmpV3GroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 3, 1, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3GroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3GroupStatus.setDescription('The status of this conceptual row. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ')NEWLINEsnmpV3ViewTreeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeTable.setDescription('')NEWLINEsnmpV3ViewTreeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3viewTreeName"), (0, "DES-1210-28MEbx", "snmpV3viewTreeSubtree"))NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3ViewTreeEntry.setDescription('')NEWLINEsnmpV3viewTreeName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeName.setDescription('The human readable name for a family of view subtrees. ')NEWLINEsnmpV3viewTreeSubtree = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeSubtree.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeSubtree.setDescription('The MIB subtree which when combined with the corresponding instance of vacmViewTreeFamilyMask defines a family of view subtrees. ')NEWLINEsnmpV3viewTreeMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeMask.setDescription("The bit mask which, in combination with the corresponding instance of vacmViewTreeFamilySubtree, defines a family of view subtrees. Each bit of this bit mask corresponds to a sub-identifier of vacmViewTreeFamilySubtree, with the most significant bit of the i-th octet of this octet string value (extended if necessary, see below) corresponding to the (8*i - 7)-th sub-identifier, and the least significant bit of the i-th octet of this octet string corresponding to the (8*i)-th sub-identifier, where i is in the range 1 through 16. Each bit of this bit mask specifies whether or not the corresponding sub-identifiers must match when determining if an OBJECT IDENTIFIER is in this family of view subtrees; a '1' indicates that an exact match must occur; a '0' indicates 'wild card', i.e., any sub-identifier value matches. Thus, the OBJECT IDENTIFIER X of an object instance is contained in a family of view subtrees if, for each sub-identifier of the value of vacmViewTreeFamilySubtree, either: the i-th bit of vacmViewTreeFamilyMask is 0, or the i-th sub-identifier of X is equal to the i-th sub-identifier of the value of vacmViewTreeFamilySubtree. If the value of this bit mask is M bits long and there are more than M sub-identifiers in the corresponding instance of vacmViewTreeFamilySubtree, then the bit mask is extended with 1's to be the required length. Note that when the value of this object is the zero-length string, this extension rule results in a mask of all-1's being used (i.e., no 'wild card'), and the family of view subtrees is the one view subtree uniquely identified by the corresponding instance of vacmViewTreeFamilySubtree. Note that masks of length greater than zero length do not need to be supported. In this case this object is made read-only. ")NEWLINEsnmpV3viewTreeType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("included", 1), ("excluded", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeType.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeType.setDescription('Indicates whether the corresponding instances of vacmViewTreeFamilySubtree and vacmViewTreeFamilyMask define a family of view subtrees which is included in or excluded from the MIB view. ')NEWLINEsnmpV3viewTreeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 4, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3viewTreeStatus.setDescription('The status of this conceptual row. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ')NEWLINEsnmpV3CommunityTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1), )NEWLINEif mibBuilder.loadTexts: snmpV3CommunityTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityTable.setDescription('')NEWLINEsnmpV3CommunityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3CommunityName"))NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEntry.setDescription('')NEWLINEsnmpV3CommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityName.setDescription('The unique index value of a row in this table.')NEWLINEsnmpV3CommunityPolicy = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityPolicy.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityPolicy.setDescription('A human readable string representing the corresponding value of snmpCommunityName in a Security Model independent format.')NEWLINEsnmpV3CommunityStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 5, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityStatus.setDescription('The status of this conceptual row in the snmpCommunityTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The snmpCommunityName and snmpCommunitySecurityName objects must be explicitly set. There is no restriction on setting columns in this table when the value of snmpCommunityStatus is active(1).')NEWLINEipv4snmpV3HostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1), )NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostTable.setDescription('')NEWLINEipv4snmpV3HostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4snmpV3HostAddress"))NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostEntry.setDescription('')NEWLINEipv4snmpV3HostAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 1), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostAddress.setDescription('This object contains a transport address. The format of this address depends on the value of the snmpTargetAddrTDomain object. And this object is unique identifier associated with this snmpNotifyEntry.')NEWLINEipv4snmpV3HostCommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostCommunityName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostCommunityName.setDescription('The locally arbitrary.')NEWLINEipv4snmpV3HostVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3NoAuthNoPriv", 3), ("v3AuthNoPriv", 4), ("v3AuthPriv", 5)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostVersion.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostVersion.setDescription('The Level of Security to be used when generating SNMP messages using this entry.')NEWLINEipv4snmpV3HostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4snmpV3HostStatus.setDescription('')NEWLINEsnmpV3HostTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2), )NEWLINEif mibBuilder.loadTexts: snmpV3HostTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostTable.setDescription('')NEWLINEsnmpV3HostEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "snmpV3HostAddress"), (0, "DES-1210-28MEbx", "snmpV3IPType"))NEWLINEif mibBuilder.loadTexts: snmpV3HostEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostEntry.setDescription('')NEWLINEsnmpV3HostAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 1), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3HostAddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostAddress.setDescription('This object contains a transport address. The format of this address depends on the value of the snmpTargetAddrTDomain object. And this object is unique identifier associated with this snmpNotifyEntry.')NEWLINEsnmpV3IPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: snmpV3IPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3IPType.setDescription('Type of IP interface.')NEWLINEsnmpV3HostCommunityName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostCommunityName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostCommunityName.setDescription('The locally arbitrary.')NEWLINEsnmpV3HostVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("v1", 1), ("v2c", 2), ("v3NoAuthNoPriv", 3), ("v3AuthNoPriv", 4), ("v3AuthPriv", 5)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostVersion.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostVersion.setDescription('The Level of Security to be used when generating SNMP messages using this entry.')NEWLINEsnmpV3HostInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 5), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostInterfaceName.setDescription('Specifies the interface name when the syslogSrvIP is linklocal address.')NEWLINEsnmpV3HostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 6, 2, 1, 6), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: snmpV3HostStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3HostStatus.setDescription('')NEWLINEsnmpV3TrapSNMPAuthentication = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapSNMPAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapSNMPAuthentication.setDescription('This object is for enabling or disabling SNMP login fail event trap in the system.')NEWLINEsnmpV3TrapColdStart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapColdStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapColdStart.setDescription('This object is for enabling or disabling devie Bootup event trap in the system.')NEWLINEsnmpV3TrapWarmStart = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapWarmStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapWarmStart.setDescription('This object is for enabling or disabling devie Bootup event trap in the system.')NEWLINEsnmpV3TrapLinkUpDown = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapLinkUpDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapLinkUpDown.setDescription('This object is for enabling or disabling Copper link up / link down event trap in the system.')NEWLINEsnmpV3TrapRSTPStateChange = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapRSTPStateChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapRSTPStateChange.setDescription('This object is for enabling or disabling RSTP topology change event trap in the system.')NEWLINEsnmpV3TrapFirmUpgrade = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapFirmUpgrade.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapFirmUpgrade.setDescription('This object is for enabling or disabling Firmware upgrade suess or fail event trap in the system.')NEWLINEsnmpV3TrapBPDUAttack = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("attackDetected", 2), ("attackCleared", 3), ("both", 4))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapBPDUAttack.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapBPDUAttack.setDescription('Used to configure trap settings for BPDU attack protection events.')NEWLINEsnmpV3TrapPortSecurity = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapPortSecurity.setDescription('')NEWLINEsnmpV3TrapIMPBViolation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapIMPBViolation.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapIMPBViolation.setDescription('')NEWLINEsnmpV3TrapLBD = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapLBD.setDescription('')NEWLINEsnmpV3TrapDHCPServerScreening = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapDHCPServerScreening.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapDHCPServerScreening.setDescription('')NEWLINEsnmpV3TrapDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 8, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3TrapDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3TrapDuplicateIPDetected.setDescription('This object is for enabling or disabling send gratuitous trap when IP address conflicted in the network.')NEWLINEsnmpV3CommunityEncryption = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 5, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEncryption.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpV3CommunityEncryption.setDescription('This object is for enabling or disabling community encryption.')NEWLINEtraps = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0))NEWLINEsnmpTrapSNMPAuthentication = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 1))NEWLINEif mibBuilder.loadTexts: snmpTrapSNMPAuthentication.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapSNMPAuthentication.setDescription('SnmpV3TrapSNMPAuthentication.')NEWLINEsnmpTrapColdStart = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 2))NEWLINEif mibBuilder.loadTexts: snmpTrapColdStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapColdStart.setDescription('SnmpV3TrapColdStart.')NEWLINEsnmpTrapWarmStart = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 3))NEWLINEif mibBuilder.loadTexts: snmpTrapWarmStart.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapWarmStart.setDescription('SnmpV3TrapWarmStart.')NEWLINEsnmpTrapCopperLinkUpDown = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 4))NEWLINEif mibBuilder.loadTexts: snmpTrapCopperLinkUpDown.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapCopperLinkUpDown.setDescription('SnmpV3TrapCopperLinkUpDown.')NEWLINEsnmpTrapRSTPStateChange = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 5))NEWLINEif mibBuilder.loadTexts: snmpTrapRSTPStateChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapRSTPStateChange.setDescription('SnmpV3TrapRSTPStateChange.')NEWLINEsnmpTrapFirmUpgrade = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 6))NEWLINEif mibBuilder.loadTexts: snmpTrapFirmUpgrade.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapFirmUpgrade.setDescription('SnmpV3TrapFirmUpgrade.')NEWLINEsnmpTrapBPDUAttack = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 11))NEWLINEif mibBuilder.loadTexts: snmpTrapBPDUAttack.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapBPDUAttack.setDescription('SnmpV3TrapBPDUAttack.')NEWLINEsnmpTrapPortSecurity = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 12))NEWLINEif mibBuilder.loadTexts: snmpTrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapPortSecurity.setDescription('SnmpV3TrapPortSecurity.')NEWLINEsnmpTrapIMPBv2 = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 13))NEWLINEif mibBuilder.loadTexts: snmpTrapIMPBv2.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapIMPBv2.setDescription('SnmpV3TrapIMPBv2.')NEWLINEsnmpTrapLBD = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 14))NEWLINEif mibBuilder.loadTexts: snmpTrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapLBD.setDescription('SnmpV3TrapLBD.')NEWLINEsnmpTrapDHCPScreen = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 15))NEWLINEif mibBuilder.loadTexts: snmpTrapDHCPScreen.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapDHCPScreen.setDescription('SnmpV3TrapDHCPScreen.')NEWLINEsnmpTrapGratuitousArp = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 16))NEWLINEif mibBuilder.loadTexts: snmpTrapGratuitousArp.setStatus('current')NEWLINEif mibBuilder.loadTexts: snmpTrapGratuitousArp.setDescription('SnmpV3TrapGratuitousArp.')NEWLINEmacNotificatiotn = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 17))NEWLINEif mibBuilder.loadTexts: macNotificatiotn.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotificatiotn.setDescription(' This trap indicates the MAC address variations in the address table . ')NEWLINEduplicateIP = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 21))NEWLINEif mibBuilder.loadTexts: duplicateIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: duplicateIP.setDescription(' duplicateIP . ')NEWLINEtrafficControl = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 22))NEWLINEif mibBuilder.loadTexts: trafficControl.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficControl.setDescription(' trafficControl. ')NEWLINEtopologyChange = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 23))NEWLINEif mibBuilder.loadTexts: topologyChange.setStatus('current')NEWLINEif mibBuilder.loadTexts: topologyChange.setDescription(' topologyChange. ')NEWLINEnewRootBrgaddress = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 24))NEWLINEif mibBuilder.loadTexts: newRootBrgaddress.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootBrgaddress.setDescription(' newRootBrgaddress. ')NEWLINEnewRootOlddesignatedroot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 25))NEWLINEif mibBuilder.loadTexts: newRootOlddesignatedroot.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootOlddesignatedroot.setDescription(' newRootOlddesignatedroot. ')NEWLINEnewRootMSTibridgeregionalroot = NotificationType((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 120, 0, 26))NEWLINEif mibBuilder.loadTexts: newRootMSTibridgeregionalroot.setStatus('current')NEWLINEif mibBuilder.loadTexts: newRootMSTibridgeregionalroot.setDescription(' topologyChange. ')NEWLINEsyslogSettingGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1))NEWLINEsyslogEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogEnable.setDescription('This object is for enabling or disabling syslog alert features in the system and the syslog will save to flash or send to remote syslog server. System Logs record and manage events, as well as report errors and informational messages.')NEWLINEsyslogSaveMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("onDemand", 0), ("timeInterval", 1), ("logTrigger", 2))).clone('logTrigger')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogSaveMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogSaveMode.setDescription('This object is for choosing the method to save syslog into flash.')NEWLINEsyslogSaveMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(30)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogSaveMinutes.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogSaveMinutes.setDescription("When savemode is time interval, it's used to set the interval minutes of system save syslog to flash.")NEWLINEipv4syslogServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2))NEWLINEipv4syslogServTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1), )NEWLINEif mibBuilder.loadTexts: ipv4syslogServTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServTable.setDescription('The table of syslog remote server.')NEWLINEipv4syslogServEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4syslogServIndex"))NEWLINEif mibBuilder.loadTexts: ipv4syslogServEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServEntry.setDescription('The list of syslog remote server entry.')NEWLINEipv4syslogServIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4syslogServIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServIndex.setDescription('The index of syslog remote server.')NEWLINEipv4syslogServAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 2), IpAddress()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServAddr.setDescription('The IP Address of syslog remote server.')NEWLINEipv4syslogServSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 6, 7))).clone(namedValues=NamedValues(("warning", 4), ("information", 6), ("all", 7)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSeverity.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSeverity.setDescription('Specifies the log level option to be set for a specific server.')NEWLINEipv4syslogServFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(128, 136, 144, 152, 160, 168, 176, 184))).clone(namedValues=NamedValues(("local0", 128), ("local1", 136), ("local2", 144), ("local3", 152), ("local4", 160), ("local5", 168), ("local6", 176), ("local7", 184))).clone('local0')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServFacility.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServFacility.setDescription('The Syslog standard facilities. The facility to be used when sending Syslog messages to this server.')NEWLINEipv4syslogServUDPport = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(514, 514), ValueRangeConstraint(6000, 65535), ))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServUDPport.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServUDPport.setDescription('The value is for setting UDP Port.')NEWLINEipv4syslogServSrvStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvStatus.setDescription('The status for this server. If enable, system will send message to this server.')NEWLINEipv4syslogServSrvRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 2, 1, 1, 7), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4syslogServSrvRowStatus.setDescription('Row status of this server entry.')NEWLINEsyslogServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3))NEWLINEsyslogServTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1), )NEWLINEif mibBuilder.loadTexts: syslogServTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServTable.setDescription('The table of syslog remote server.')NEWLINEsyslogServEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "syslogServIndex"))NEWLINEif mibBuilder.loadTexts: syslogServEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServEntry.setDescription('The list of syslog remote server entry.')NEWLINEsyslogServIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: syslogServIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServIndex.setDescription('The index of syslog remote server.')NEWLINEsyslogServAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServAddrType.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServAddrType.setDescription('Specifies the Address type of server.Address type shall be ipv4 or ipv6.')NEWLINEsyslogServAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 3), Ipv6Address()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServAddr.setDescription('Specifies the ServerIP to which the syslog shall be forwarded.')NEWLINEsyslogServInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServInterfaceName.setDescription('Specifies the interface name when the syslogServInterfaceName is linklocal address.')NEWLINEsyslogServSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 6, 7))).clone(namedValues=NamedValues(("warning", 4), ("information", 6), ("all", 7)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServSeverity.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSeverity.setDescription('Specifies the log level option to be set for a specific server.')NEWLINEsyslogServFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(128, 136, 144, 152, 160, 168, 176, 184))).clone(namedValues=NamedValues(("local0", 128), ("local1", 136), ("local2", 144), ("local3", 152), ("local4", 160), ("local5", 168), ("local6", 176), ("local7", 184))).clone('local0')).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServFacility.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServFacility.setDescription('The Syslog standard facilities. The facility to be used when sending Syslog messages to this server.')NEWLINEsyslogServUDPport = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(514, 514), ValueRangeConstraint(6000, 65535), ))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: syslogServUDPport.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServUDPport.setDescription('The value is for setting UDP Port.')NEWLINEsyslogServSrvStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogServSrvStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSrvStatus.setDescription('The status for this server. If enable, system will send message to this server.')NEWLINEsyslogServSrvRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 16, 3, 1, 1, 9), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: syslogServSrvRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: syslogServSrvRowStatus.setDescription('Row status of this server entry.')NEWLINEsysLBDStateEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDStateEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDStateEnable.setDescription('Enable/Disable Loopback detection function. The Loopback Detection function is used to detect the loop created by a specific port while Spanning Tree Protocol (STP) is not enabled in the network, especially when the down links are hubs or unmanaged switchs.The Switch will automatically shutdown the port and sends a log to the administrator.')NEWLINEsysLBDMode = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("port", 1), ("vlan", 2))).clone('port')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDMode.setDescription('Loopback detection function mode.')NEWLINEsysLBDInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32767)).clone(2)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDInterval.setDescription('Set a Loop detection Interval between 1 and 32767 seconds. The default is 2 seconds. This time interval to be used at counting time seconds to resend the CTP packet automatically.')NEWLINEsysLBDRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDRecoverTime.setDescription('This time interval to be used at counting time seconds to recover the disabled port automatically. The Loop Detection Recover Time can be set at 0 seconds, or 60 to 1000000 seconds. Entering 0 will disable the Loop Detection Recover Time. The default is 60 seconds.')NEWLINEsysLBDCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5), )NEWLINEif mibBuilder.loadTexts: sysLBDCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlTable.setDescription('A table to control Loopback detection features either for the entire switch or for each interface in the switch.')NEWLINEsysLBDCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysLBDCtrlIndex"))NEWLINEif mibBuilder.loadTexts: sysLBDCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysLBDCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEsysLBDPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysLBDPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDPortStatus.setDescription('Provides control to per port enable or disable the loopback detection function. Default is disabled.')NEWLINEsysLBDPortLoopStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("loop", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDPortLoopStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDPortLoopStatus.setDescription('The loop status for this port.')NEWLINEsysLBDVlanLoopTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6), )NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopTable.setDescription('A table to display Loopback detection features by vlan mode .')NEWLINEsysLBDVlanLoopEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysLBDVlanLoopIndex"))NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysLBDVlanLoopIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopIndex.setDescription('Display port lists loop status by vlan.')NEWLINEsysLBDVlanLoopPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 17, 6, 1, 2), PortList()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopPorts.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysLBDVlanLoopPorts.setDescription('Display port lists loop status by vlan.')NEWLINEsysMirrorStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorStatus.setDescription('Enable/Disable Port Mirroring function. Default is disabled. Port Mirroring is a method of monitoring network traffic that forwards a copy of each incoming and/or outgoing packet from one port of the Switch to another port where the packet can be studied.')NEWLINEsysMirrorTargetPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 2), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorTargetPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorTargetPort.setDescription('Specifies the port to which the mirrored traffic in the system is to be copied.')NEWLINEsysMirrorCtrlIngressMirroring = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlIngressMirroring.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlIngressMirroring.setDescription('Provides control to enable or disable mirroring of ingress traffic over this interface to the mirrored-to port.')NEWLINEsysMirrorCtrlEgressMirroring = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 18, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlEgressMirroring.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysMirrorCtrlEgressMirroring.setDescription('Provides control to enable or disable mirroring of egress traffic over this interface to the mirrored-to port.')NEWLINEsysTrapIP = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 1), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapIP.setDescription("The smart console utility's IP address is used to recive trap events.")NEWLINEsysTrapSystemEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("deviceBootUp", 1), ("illegalLogin", 2), ("both", 3))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapSystemEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapSystemEvent.setDescription('Enable/Disable system trap events in the switch system.')NEWLINEsysTrapFiberPortEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapFiberPortEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapFiberPortEvent.setDescription('Enable/Disable fiber port trap event in the system.')NEWLINEsysTrapTwistedPortEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapTwistedPortEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapTwistedPortEvent.setDescription('Enable/Disable twisted port trap event in the system.')NEWLINEsysTrapStateChangeEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapStateChangeEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapStateChangeEvent.setDescription('Enable/Disable RSTP state change trap event in the system.')NEWLINEsysTrapFirmUpgradeEvent = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapFirmUpgradeEvent.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapFirmUpgradeEvent.setDescription('Enable/Disable firmware upgrading trap event in the system.')NEWLINEsysTrapStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapStatus.setDescription('Enable/Disable trap event in the system.')NEWLINEsysTrapPortSecurity = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapPortSecurity.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapPortSecurity.setDescription('')NEWLINEsysTrapIMPBViolation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapIMPBViolation.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapIMPBViolation.setDescription('')NEWLINEsysTrapLBD = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapLBD.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapLBD.setDescription('')NEWLINEsysTrapDHCPServerScreening = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapDHCPServerScreening.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapDHCPServerScreening.setDescription('')NEWLINEsysTrapDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 30, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysTrapDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysTrapDuplicateIPDetected.setDescription('This object is for enabling or disabling send gratuitous trap when IP address conflicted in the network.')NEWLINEipv4sysSNTPTimeSeconds = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 1), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPTimeSeconds.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPTimeSeconds.setDescription('This object is for setting the system time in seconds from Epoch (00:00:00 UTC, January 1, 2009). Notice : input value must larger than 1230768000 (00:00:00 UTC, January 1, 2009) and smaller than 2145916799 (23:59:59 UTC, December 31, 2037).')NEWLINEipv4sysSNTPFirstServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPFirstServer.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPFirstServer.setDescription("SNTP First Server's IP Address")NEWLINEipv4sysSNTPSecondServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 3), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPSecondServer.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPSecondServer.setDescription("SNTP Second Server's IP Address")NEWLINEipv4sysSNTPPollInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 4), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPPollInterval.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPPollInterval.setDescription('SNTP Poll Interval In Seconds (30-99999) ')NEWLINEipv4sysSNTPState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("sntp", 1), ("local", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPState.setDescription('Enable/Disable SNTP function in the system.')NEWLINEipv4sysSNTPDSTOffset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(30, 60, 90, 120))).clone(namedValues=NamedValues(("offset30min", 30), ("offset60min", 60), ("offset90min", 90), ("offset120min", 120)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTOffset.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTOffset.setDescription('This object is for Daylight Saving Time Offset In (30/60/90/120) Minutes.')NEWLINEipv4sysSNTPGMTMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 7), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPGMTMinutes.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPGMTMinutes.setDescription('Specifies the Time Zone Offset from GMT in +/- Minutes. (+780 ~ -720)')NEWLINEipv4sysSNTPDSTStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 8), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMon.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMon.setDescription('The start month of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 9), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartDay.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartDay.setDescription('The start day of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 10), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartHour.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartHour.setDescription('The start hour of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 11), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMin.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTStartMin.setDescription('The start minute of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMon.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMon.setDescription('The end month of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 13), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndDay.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndDay.setDescription('The end day of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 14), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndHour.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndHour.setDescription('The end hour of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMin.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTEndMin.setDescription('The end minute of Daylight Saving Time.')NEWLINEipv4sysSNTPDSTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("annual", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4sysSNTPDSTState.setDescription('This object is for Annual(1) or Disabled(2) DST state in the system.')NEWLINEsysSNTPServerTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17))NEWLINEsysSNTPTimeSeconds = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 1), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPTimeSeconds.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPTimeSeconds.setDescription('This object is for setting the system time in seconds from Epoch (00:00:00 UTC, January 1, 2009). Notice : input value must larger than 1230768000 (00:00:00 UTC, January 1, 2009) and smaller than 2145916799 (23:59:59 UTC, December 31, 2037).')NEWLINEsysSNTPFirstServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 2), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstServer.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstServer.setDescription("SNTP First Server's IPv6 Address")NEWLINEsysSNTPFirstType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstType.setDescription("SNTP First Server's IPv6 Address type.")NEWLINEsysSNTPFirstInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPFirstInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPFirstInterfaceName.setDescription('Specifies the interface name when the sysSNTPFirstServer is linklocal address.')NEWLINEsysSNTPSecondServer = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 5), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondServer.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondServer.setDescription("SNTP Second Server's IPv6 Address")NEWLINEsysSNTPSecondType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondType.setDescription("SNTP First Server's IPv6 Address type.")NEWLINEsysSNTPSecondInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 7), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPSecondInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPSecondInterfaceName.setDescription('Specifies the interface name when the sysSNTPSecondServer is linklocal address.')NEWLINEsysSNTPPollInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 8), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPPollInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPPollInterval.setDescription('SNTP Poll Interval In Seconds (30-99999) ')NEWLINEsysSNTPState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("sntp", 1), ("local", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPState.setDescription('Enable/Disable SNTP function in the system.')NEWLINEsysSNTPDSTOffset = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(30, 60, 90, 120))).clone(namedValues=NamedValues(("offset30min", 30), ("offset60min", 60), ("offset90min", 90), ("offset120min", 120)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTOffset.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTOffset.setDescription('This object is for Daylight Saving Time Offset In (30/60/90/120) Minutes.')NEWLINEsysSNTPGMTMinutes = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 11), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPGMTMinutes.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPGMTMinutes.setDescription('Specifies the Time Zone Offset from GMT in +/- Minutes. (+780 ~ -720)')NEWLINEsysSNTPDSTStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 12), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMon.setDescription('The start month of Daylight Saving Time.')NEWLINEsysSNTPDSTStartDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 13), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartDay.setDescription('The start day of Daylight Saving Time.')NEWLINEsysSNTPDSTStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 14), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartHour.setDescription('The start hour of Daylight Saving Time.')NEWLINEsysSNTPDSTStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 15), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTStartMin.setDescription('The start minute of Daylight Saving Time.')NEWLINEsysSNTPDSTEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 16), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMon.setDescription('The end month of Daylight Saving Time.')NEWLINEsysSNTPDSTEndDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 17), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndDay.setDescription('The end day of Daylight Saving Time.')NEWLINEsysSNTPDSTEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 18), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndHour.setDescription('The end hour of Daylight Saving Time.')NEWLINEsysSNTPDSTEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 19), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTEndMin.setDescription('The end minute of Daylight Saving Time.')NEWLINEsysSNTPDSTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTState.setDescription('This object is for Enabled(1) or Disabled(2) DST state in the system.')NEWLINEsysSNTPDSTMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("annual", 1), ("repeating", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTMethod.setDescription('This object is for Annual(1) or Repeating(2) DST method in the system.')NEWLINEsysSNTPDSTRepeatStartMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 31), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMon.setDescription('The start month of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartWeek = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("last", 0), ("first", 1), ("second", 2), ("third", 3), ("fourth", 4), ("fifth", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeek.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeek.setDescription('The start week of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartWeekDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sun", 0), ("mon", 1), ("tue", 2), ("wed", 3), ("thu", 4), ("fri", 5), ("sat", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeekDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartWeekDay.setDescription('The start weekday of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatStartHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 34), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartHour.setDescription('The start hour of Daylight Saving Time in Repeating mode..')NEWLINEsysSNTPDSTRepeatStartMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 35), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatStartMin.setDescription('The start minute of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndMon = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 36), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMon.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMon.setDescription('The end month of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndWeek = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("last", 0), ("first", 1), ("second", 2), ("third", 3), ("fourth", 4), ("fifth", 5)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeek.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeek.setDescription('The end week of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndWeekDay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 38), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("sun", 0), ("mon", 1), ("tue", 2), ("wed", 3), ("thu", 4), ("fri", 5), ("sat", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeekDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndWeekDay.setDescription('The end weekday of Daylight Saving Time in Repeating mode.')NEWLINEsysSNTPDSTRepeatEndHour = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 39), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndHour.setDescription('The end hour of Daylight Saving Time in Repeating mode..')NEWLINEsysSNTPDSTRepeatEndMin = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 20, 17, 40), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMin.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysSNTPDSTRepeatEndMin.setDescription('The end minute of Daylight Saving Time in Repeating mode.')NEWLINElimitIpMulticastProfileTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileTable.setDescription('A list of the limit ip multicast Profile Table.')NEWLINElimitIpMulticastProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastProfileID"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileEntry.setDescription('A limit ip multicast entry maintain by the start IP Address, end ip address, profile id.')NEWLINElimitIpMulticastIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastIPType.setDescription('Indicate the IP type of profile.')NEWLINElimitIpMulticastProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileID.setDescription('The ProfileID of the limit ip multicast profile entry.')NEWLINElimitIpMulticastProfileName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileName.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileName.setDescription('The ProfileName of the limit ip multicast profile entry.')NEWLINElimitIpMulticastProfileStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 1, 1, 4), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastProfileStatus.setDescription('The status of an entry in the limit ip multicast profile Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINElimitIpMulticastEntryTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryTable.setDescription('A list of the limit ip multicast entry Table.')NEWLINElimitIpMulticastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastEntryIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastEntryProfileID"), (0, "DES-1210-28MEbx", "limitIpMulticaststartIpAddr"), (0, "DES-1210-28MEbx", "limitIpMulticastendIpAddr"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntry.setDescription('A limit ip multicast entry maintain by the start IP Address, end ip address, profile id.')NEWLINElimitIpMulticastEntryIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryIPType.setDescription('Indicate the IP type of entry.')NEWLINElimitIpMulticastEntryProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastEntryProfileID.setDescription('The ProfileID of the limit ip multicast entry.')NEWLINElimitIpMulticaststartIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticaststartIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticaststartIpAddr.setDescription('The limit ip multicast IP address is used to set start ip')NEWLINElimitIpMulticastendIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastendIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastendIpAddr.setDescription('The limit ip multicast IP address is used to set end ip')NEWLINElimitIpMulticastStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 2, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastStatus.setDescription('The status of an entry in the limit ip multicast entry Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINElimitIpMulticastPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3), )NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortTable.setDescription('A list of the limit ip multicast Port entry Table.')NEWLINElimitIpMulticastPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "limitIpMulticastPortIPType"), (0, "DES-1210-28MEbx", "limitIpMulticastPortID"))NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortEntry.setDescription('A limit ip multicast entry maintain by the Port Index.')NEWLINElimitIpMulticastPortIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortIPType.setDescription('Indicate the IP type of entry.')NEWLINElimitIpMulticastPortID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortID.setDescription('The Port Index of the limit ip multicast port entry. For all machines give maximum port number.')NEWLINElimitIpMulticastPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("permit", 1), ("deny", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortState.setDescription('The limit ip multicast port state')NEWLINElimitIpMulticastPortProfileID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortProfileID.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortProfileID.setDescription('The limit ip multicast port mapping profileID list.')NEWLINElimitIpMulticastPortMaxGrp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 45, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 256))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortMaxGrp.setStatus('current')NEWLINEif mibBuilder.loadTexts: limitIpMulticastPortMaxGrp.setDescription('The limit ip multicast per-port max group.')NEWLINEguestVlanName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanName.setDescription('The VLAN name of guest VLAN.')NEWLINEguestVlanPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanPort.setDescription('This object indicates the guest VLAN port members of this device.')NEWLINEguestVlanDelState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 24, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("start", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: guestVlanDelState.setStatus('current')NEWLINEif mibBuilder.loadTexts: guestVlanDelState.setDescription('Used to delete the guest VLAN.')NEWLINEprotocolGroupNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1), )NEWLINEif mibBuilder.loadTexts: protocolGroupNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupNameTable.setDescription('A table to control protocol group name features of the device.')NEWLINEprotocolGroupNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolGroupGID"))NEWLINEif mibBuilder.loadTexts: protocolGroupNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupNameEntry.setDescription('An entry appears in protocol group name table for each interface in the system.')NEWLINEprotocolGroupGID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupGID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupGID.setDescription('The group ID of protocol group name table.')NEWLINEprotocolGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: protocolGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupName.setDescription('The group name of protocol group name table.')NEWLINEprotocolGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2), )NEWLINEif mibBuilder.loadTexts: protocolGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupTable.setDescription('A table to control protocol group features of the device.')NEWLINEprotocolGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolGroupId"), (0, "DES-1210-28MEbx", "protocolGroupFrameType"), (0, "DES-1210-28MEbx", "protocolGroupProtocolValue"))NEWLINEif mibBuilder.loadTexts: protocolGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupEntry.setDescription('An entry appears in protocol group table for each interface in the system.')NEWLINEprotocolGroupId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupId.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupId.setDescription('The group ID of protocol group table.')NEWLINEprotocolGroupFrameType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ethernet", 1), ("ieee8023-snap", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupFrameType.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupFrameType.setDescription('The frame type of protocol group table.')NEWLINEprotocolGroupProtocolValue = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolGroupProtocolValue.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupProtocolValue.setDescription('The protocol value of protocol group table.')NEWLINEprotocolGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 2, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: protocolGroupRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolGroupRowStatus.setDescription('The row status of protocol group table.')NEWLINEprotocolVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3), )NEWLINEif mibBuilder.loadTexts: protocolVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanTable.setDescription('A table to control protocol vlan features of the device.')NEWLINEprotocolVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "protocolVlanPort"), (0, "DES-1210-28MEbx", "protocolVlanVID"), (0, "DES-1210-28MEbx", "protocolVlanGroupID"))NEWLINEif mibBuilder.loadTexts: protocolVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanEntry.setDescription('An entry appears in protocol vlan table for each interface in the system.')NEWLINEprotocolVlanPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanPort.setDescription('The interface number of protocol vlan table.')NEWLINEprotocolVlanVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanVID.setDescription('The vlan ID of protocol vlan table.')NEWLINEprotocolVlanGroupID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: protocolVlanGroupID.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanGroupID.setDescription('The group ID of protocol vlan table.')NEWLINEprotocolVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 101, 3, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: protocolVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: protocolVlanRowStatus.setDescription('The row status of protocol vlan table.')NEWLINEmacNotifyState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyState.setDescription('This object can enabled or disabled MAC Notification.')NEWLINEmacNotifyInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyInterval.setDescription('This object indicates the time interval in second for trigger the MAC notify message. ')NEWLINEmacNotifyHistorySize = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 500))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyHistorySize.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyHistorySize.setDescription('This object indicates the history size of variation MAC in address table. The default value is 1 .')NEWLINEmacNotifyCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4), )NEWLINEif mibBuilder.loadTexts: macNotifyCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlTable.setDescription('A table to control Loopback detection features either for the entire switch or for each interface in the switch.')NEWLINEmacNotifyCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "macNotifyCtrlIndex"))NEWLINEif mibBuilder.loadTexts: macNotifyCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEmacNotifyCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: macNotifyCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEmacNotifyPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macNotifyPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyPortStatus.setDescription('Provides control to per port enable or disable the loopback detection function. Default is disabled.')NEWLINEmacNotifyInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 5))NEWLINEmacNotifyInfoDiscription = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 25, 5, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1024))).setMaxAccess("accessiblefornotify")NEWLINEif mibBuilder.loadTexts: macNotifyInfoDiscription.setStatus('current')NEWLINEif mibBuilder.loadTexts: macNotifyInfoDiscription.setDescription('This object indicates the information for the device MAC address changes. And the detailed information include: Operation Code + MAC address + Box ID + Port Number + Zero... Operation Code: 1, 2 and 3 1 means learned a new MAC address 2 means deleted an old MAC address. 3 means station movement. Box ID: The switch box ID, for standalone device, it always 1. Port Number: The port number learned or deleted for the box. Zero: Used to separate each message (Operate Code + MAC address + Box ID + Port Number).')NEWLINEsysBPDUAttackStateEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackStateEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackStateEnable.setDescription('Use this to enable BPDU attack protection. The BPDU Attack Protection function and Spanning Tree Protocol for ports are mutually exclusive. When the STP function is enabled on a particular port, BPDU Attack Protection cannot be enabled.')NEWLINEsysBPDUAttackRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackRecoverTime.setDescription('When a port enters under attack state, it can be disabled or blocked based on the configuration. The state can be recovered manually or by the auto recovery mechanism. This command is used to configure the auto-recovery timer. To manually recover the port, the user needs to disable and re-enable the port.')NEWLINEsysBPDUAttackCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3), )NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlTable.setDescription('A table to control BPDU Attack features either for the entire switch or for each interface in the switch.')NEWLINEsysBPDUAttackCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysBPDUAttackCtrlIndex"))NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEsysBPDUAttackCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackCtrlIndex.setDescription('The interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEsysBPDUAttackPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortState.setDescription('Used to configure the BPDU Attack Protection state of a port. The default state is disable.')NEWLINEsysBPDUAttackPortMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("drop", 1), ("block", 2), ("shutdown", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortMode.setDescription('Used to configure the BPDU Attack Protection mode of a port.')NEWLINEsysBPDUAttackPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("underAttack", 2))).clone('normal')).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackPortStatus.setDescription('Use this to view per port BPDU attack protection status.')NEWLINEsysBPDUAttackLog = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 77, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("attackDetected", 2), ("attackCleared", 3), ("both", 4))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysBPDUAttackLog.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysBPDUAttackLog.setDescription('Used to configure log settings for BPDU attack protection events.')NEWLINEvlanTrunkSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1))NEWLINEvlanTrunkGlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanTrunkGlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkGlobalStatus.setDescription('This indicates the global state of the VLAN trunking feature of the device.')NEWLINEvlanTrunkTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2), )NEWLINEif mibBuilder.loadTexts: vlanTrunkTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkTable.setDescription('This table is used to manage the VLAN trunking feature of the device.')NEWLINEvlanTrunkEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "vlanTrunkIfIndex"))NEWLINEif mibBuilder.loadTexts: vlanTrunkEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkEntry.setDescription('There is one entry in this table for each created port-channel port.')NEWLINEvlanTrunkIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanTrunkIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkIfIndex.setDescription('The index of the port. ')NEWLINEvlanTrunkState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 36, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanTrunkState.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanTrunkState.setDescription('Sets the VLAN trunk status as enabled or disabled.')NEWLINEqinqSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1))NEWLINEqinqVLANTranslation = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2))NEWLINEqinqGlobalStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqGlobalStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqGlobalStatus.setDescription('This object is used to enable/disable the Q-in-Q status.')NEWLINEqinqTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2), )NEWLINEif mibBuilder.loadTexts: qinqTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqTable.setDescription('A table that contains Q-in-Q VLAN mode information about each port.')NEWLINEqinqEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qinqIfIndex"))NEWLINEif mibBuilder.loadTexts: qinqEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqEntry.setDescription('A list of Q-in-Q VLAN mode information for each port.')NEWLINEqinqIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qinqIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqIfIndex.setDescription('The index of the port. ')NEWLINEqinqRoleState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("nni", 1), ("uni", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqRoleState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqRoleState.setDescription('Sets the QinQ Role as NNI or UNI.')NEWLINEqinqOuterTPID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 3), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqOuterTPID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqOuterTPID.setDescription('Sets the QinQ Outer TPID value.')NEWLINEqinqTrustCVIDState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqTrustCVIDState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqTrustCVIDState.setDescription('Sets the QinQ Trust CVID state as enabled or disabled.')NEWLINEqinqVLANTranslationState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: qinqVLANTranslationState.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVLANTranslationState.setDescription('Sets the QinQ VLANTranslation state as enabled or disabled.')NEWLINEqinqVlanTranslationCVIDTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1), )NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDTable.setDescription("A table that contains VLAN translation information applied in enabling port's swQinQPortVlanTranslation, swQinQPortTrustCVID and QinQ.")NEWLINEqinqVlanTranslationCVIDEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "qinqVlanTranslationCVID"))NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDEntry.setDescription("A list of VLAN translation information applied in enabling a port's swQinQPortVlanTranslation, swQinQPortTrustCVID and QinQ.")NEWLINEqinqVlanTranslationCVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 1), Unsigned32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVID.setDescription('The customer VLAN identifier in a C-TAG.')NEWLINEqinqVlanTranslationSVID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 2), Unsigned32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVID.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVID.setDescription('A VLAN identifier conveyed in an S-TAG.')NEWLINEqinqVlanTranslationSVIDOperation = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("add", 1), ("replace", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVIDOperation.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationSVIDOperation.setDescription("The 'add' action indicates to add a tag for the assigned SP-VLAN before the C-VLAN tag. If there is S-TAG in the packet, this rule will not take effect. The 'replace' action indicates to replace the C-VLAN in the tag by the SP-VLAN. If there is no C-TAG in the packet, this rule will not take effect.")NEWLINEqinqVlanTranslationCVIDRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 37, 2, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: qinqVlanTranslationCVIDRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEeoamSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1))NEWLINEeoamLinkMonitor = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2))NEWLINEeoamTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2), )NEWLINEif mibBuilder.loadTexts: eoamTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamTable.setDescription('A table that contains EOAM mode information about each port.')NEWLINEeoamEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "eoamIfIndex"))NEWLINEif mibBuilder.loadTexts: eoamEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamEntry.setDescription('A list of EOAM mode information for each port.')NEWLINEeoamIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: eoamIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamIfIndex.setDescription('The index of the port. ')NEWLINEeoamState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamState.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamState.setDescription('Sets the EOAM state enabled or disabled.')NEWLINEeoamMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("passive", 1), ("active", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamMode.setDescription('Sets the EOAM mode as active or passive.')NEWLINEeoamReceivedRemoteLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ignore", 1), ("process", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamReceivedRemoteLoopback.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamReceivedRemoteLoopback.setDescription('Sets the EOAM received or ignore remote loopback packets.')NEWLINEeoamRemoteLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("noLoopBack", 1), ("startLoopBack", 2), ("remoteLoopBack", 3), ("stopLoopBack", 4), ("localLoopBack", 5), ("unknownLoopBack", 6)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamRemoteLoopback.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamRemoteLoopback.setDescription('Sets the EOAM remote loopback start or stop.')NEWLINEeoamDyingGaspEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamDyingGaspEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamDyingGaspEnable.setDescription('Sets the EOAM dying gasp state enabled or disabled.')NEWLINEeoamCriticalEventEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: eoamCriticalEventEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamCriticalEventEnable.setDescription('Sets the EOAM critical event state enabled or disabled.')NEWLINEeoamLinkMonitorTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1), )NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorTable.setDescription('A table that contains EOAM link monitor information about each port.')NEWLINEeoamLinkMonitorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "eoamLinkMonitorIfIndex"))NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorEntry.setDescription('A list of EOAM link monitor information for each port.')NEWLINEeoamLinkMonitorIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: eoamLinkMonitorIfIndex.setDescription('The index of the port. ')NEWLINEerrorSymbolNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorSymbolThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 3), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorSymbolWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 4), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorSymbolWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorSymbolWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFrameNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameNotifyState.setDescription('Sets the EOAM error frame notify state enabled or disabled.')NEWLINEerrorFrameThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 6), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameThreshold.setDescription('Sets the EOAM error frame threshold.')NEWLINEerrorFrameWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 7), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFrameSecondsNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorFrameSecondsThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 9), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorFrameSecondsWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 10), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFrameSecondsWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFrameSecondsWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEerrorFramePeriodNotifyState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodNotifyState.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodNotifyState.setDescription('Sets the EOAM error symbol notify state enabled or disabled.')NEWLINEerrorFramePeriodThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 12), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodThreshold.setDescription('Sets the EOAM error symbol threshold.')NEWLINEerrorFramePeriodWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 51, 2, 1, 1, 13), Unsigned32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: errorFramePeriodWindow.setStatus('current')NEWLINEif mibBuilder.loadTexts: errorFramePeriodWindow.setDescription('Sets the EOAM error symbol window.')NEWLINEduldSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1))NEWLINEduldTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1), )NEWLINEif mibBuilder.loadTexts: duldTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldTable.setDescription('A table that contains DULD mode information about each port.')NEWLINEduldEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "duldIfIndex"))NEWLINEif mibBuilder.loadTexts: duldEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldEntry.setDescription('A list of DULD mode information for each port.')NEWLINEduldIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldIfIndex.setDescription('The index of the port. ')NEWLINEduldState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldState.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldState.setDescription('Sets the DULD admin state enabled or disabled.')NEWLINEduldOperState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldOperState.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldOperState.setDescription('Gets the DULD Oper state enabled or disabled.')NEWLINEduldMode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("shutdown", 1), ("normal", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldMode.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldMode.setDescription('Sets the DULD mode as shutdown or normal.')NEWLINEduldLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("unknow", 1), ("bidirectional", 2), ("txFault", 3), ("rxFault", 4), ("linkDown", 5)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: duldLinkStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldLinkStatus.setDescription('Gets the DULD link status.')NEWLINEduldDiscoveryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 1, 1, 6), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(5, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldDiscoveryTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldDiscoveryTime.setDescription('Sets the DULD discovery time.')NEWLINEduldRecoverTime = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 52, 1, 2), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(60, 1000000), )).clone(60)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: duldRecoverTime.setStatus('current')NEWLINEif mibBuilder.loadTexts: duldRecoverTime.setDescription('Duld auto recover time.')NEWLINEdoSCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1), )NEWLINEif mibBuilder.loadTexts: doSCtrlTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlTable.setDescription('A table that holds the DoS prevention settings of the device.')NEWLINEdoSCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "doSCtrlType"))NEWLINEif mibBuilder.loadTexts: doSCtrlEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlEntry.setDescription('A list of DoS prevention settings of the device.')NEWLINEdoSCtrlType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("land-attack", 1), ("blat-attack", 2), ("smurf-attack", 3), ("tcp-null-scan", 4), ("tcp-xmascan", 5), ("tcp-synfin", 6), ("tcp-syn-srcport-less-1024", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: doSCtrlType.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlType.setDescription('This object indicates the DoS prevention type.')NEWLINEdoSCtrlState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlState.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlState.setDescription('This object indicates the status of the DoS prevention type.')NEWLINEdoSCtrlActionType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("drop", 0), ("mirror", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlActionType.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlActionType.setDescription("This object indicates the action for the DoS prevention type. If this object is set to 'mirror' and DoSCtrlState is set to 'enable', the configuration will not take effect until a valid mirror port is specified. If mirror port is not valid the behavior will be the same as 'drop'")NEWLINEdoSCtrlMirrorPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorPort.setDescription("This object indicates the port to which the attack packet will be forwarded. A value of 0 means that the DoS prevention action type is either not set to 'mirror'. or the 'mirror' DoS action is not active. When DoSCtrlActionType is set to 'mirror' with DoSCtrlState set to 'enable', setting this value to a valid port number will activate the 'mirror' DoS action.")NEWLINEdoSCtrlMirrorReplace1P = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorReplace1P.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorReplace1P.setDescription('This object indicates the packet to which the attack packet will be replaced 1p to mirror port. The Range of 1p is 0 ~ 7. If value set to -1, it means no chenged.')NEWLINEdoSCtrlMirrorRxRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1024000))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorRxRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlMirrorRxRate.setDescription('This object indicates the packet to which the attack packet will be rate limited to mirror port. The Range of rx limit is 0 or 64~1024000. If rate set to 0, it means no limit.')NEWLINEdoSCtrlFrameCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 7), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: doSCtrlFrameCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlFrameCount.setDescription('This object indicates the frame counts of the DoS prevention type.')NEWLINEdoSCtrlClearFrameCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("normal", 0), ("clear", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: doSCtrlClearFrameCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: doSCtrlClearFrameCount.setDescription('This object will clear frame count when set to clear.')NEWLINEdosCtrlTrapLogState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 99, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dosCtrlTrapLogState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dosCtrlTrapLogState.setDescription('Enable/Disable Dos Trap Log function. Default is disabled.')NEWLINEswTimeRangeSettingTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1), )NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingTable.setDescription('A table to configure time Range in the system.')NEWLINEswTimeRangeSettingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "swTimeRangeIndex"))NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSettingEntry.setDescription('A schedule entry to configure time Range in the system.')NEWLINEswTimeRangeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 52))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: swTimeRangeIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeIndex.setDescription('The Time Range identifier. The maximum number of Schedule entry is the number of ports supported PoE function. The value must be between 1 and 52.')NEWLINEswTimeRangeName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeName.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeName.setDescription("The Schedule name associated with the Schedule entry (e.g., `abc, bbb').")NEWLINEswTimeRangeDate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeDate.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeDate.setDescription('Enable/Disable date range checking while executing time base PoE.')NEWLINEswTimeRangeStartYear = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037))).clone(namedValues=NamedValues(("y2009", 2009), ("y2010", 2010), ("y2011", 2011), ("y2012", 2012), ("y2013", 2013), ("y2014", 2014), ("y2015", 2015), ("y2016", 2016), ("y2017", 2017), ("y2018", 2018), ("y2019", 2019), ("y2020", 2020), ("y2021", 2021), ("y2022", 2022), ("y2023", 2023), ("y2024", 2024), ("y2025", 2025), ("y2026", 2026), ("y2027", 2027), ("y2028", 2028), ("y2029", 2029), ("y2030", 2030), ("y2031", 2031), ("y2032", 2032), ("y2033", 2033), ("y2034", 2034), ("y2035", 2035), ("y2036", 2036), ("y2037", 2037)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartYear.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartYear.setDescription('Start year of the Schedule entry.')NEWLINEswTimeRangeStartMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("january", 1), ("february", 2), ("march", 3), ("april", 4), ("may", 5), ("june", 6), ("july", 7), ("august", 8), ("september", 9), ("october", 10), ("november", 11), ("december", 12)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMonth.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMonth.setDescription('Start month of the Schedule entry.')NEWLINEswTimeRangeStartDay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartDay.setDescription('Start day of the Schedule entry. The value must be from 1 to 31.')NEWLINEswTimeRangeStartHour = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 23))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartHour.setDescription('Start hour of the Schedule entry. The value must be from 0 to 23.')NEWLINEswTimeRangeStartMinute = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 59))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMinute.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeStartMinute.setDescription('Start minute of the Schedule entry. The value must be from 0 to 59.')NEWLINEswTimeRangeEndYear = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037))).clone(namedValues=NamedValues(("y2009", 2009), ("y2010", 2010), ("y2011", 2011), ("y2012", 2012), ("y2013", 2013), ("y2014", 2014), ("y2015", 2015), ("y2016", 2016), ("y2017", 2017), ("y2018", 2018), ("y2019", 2019), ("y2020", 2020), ("y2021", 2021), ("y2022", 2022), ("y2023", 2023), ("y2024", 2024), ("y2025", 2025), ("y2026", 2026), ("y2027", 2027), ("y2028", 2028), ("y2029", 2029), ("y2030", 2030), ("y2031", 2031), ("y2032", 2032), ("y2033", 2033), ("y2034", 2034), ("y2035", 2035), ("y2036", 2036), ("y2037", 2037)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndYear.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndYear.setDescription('End year of the Schedule entry.')NEWLINEswTimeRangeEndMonth = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("january", 1), ("february", 2), ("march", 3), ("april", 4), ("may", 5), ("june", 6), ("july", 7), ("august", 8), ("september", 9), ("october", 10), ("november", 11), ("december", 12)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMonth.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMonth.setDescription('End month of the Schedule entry.')NEWLINEswTimeRangeEndDay = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndDay.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndDay.setDescription('End day of the Schedule entry. The value must be from 1 to 31.')NEWLINEswTimeRangeEndHour = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 23))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndHour.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndHour.setDescription('End hour of the Schedule entry. The value must be from 0 to 23.')NEWLINEswTimeRangeEndMinute = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 59))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMinute.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeEndMinute.setDescription('End minute of the Schedule entry. The value must be from 0 to 59.')NEWLINEswTimeRangeMonday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeMonday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeMonday.setDescription('Enable/Disble scheduling Monday.')NEWLINEswTimeRangeTuesday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeTuesday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeTuesday.setDescription('Enable/Disble scheduling Tuesday.')NEWLINEswTimeRangeWednesday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeWednesday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeWednesday.setDescription('Enable/Disble scheduling Wednesday.')NEWLINEswTimeRangeThursday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeThursday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeThursday.setDescription('Enable/Disble scheduling Thursday.')NEWLINEswTimeRangeFriday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeFriday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeFriday.setDescription('Enable/Disble scheduling Friday.')NEWLINEswTimeRangeSaturday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeSaturday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSaturday.setDescription('Enable/Disble scheduling Saturday.')NEWLINEswTimeRangeSunday = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: swTimeRangeSunday.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeSunday.setDescription('Enable/Disble scheduling Sunday.')NEWLINEswTimeRangeRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 38, 1, 1, 21), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: swTimeRangeRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: swTimeRangeRowStatus.setDescription('The status of an entry in the Time Range Information Table. Only a subset of the rowstatus variables (active, notinservice, createAndWait, destroy) are available.')NEWLINEdlinklldpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpState.setDescription('This object is used for enabling or disabling LLDP in the system.')NEWLINEdlinklldpMsgHoldMultiplier = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpMsgHoldMultiplier.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpMsgHoldMultiplier.setDescription('The time-to-live value expressed as a multiple of the lldpMessageTxInterval object.The actual time-to-live value used in LLDP frames, transmitted on behalf of this LLDP agent, can be expressed by the following formula: TTL = min(65535, (lldpMessageTxInterval * lldpMessageTxHoldMultiplier))')NEWLINEdlinklldpMsgTxInterval = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 32768))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpMsgTxInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpMsgTxInterval.setDescription('This object is used for LLDP packet update frequency. The timer in units of seconds.')NEWLINEdlinklldpReinitDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpReinitDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpReinitDelay.setDescription('This object is used for LLDP Reinitialization Delay. The timer in units of seconds.')NEWLINEdlinklldpTxDelay = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8192))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpTxDelay.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpTxDelay.setDescription('The lldpTxDelay indicates the delay (in units of seconds) between successive LLDP frame transmissions initiated by value/status changes in the LLDP local systems MIB. The recommended value for the lldpTxDelay is set by the following formula: 1 <= lldpTxDelay <= (0.25 * lldpMessageTxInterval).')NEWLINEdlinklldpConfigManAddrPortsTxEnable = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dlinklldpConfigManAddrPortsTxEnable.setDescription('A set of ports that are identified by a PortList, in which each port is represented as a bit. The corresponding local system management address instance will be transmitted on the member ports of the lldpManAddrPortsTxEnable. The default value for lldpConfigManAddrPortsTxEnable object is empty binary string, which means no ports are specified for advertising indicated management address instance.')NEWLINEclass LldpPortNumber(TextualConvention, Integer32):NEWLINE description = "Each port contained in the chassis (that is known to the LLDP agent) is uniquely identified by a port number. A port number has no mandatory relationship to an InterfaceIndex object (of the interfaces MIB, IETF RFC 2863). If the LLDP agent is a IEEE 802.1D, IEEE 802.1Q bridge, the LldpPortNumber will have the same value as the dot1dBasePort object (defined in IETF RFC 1493) associated corresponding bridge port. If the system hosting LLDP agent is not an IEEE 802.1D or an IEEE 802.1Q bridge, the LldpPortNumber will have the same value as the corresponding interface's InterfaceIndex object. Port numbers should be in the range of 1 and 4096 since a particular port is also represented by the corresponding port number bit in LldpPortList."NEWLINE status = 'current'NEWLINE displayHint = 'd'NEWLINE subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 4096)NEWLINENEWLINElldpPortConfigTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11), )NEWLINEif mibBuilder.loadTexts: lldpPortConfigTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTable.setDescription('The table that controls LLDP frame transmission on individual ports.')NEWLINElldpPortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpPortConfigPortNum"))NEWLINEif mibBuilder.loadTexts: lldpPortConfigEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigEntry.setDescription('LLDP configuration information for a particular port. This configuration parameter controls the transmission and the reception of LLDP frames on those ports whose rows are created in this table.')NEWLINElldpPortConfigPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 1), LldpPortNumber())NEWLINEif mibBuilder.loadTexts: lldpPortConfigPortNum.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigPortNum.setDescription('The index value used to identify the port component (contained in the local chassis with the LLDP agent) associated with this entry. The value of this object is used as a port index to the lldpPortConfigTable.')NEWLINElldpPortConfigAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("txOnly", 1), ("rxOnly", 2), ("txAndRx", 3), ("disabled", 4))).clone('txAndRx')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setReference('IEEE 802.1AB-2005 10.5.1')NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigAdminStatus.setDescription("The administratively desired status of the local LLDP agent. If the associated lldpPortConfigAdminStatus object has a value of 'txOnly(1)', then LLDP agent will transmit LLDP frames on this port and it will not store any information about the remote systems connected. If the associated lldpPortConfigAdminStatus object has a value of 'rxOnly(2)', then the LLDP agent will receive, but it will not transmit LLDP frames on this port. If the associated lldpPortConfigAdminStatus object has a value of 'txAndRx(3)', then the LLDP agent will transmit and receive LLDP frames on this port. If the associated lldpPortConfigAdminStatus object has a value of 'disabled(4)', then LLDP agent will not transmit or receive LLDP frames on this port. If there is remote systems information which is received on this port and stored in other tables, before the port's lldpPortConfigAdminStatus becomes disabled, then the information will naturally age out.")NEWLINElldpPortConfigNotificationEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigNotificationEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigNotificationEnable.setDescription('The lldpPortConfigNotificationEnable controls, on a per port basis, whether or not notifications from the agent are enabled. The value true(1) means that notifications are enabled; the value false(2) means that they are not.')NEWLINElldpPortConfigTLVsTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 11, 1, 4), Bits().clone(namedValues=NamedValues(("portDesc", 0), ("sysName", 1), ("sysDesc", 2), ("sysCap", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpPortConfigTLVsTxEnable.setDescription("The lldpPortConfigTLVsTxEnable, defined as a bitmap, includes the basic set of LLDP TLVs whose transmission is allowed on the local LLDP agent by the network management. Each bit in the bitmap corresponds to a TLV type associated with a specific optional TLV. It should be noted that the organizationally-specific TLVs are excluded from the lldpTLVsTxEnable bitmap. LLDP Organization Specific Information Extension MIBs should have similar configuration object to control transmission of their organizationally defined TLVs. The bit 'portDesc(0)' indicates that LLDP agent should transmit 'Port Description TLV'. The bit 'sysName(1)' indicates that LLDP agent should transmit 'System Name TLV'. The bit 'sysDesc(2)' indicates that LLDP agent should transmit 'System Description TLV'. The bit 'sysCap(3)' indicates that LLDP agent should transmit 'System Capabilities TLV'. There is no bit reserved for the management address TLV type since transmission of management address TLVs are controlled by another object, lldpConfigManAddrTable. The default value for lldpPortConfigTLVsTxEnable object is empty set, which means no enumerated values are set. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.")NEWLINElldpXdot3Objects = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12))NEWLINElldpXdot3Config = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1))NEWLINElldpXdot3LocalData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2))NEWLINElldpXdot3RemoteData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3))NEWLINEclass LldpPowerPortClass(TextualConvention, Integer32):NEWLINE description = 'This TC describes the Power over Ethernet (PoE) port class.'NEWLINE status = 'current'NEWLINE subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))NEWLINE namedValues = NamedValues(("pClassPSE", 1), ("pClassPD", 2))NEWLINENEWLINEclass LldpLinkAggStatusMap(TextualConvention, Bits):NEWLINE description = "This TC describes the link aggregation status. The bit 'aggCapable(0)' indicates the link is capable of being aggregated. The bit 'aggEnabled(1)' indicates the link is currently in aggregation."NEWLINE status = 'current'NEWLINE namedValues = NamedValues(("aggCapable", 0), ("aggEnabled", 1))NEWLINENEWLINElldpXdot3PortConfigTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTable.setDescription('A table that controls selection of LLDP TLVs to be transmitted on individual ports.')NEWLINElldpXdot3PortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1, 1), )NEWLINElldpPortConfigEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot3PortConfigEntry"))NEWLINElldpXdot3PortConfigEntry.setIndexNames(*lldpPortConfigEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigEntry.setDescription('LLDP configuration information that controls the transmission of IEEE 802.3 organizationally defined TLVs on LLDP transmission capable ports. This configuration object augments the lldpPortConfigEntry of the LLDP-MIB, therefore it is only present along with the port configuration defined by the associated lldpPortConfigEntry entry. Each active lldpXdot3PortConfigEntry must be from non-volatile storage (along with the corresponding lldpPortConfigEntry) after a re-initialization of the management system.')NEWLINElldpXdot3PortConfigTLVsTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 1, 1, 1, 1), Bits().clone(namedValues=NamedValues(("macPhyConfigStatus", 0), ("powerViaMDI", 1), ("linkAggregation", 2), ("maxFrameSize", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3PortConfigTLVsTxEnable.setDescription("The lldpXdot3PortConfigTLVsTxEnable, defined as a bitmap, includes the IEEE 802.3 organizationally defined set of LLDP TLVs whose transmission is allowed on the local LLDP agent by the network management. Each bit in the bitmap corresponds to an IEEE 802.3 subtype associated with a specific IEEE 802.3 optional TLV. The bit 0 is not used since there is no corresponding subtype. The bit 'macPhyConfigStatus(0)' indicates that LLDP agent should transmit 'MAC/PHY configuration/status TLV'. The bit 'powerViaMDI(1)' indicates that LLDP agent should transmit 'Power via MDI TLV'. The bit 'linkAggregation(2)' indicates that LLDP agent should transmit 'Link Aggregation TLV'. The bit 'maxFrameSize(3)' indicates that LLDP agent should transmit 'Maximum-frame-size TLV'. The default value for lldpXdot3PortConfigTLVsTxEnable object is an empty set, which means no enumerated values are set. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.")NEWLINElldpXdot3LocPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortTable.setDescription('This table contains one row per port of Ethernet port information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocPortAutoNegSupported"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot3LocPortAutoNegSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 1), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegSupported.setDescription('The truth value used to indicate whether the given port (associated with the local system) supports Auto-negotiation.')NEWLINElldpXdot3LocPortAutoNegEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegEnabled.setDescription('The truth value used to indicate whether port Auto-negotiation is enabled on the given port associated with the local system.')NEWLINElldpXdot3LocPortAutoNegAdvertisedCap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setReference('IEEE 802.1AB-2005 G.2.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortAutoNegAdvertisedCap.setDescription('This object contains the value (bitmap) of the ifMauAutoNegCapAdvertisedBits object (defined in IETF RFC 3636) which is associated with the given port on the local system.')NEWLINElldpXdot3LocPortOperMauType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setReference('IEEE 802.1AB-2005 G.2.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPortOperMauType.setDescription('An integer value that indicates the operational MAU type of the given port on the local system. This object contains the integer value derived from the list position of the corresponding dot3MauType as listed in IETF RFC 3636 (or subsequent revisions) and is equal to the last number in the respective dot3MauType OID. For example, if the ifMauType object is dot3MauType1000BaseTHD which corresponds to {dot3MauType 29}, the numerical value of this field will be 29. For MAU types not listed in RFC 3636 (or subsequent revisions), the value of this field shall be set to zero.')NEWLINElldpXdot3LocPowerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerTable.setDescription('This table contains one row per port of power ethernet information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocPowerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocPowerPortClass"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot3LocPowerPortClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 1), LldpPowerPortClass()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPortClass.setDescription('The value that identifies the port Class of the given port associated with the local system.')NEWLINElldpXdot3LocPowerMDISupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDISupported.setDescription('The truth value used to indicate whether the MDI power is supported on the given port associated with the local system.')NEWLINElldpXdot3LocPowerMDIEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerMDIEnabled.setDescription('The truth value used to identify whether MDI power is enabled on the given port associated with the local system.')NEWLINElldpXdot3LocPowerPairControlable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 4), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairControlable.setDescription('The truth value is derived from the value of pethPsePortPowerPairsControlAbility object (defined in IETF RFC 3621) and is used to indicate whether the pair selection can be controlled on the given port associated with the local system.')NEWLINElldpXdot3LocPowerPairs = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setReference('IEEE 802.1AB-2005 G.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerPairs.setDescription('This object contains the value of the pethPsePortPowerPairs object (defined in IETF RFC 3621) which is associated with the given port on the local system.')NEWLINElldpXdot3LocPowerClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ValueRangeConstraint(3, 3), ValueRangeConstraint(4, 4), ValueRangeConstraint(5, 5), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setReference('IEEE 802.1AB-2005 G.3.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocPowerClass.setDescription('This object contains the value of the pethPsePortPowerClassifications object (defined in IETF RFC 3621) which is associated with the given port on the local system.')NEWLINElldpXdot3LocLinkAggTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggTable.setDescription('This table contains one row per port of link aggregation information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocLinkAggEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocLinkAggStatus"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggEntry.setDescription('Link Aggregation information about a particular port component.')NEWLINElldpXdot3LocLinkAggStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1, 1), LldpLinkAggStatusMap()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setReference('IEEE 802.1AB-2005 G.4.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggStatus.setDescription('The bitmap value contains the link aggregation capabilities and the current aggregation status of the link.')NEWLINElldpXdot3LocLinkAggPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 2147483647), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setReference('IEEE 802.1AB-2005 G.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocLinkAggPortId.setDescription('This object contains the IEEE 802.3 aggregated port identifier, aAggPortID (IEEE 802.3-2002, 30.7.2.1.1), derived from the ifNumber of the ifIndex for the port component in link aggregation. If the port is not in link aggregation state and/or it does not support link aggregation, this value should be set to zero.')NEWLINElldpXdot3LocMaxFrameSizeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeTable.setDescription('This table contains one row per port of maximum frame size information (as a part of the LLDP 802.3 organizational extension) on the local system known to this agent.')NEWLINElldpXdot3LocMaxFrameSizeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3LocMaxFrameSize"))NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSizeEntry.setDescription('Maximum Frame Size information about a particular port component.')NEWLINElldpXdot3LocMaxFrameSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setReference('IEEE 802.1AB-2005 G.5.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3LocMaxFrameSize.setDescription('An integer value indicating the maximum supported frame size in octets on the given port of the local system.')NEWLINElldpXdot3RemPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortTable.setDescription('This table contains Ethernet port information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemPortAutoNegSupported"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortEntry.setDescription('Information about a particular physical network connection.')NEWLINElldpXdot3RemPortAutoNegSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 1), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegSupported.setDescription('The truth value used to indicate whether the given port (associated with remote system) supports Auto-negotiation.')NEWLINElldpXdot3RemPortAutoNegEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setReference('IEEE 802.1AB-2005 G.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegEnabled.setDescription('The truth value used to indicate whether port Auto-negotiation is enabled on the given port associated with the remote system.')NEWLINElldpXdot3RemPortAutoNegAdvertisedCap = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setReference('IEEE 802.1AB-2005 G.2.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortAutoNegAdvertisedCap.setDescription('This object contains the value (bitmap) of the ifMauAutoNegCapAdvertisedBits object (defined in IETF RFC 3636) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemPortOperMauType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setReference('IEEE 802.1AB-2005 G.2.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPortOperMauType.setDescription('An integer value that indicates the operational MAU type of the sending device. This object contains the integer value derived from the list position of the corresponding dot3MauType as listed in in IETF RFC 3636 (or subsequent revisions) and is equal to the last number in the respective dot3MauType OID. For example, if the ifMauType object is dot3MauType1000BaseTHD which corresponds to {dot3MauType 29}, the numerical value of this field will be 29. For MAU types not listed in RFC 3636 (or subsequent revisions), the value of this field shall be set to zero.')NEWLINElldpXdot3RemPowerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerTable.setDescription('This table contains Ethernet power information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemPowerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemPowerPortClass"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerEntry.setDescription('Information about a particular physical network connection.')NEWLINElldpXdot3RemPowerPortClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 1), LldpPowerPortClass()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPortClass.setDescription('The value that identifies the port Class of the given port associated with the remote system.')NEWLINElldpXdot3RemPowerMDISupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDISupported.setDescription('The truth value used to indicate whether the MDI power is supported on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerMDIEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerMDIEnabled.setDescription('The truth value used to identify whether MDI power is enabled on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerPairControlable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 4), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setReference('IEEE 802.1AB-2005 G.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairControlable.setDescription('The truth value is derived from the value of pethPsePortPowerPairsControlAbility object (defined in IETF RFC 3621) and is used to indicate whether the pair selection can be controlled on the given port associated with the remote system.')NEWLINElldpXdot3RemPowerPairs = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setReference('IEEE 802.1AB-2005 G.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerPairs.setDescription('This object contains the value of the pethPsePortPowerPairs object (defined in IETF RFC 3621) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemPowerClass = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1, 1), ValueRangeConstraint(2, 2), ValueRangeConstraint(3, 3), ValueRangeConstraint(4, 4), ValueRangeConstraint(5, 5), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setReference('IEEE 802.1AB-2005 G.3.3')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemPowerClass.setDescription('This object contains the value of the pethPsePortPowerClassifications object (defined in IETF RFC 3621) which is associated with the given port on the remote system.')NEWLINElldpXdot3RemLinkAggTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggTable.setDescription('This table contains port link aggregation information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemLinkAggEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemLinkAggStatus"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggEntry.setDescription("Link Aggregation information about remote system's port component.")NEWLINElldpXdot3RemLinkAggStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1, 1), LldpLinkAggStatusMap()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setReference('IEEE 802.1AB-2005 G.4.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggStatus.setDescription('The bitmap value contains the link aggregation capabilities and the current aggregation status of the link.')NEWLINElldpXdot3RemLinkAggPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 2147483647), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setReference('IEEE 802.1AB-2005 G.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemLinkAggPortId.setDescription('This object contains the IEEE 802.3 aggregated port identifier, aAggPortID (IEEE 802.3-2002, 30.7.2.1.1), derived from the ifNumber of the ifIndex for the port component associated with the remote system. If the remote port is not in link aggregation state and/or it does not support link aggregation, this value should be zero.')NEWLINElldpXdot3RemMaxFrameSizeTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeTable.setDescription('This table contains one row per port of maximum frame size information (as a part of the LLDP 802.3 organizational extension) of the remote system.')NEWLINElldpXdot3RemMaxFrameSizeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot3RemMaxFrameSize"))NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSizeEntry.setDescription('Maximum Frame Size information about a particular port component.')NEWLINElldpXdot3RemMaxFrameSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 12, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setReference('IEEE 802.1AB-2005 G.5.1')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot3RemMaxFrameSize.setDescription('An integer value indicating the maximum supported frame size in octets on the port component associated with the remote system.')NEWLINElldpXdot1Objects = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13))NEWLINElldpXdot1Config = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1))NEWLINElldpXdot1LocalData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2))NEWLINElldpXdot1RemoteData = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3))NEWLINElldpXdot1ConfigPortVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTable.setDescription('A table that controls selection of LLDP Port VLAN-ID TLVs to be transmitted on individual ports.')NEWLINElldpXdot1ConfigPortVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1, 1), )NEWLINElldpPortConfigEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigPortVlanEntry"))NEWLINElldpXdot1ConfigPortVlanEntry.setIndexNames(*lldpPortConfigEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanEntry.setDescription('LLDP configuration information that controls the transmission of IEEE 802.1 organizationally defined Port VLAN-ID TLV on LLDP transmission capable ports. This configuration object augments the lldpPortConfigEntry of the LLDP-MIB, therefore it is only present along with the port configuration defined by the associated lldpPortConfigEntry entry. Each active lldpConfigEntry must be restored from non-volatile storage (along with the corresponding lldpPortConfigEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigPortVlanTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 1, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigPortVlanTxEnable.setDescription('The lldpXdot1ConfigPortVlanTxEnable, which is defined as a truth value and configured by the network management, determines whether the IEEE 802.1 organizationally defined port VLAN TLV transmission is allowed on a given LLDP transmission capable port. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameTable.setDescription('This table contains one or more rows per IEEE 802.1Q VLAN name information on the local system known to this agent.')NEWLINElldpXdot1LocVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanNameEntry.setDescription('VLAN name Information about a particular port component. There may be multiple VLANs, identified by a particular lldpXdot1LocVlanId, configured on the given port.')NEWLINElldpXdot1LocVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1, 1), VlanId())NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setReference('IEEE 802.1AB-2005 F.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanId.setDescription('The integer value used to identify the IEEE 802.1Q VLAN IDs with which the given port is compatible.')NEWLINElldpXdot1LocVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setReference('IEEE 802.1AB-2005 F.4.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocVlanName.setDescription('The string value used to identify VLAN name identified by the Vlan Id associated with the given port on the local system. This object should contain the value of the dot1QVLANStaticName object (defined in IETF RFC 2674) identified with the given lldpXdot1LocVlanId.')NEWLINElldpXdot1ConfigVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTable.setDescription('The table that controls selection of LLDP VLAN name TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2, 1), )NEWLINElldpXdot1LocVlanNameEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigVlanNameEntry"))NEWLINElldpXdot1ConfigVlanNameEntry.setIndexNames(*lldpXdot1LocVlanNameEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System VLAN name instance will be transmitted. This configuration object augments the lldpLocVlanEntry, therefore it is only present along with the VLAN Name instance contained in the associated lldpLocVlanNameEntry entry. Each active lldpXdot1ConfigVlanNameEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocVlanNameEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigVlanNameTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 2, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigVlanNameTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System VLAN name instance will be transmitted on the port defined by the given lldpXdot1LocVlanNameEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanTable.setDescription('This table contains one or more rows per Port and Protocol VLAN information about the local system.')NEWLINElldpXdot1LocProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocProtoVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEntry.setDescription('Port and protocol VLAN ID Information about a particular port component. There may be multiple port and protocol VLANs, identified by a particular lldpXdot1LocProtoVlanId, configured on the given port.')NEWLINElldpXdot1LocProtoVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), )))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setReference('IEEE 802.1AB-2005 F.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanId.setDescription('The integer value used to identify the port and protocol VLANs associated with the given port associated with the local system. A value of zero shall be used if the system either does not know the protocol VLAN ID (PPVID) or does not support port and protocol VLAN operation.')NEWLINElldpXdot1LocProtoVlanSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanSupported.setDescription('The truth value used to indicate whether the given port (associated with the local system) supports port and protocol VLANs.')NEWLINElldpXdot1LocProtoVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtoVlanEnabled.setDescription('The truth value used to indicate whether the port and protocol VLANs are enabled on the given port associated with the local system.')NEWLINElldpXdot1ConfigProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTable.setDescription('The table that controls selection of LLDP Port and Protocol VLAN ID TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3, 1), )NEWLINElldpXdot1LocProtoVlanEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigProtoVlanEntry"))NEWLINElldpXdot1ConfigProtoVlanEntry.setIndexNames(*lldpXdot1LocProtoVlanEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System Protocol VLAN instance will be transmitted. This configuration object augments the lldpXdot1LocVlanEntry, therefore it is only present along with the Port and Protocol VLAN ID instance contained in the associated lldpXdot1LocVlanEntry entry. Each active lldpXdot1ConfigProtoVlanEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocProtoVlanEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigProtoVlanTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 3, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtoVlanTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System Port and Protocol VLAN instance will be transmitted on the port defined by the given lldpXdot1LocProtoVlanEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setReference('IEEE 802.1AB-2005 F.5')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolTable.setDescription('This table contains one or more rows per protocol identity information on the local system known to this agent.')NEWLINElldpXdot1LocProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocProtocolIndex"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setReference('IEEE 802.1AB-2005 F.5')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolEntry.setDescription('Information about particular protocols that are accessible through the given port component. There may be multiple protocols, identified by particular lldpXdot1ProtocolIndex, and lldpLocPortNum.')NEWLINElldpXdot1LocProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolIndex.setDescription('This object represents an arbitrary local integer value used by this agent to identify a particular protocol identity.')NEWLINElldpXdot1LocProtocolId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setReference('IEEE 802.1AB-2005 F.5.3')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocProtocolId.setDescription('The octet string value used to identify the protocols associated with the given port of the local system.')NEWLINElldpXdot1ConfigProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTable.setDescription('The table that controls selection of LLDP Protocol TLV instances to be transmitted on individual ports.')NEWLINElldpXdot1ConfigProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4, 1), )NEWLINElldpXdot1LocProtocolEntry.registerAugmentions(("DES-1210-28MEbx", "lldpXdot1ConfigProtocolEntry"))NEWLINElldpXdot1ConfigProtocolEntry.setIndexNames(*lldpXdot1LocProtocolEntry.getIndexNames())NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolEntry.setDescription('LLDP configuration information that specifies the set of ports (represented as a PortList) on which the Local System Protocol instance will be transmitted. This configuration object augments the lldpXdot1LocProtoEntry, therefore it is only present along with the Protocol instance contained in the associated lldpXdot1LocProtoEntry entry. Each active lldpXdot1ConfigProtocolEntry must be restored from non-volatile storage (along with the corresponding lldpXdot1LocProtocolEntry) after a re-initialization of the management system.')NEWLINElldpXdot1ConfigProtocolTxEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 1, 4, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setReference('IEEE 802.1AB-2005 10.2.1.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1ConfigProtocolTxEnable.setDescription('The boolean value that indicates whether the corresponding Local System Protocol Identity instance will be transmitted on the port defined by the given lldpXdot1LocProtocolEntry. The value of this object must be restored from non-volatile storage after a re-initialization of the management system.')NEWLINElldpXdot1LocTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1LocTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocTable.setDescription('This table contains one row per port for IEEE 802.1 organizationally defined LLDP extension on the local system known to this agent.')NEWLINElldpXdot1LocEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1LocPortVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1LocEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocEntry.setDescription('Information about IEEE 802.1 organizationally defined LLDP extension.')NEWLINElldpXdot1LocPortVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setReference('IEEE 802.1AB-2005 F.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1LocPortVlanId.setDescription("The integer value used to identify the port's VLAN identifier associated with the local system. A value of zero shall be used if the system either does not know the PVID or does not support port-based VLAN operation.")NEWLINElldpXdot1RemTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemTable.setDescription('This table contains one or more rows per physical network connection known to this agent. The agent may wish to ensure that only one lldpXdot1RemEntry is present for each local port, or it may choose to maintain multiple lldpXdot1RemEntries for the same local port.')NEWLINElldpXdot1RemEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemPortVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemEntry.setDescription('Information about a particular port component.')NEWLINElldpXdot1RemPortVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setReference('IEEE 802.1AB-2005 F.2.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemPortVlanId.setDescription("The integer value used to identify the port's VLAN identifier associated with the remote system. if the remote system either does not know the PVID or does not support port-based VLAN operation, the value of lldpXdot1RemPortVlanId should be zero.")NEWLINElldpXdot1RemProtoVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanTable.setDescription('This table contains one or more rows per Port and Protocol VLAN information about the remote system, received on the given port.')NEWLINElldpXdot1RemProtoVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemProtoVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEntry.setDescription('Port and protocol VLAN name Information about a particular port component. There may be multiple protocol VLANs, identified by a particular lldpXdot1RemProtoVlanId, configured on the remote system.')NEWLINElldpXdot1RemProtoVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), )))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setReference('IEEE 802.1AB-2005 F.3.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanId.setDescription('The integer value used to identify the port and protocol VLANs associated with the given port associated with the remote system. If port and protocol VLANs are not supported on the given port associated with the remote system, or if the port is not enabled with any port and protocol VLAN, the value of lldpXdot1RemProtoVlanId should be zero.')NEWLINElldpXdot1RemProtoVlanSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 2), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanSupported.setDescription('The truth value used to indicate whether the given port (associated with the remote system) is capable of supporting port and protocol VLANs.')NEWLINElldpXdot1RemProtoVlanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 2, 1, 3), TruthValue()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setReference('IEEE 802.1AB-2005 F.3.1')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtoVlanEnabled.setDescription('The truth value used to indicate whether the port and protocol VLANs are enabled on the given port associated with the remote system.')NEWLINElldpXdot1RemVlanNameTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setReference('IEEE 802.1AB-2005 F.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameTable.setDescription('This table contains one or more rows per IEEE 802.1Q VLAN name information about the remote system, received on the given port.')NEWLINElldpXdot1RemVlanNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemVlanId"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanNameEntry.setDescription('VLAN name Information about a particular port component. There may be multiple VLANs, identified by a particular lldpXdot1RemVlanId, received on the given port.')NEWLINElldpXdot1RemVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1, 1), VlanId())NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setReference('IEEE 802.1AB-2005 F.4.2')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanId.setDescription('The integer value used to identify the IEEE 802.1Q VLAN IDs with which the given port of the remote system is compatible.')NEWLINElldpXdot1RemVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setReference('IEEE 802.1AB-2005 F.4.4')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemVlanName.setDescription('The string value used to identify VLAN name identified by the VLAN Id associated with the remote system.')NEWLINElldpXdot1RemProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4), )NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolTable.setDescription('This table contains one or more rows per protocol information about the remote system, received on the given port.')NEWLINElldpXdot1RemProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "lldpXdot1RemProtocolIndex"))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolEntry.setDescription('Protocol information about a particular port component. There may be multiple protocols, identified by a particular lldpXdot1ProtocolIndex, received on the given port.')NEWLINElldpXdot1RemProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolIndex.setDescription('This object represents an arbitrary local integer value used by this agent to identify a particular protocol identity.')NEWLINElldpXdot1RemProtocolId = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 32, 13, 3, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setReference('IEEE 802.1AB-2005 F.5.3')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setStatus('current')NEWLINEif mibBuilder.loadTexts: lldpXdot1RemProtocolId.setDescription('The octet string value used to identify the protocols associated with the given port of remote system.')NEWLINEsecurityDhcpServerScreen = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7))NEWLINEdhcpServerScreenEnablePortlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 1), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnablePortlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnablePortlist.setDescription('To enable or disable DHCP Server Screening port list.')NEWLINEdhcpServerScreenEnableVlanlist = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnableVlanlist.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenEnableVlanlist.setDescription('To enable or disable DHCP Server Screening vlan list.')NEWLINEdhcpServerScreenLogSuppressDuration = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 5, 30))).clone(namedValues=NamedValues(("one-min", 1), ("five-min", 5), ("thirty-min", 30)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpServerScreenLogSuppressDuration.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpServerScreenLogSuppressDuration.setDescription('DSS Trap Log Suppress Duration.')NEWLINEfilterDHCPServerTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4), )NEWLINEif mibBuilder.loadTexts: filterDHCPServerTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerTable.setDescription('A table to control filter DHCP Server for the entire switch or for each interface in the switch.')NEWLINEfilterDHCPServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "filterDHCPServerIpAddr"), (0, "DES-1210-28MEbx", "filterDHCPServerClientMacAddr"))NEWLINEif mibBuilder.loadTexts: filterDHCPServerEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerEntry.setDescription('An entry appears in this table for each interface in the system.')NEWLINEfilterDHCPServerIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 1), IpAddress())NEWLINEif mibBuilder.loadTexts: filterDHCPServerIpAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerIpAddr.setDescription("Specifies either the Network or Host address from which the switch can be managed. An address 0.0.0.0 indicates 'Any Manager'.")NEWLINEfilterDHCPServerClientMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 2), MacAddress().clone(hexValue="000102030405"))NEWLINEif mibBuilder.loadTexts: filterDHCPServerClientMacAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerClientMacAddr.setDescription('Ethernet Mac Address.')NEWLINEfilterDHCPServerPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: filterDHCPServerPortList.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerPortList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEfilterDHCPServerVlanList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: filterDHCPServerVlanList.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerVlanList.setDescription("Specifies the port numbers through which the authorized manager can access the switch. By default the authorized manager is allowed to access the switch through all the ports. If a set of ports are configured in the 'PortList', the manager can access the switch only through the configured ports.")NEWLINEfilterDHCPServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 7, 4, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: filterDHCPServerRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: filterDHCPServerRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEsecurityTrafficSeg = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9))NEWLINEtrafficSegTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1), )NEWLINEif mibBuilder.loadTexts: trafficSegTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegTable.setDescription('A Port-channel is created through ifMain table. After the creation of the port-channel, corresponding logical interface will be created in the ifMain table. This Port-channel table is indexed through Key values and allows to configure link selection policy and the Mac address for the port-channel. All other objects in this table displays the details of the port-channel')NEWLINEtrafficSegEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "trafficSegIfIndex"))NEWLINEif mibBuilder.loadTexts: trafficSegEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegEntry.setDescription('There is one entry in this table for each created port-channel port')NEWLINEtrafficSegIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: trafficSegIfIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegIfIndex.setDescription("The ifIndex of the port-channel(Aggregator's interface index). ")NEWLINEtrafficSegMemberList = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 9, 1, 1, 2), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: trafficSegMemberList.setStatus('current')NEWLINEif mibBuilder.loadTexts: trafficSegMemberList.setDescription('Port list of port channel.')NEWLINEsecurityAAC = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11))NEWLINEaacAuthenAdminState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthenAdminState.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthenAdminState.setDescription('This object indicates the Access Authentication is enable or disable.')NEWLINEaacAuthParamResponseTimeout = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthParamResponseTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthParamResponseTimeout.setDescription('Timeout in second for login authentication response.')NEWLINEaacAuthParamAttempt = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAuthParamAttempt.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAuthParamAttempt.setDescription('The amount for login authentication, if login failure exceed, connection or access would be locked.')NEWLINEaacAPAuthMethodGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4))NEWLINEaacAPLoginMethod = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1))NEWLINEaacAPEnableMethod = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2))NEWLINEaacAPConsoleLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPConsoleLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPConsoleLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via local console')NEWLINEaacAPTelnetLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPTelnetLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPTelnetLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via telnet.')NEWLINEaacAPSSHLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPSSHLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPSSHLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via SSH.')NEWLINEaacAPHttpLoginMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPHttpLoginMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPHttpLoginMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via HTTP.')NEWLINEaacAPConsoleEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPConsoleEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPConsoleEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via local console.')NEWLINEaacAPTelnetEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPTelnetEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPTelnetEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via telnet.')NEWLINEaacAPSSHEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPSSHEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPSSHEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via SSH.')NEWLINEaacAPHttpEnableMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 4, 2, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAPHttpEnableMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAPHttpEnableMethod.setDescription('Specify the way which has to execute authentication while login the system and the method for authentication.Access system via HTTP.')NEWLINEaacServerGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5), )NEWLINEif mibBuilder.loadTexts: aacServerGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupTable.setDescription('A table that contains informations about server group.')NEWLINEaacServerGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacServerGroupIndex"))NEWLINEif mibBuilder.loadTexts: aacServerGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupEntry.setDescription('A list of the group including servers.')NEWLINEaacServerGroupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 9))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacServerGroupIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry .')NEWLINEaacServerGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerGroupName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupName.setDescription("A human-readable text string of the method group. The name is writable only if Group is new created, which the value of aacServerGroupRowStatus is 'notReady'.")NEWLINEaacServersInGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 3), Bits().clone(namedValues=NamedValues(("id1", 0), ("id2", 1), ("id3", 2), ("id4", 3), ("id5", 4), ("id6", 5), ("id7", 6), ("id8", 7), ("id9", 8), ("id10", 9), ("id11", 10), ("id12", 11), ("id13", 12), ("id14", 13), ("id15", 14), ("id16", 15)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServersInGroup.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServersInGroup.setDescription('The list of servers in the group, each bit indicates a specified server ID. The server must be created before including it.')NEWLINEaacServerGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 5, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerGroupRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerGroupRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEiPv4aacServerInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6), )NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoTable.setDescription('A table that contains information about severs.')NEWLINEiPv4aacServerInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1), ).setIndexNames((0, "DES-1210-28MEbx", "iPv4aacServerIndex"))NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerInfoEntry.setDescription('A list of the information of server .')NEWLINEiPv4aacServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: iPv4aacServerIndex.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry.')NEWLINEiPv4aacServerIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerIPAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerIPAddr.setDescription('The IP address of Server')NEWLINEiPv4aacServerAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthProtocol.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthProtocol.setDescription('The authentication protocol provided by the Server.')NEWLINEiPv4aacServerAuthPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthPort.setDescription('The TCP/IP port .')NEWLINEiPv4aacServerAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 254))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthKey.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerAuthKey.setDescription('The key used while authentication process.')NEWLINEiPv4aacServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerTimeout.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerTimeout.setDescription('Server response timeout .')NEWLINEiPv4aacServerRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: iPv4aacServerRetryCount.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerRetryCount.setDescription('Client retry count . (-1: No retry mechanism)')NEWLINEiPv4aacServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 6, 1, 8), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: iPv4aacServerRowStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: iPv4aacServerRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacServerInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7), )NEWLINEif mibBuilder.loadTexts: aacServerInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInfoTable.setDescription('A table that contains information about severs.')NEWLINEaacServerInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacServerIndex"))NEWLINEif mibBuilder.loadTexts: aacServerInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInfoEntry.setDescription('A list of the information of server .')NEWLINEaacServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacServerIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIndex.setDescription('A value that uniquely identifies this SwAACServerGroupEntry.')NEWLINEaacServerIPType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)).clone(1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerIPType.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIPType.setDescription('The IP address of the AAC server IP type referred to in this table entry. (IPv4=1, IPv6=2)')NEWLINEaacServerIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 3), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerIPAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerIPAddr.setDescription('The IP address of Server')NEWLINEaacServerInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 4), OctetString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerInterfaceName.setDescription('Specifies the interface name when the aacServerIPAddr is linklocal address.')NEWLINEaacServerAuthProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthProtocol.setDescription('The authentication protocol provided by the Server.')NEWLINEaacServerAuthPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthPort.setDescription('The TCP/IP port .')NEWLINEaacServerAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 254))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAuthKey.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAuthKey.setDescription('The key used while authentication process.')NEWLINEaacServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerTimeout.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerTimeout.setDescription('Server response timeout .')NEWLINEaacServerRetryCount = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerRetryCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerRetryCount.setDescription('Client retry count . (-1: No retry mechanism)')NEWLINEaacServerAccountingPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerAccountingPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerAccountingPort.setDescription('The accounting port .')NEWLINEaacServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 7, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacServerRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacLoginMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8), )NEWLINEif mibBuilder.loadTexts: aacLoginMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListTable.setDescription('A table that contains information about Login authentication method lists.')NEWLINEaacLoginMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacLoginMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacLoginMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacLoginMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacLoginMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacLoginMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod1.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod2.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod3.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLoginMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethod4.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacLoginMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 8, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacLoginMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLoginMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacEnableMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9), )NEWLINEif mibBuilder.loadTexts: aacEnableMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListTable.setDescription('A table that contains information about Enable authentication method lists.')NEWLINEaacEnableMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacEnableMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacEnableMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacEnableMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacEnableMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacEnableMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod1.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod2.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod3.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacEnableMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethod4.setDescription('The type of Login method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacEnableMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 9, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacEnableMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacEnableMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacLocalEnablePassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacLocalEnablePassword.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacLocalEnablePassword.setDescription('This object is used to set Local Enable Password.')NEWLINEaacAccountingMethodListTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11), )NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListTable.setDescription('A table that contains information about Accounting authentication method lists.')NEWLINEaacAccountingMethodListEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1), ).setIndexNames((0, "DES-1210-28MEbx", "aacAccountingMethodListIndex"))NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListEntry.setDescription('A list of the Authentication methods.')NEWLINEaacAccountingMethodListIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListIndex.setDescription('A value that identifies this method list.')NEWLINEaacAccountingMethodListName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListName.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListName.setDescription('A human-readable text string of the method list.')NEWLINEaacAccountingMethod1 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod1.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod1.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod2 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod2.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod2.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod3 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod3.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod3.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethod4 = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(-1, 0, 1, 2))).clone(namedValues=NamedValues(("none", -1), ("local", 0), ("tacacsPlus", 1), ("radius", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingMethod4.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethod4.setDescription('The type of Accounting method list. Besides the pre-defined type, it also allow to be set user-defined group by aacServerGroupIndex.')NEWLINEaacAccountingMethodListRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 11, 1, 7), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingMethodListRowStatus.setDescription("This object indicates the status of this entry. An entry is created in this table when this object is SET to 'createAndWait'. The entry in this table is used when the status of this object is SET 'active'. The entry in this table is not used when this object is SET 'notInService'. An entry created in this table is be deleted when this object is SET 'destroy'.")NEWLINEaacAccountingServiceIndex = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12))NEWLINEaacAccountingServiceNetwork = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceNetwork.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceNetwork.setDescription('This object indicates aac Accounting Service Network is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceShell = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceShell.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceShell.setDescription('This object indicates aac Accounting Service Shell is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceSystem = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 12, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, -1))).clone(namedValues=NamedValues(("radius-only", 0), ("default-method-list", 1), ("method-list-name", 2), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceSystem.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceSystem.setDescription('This object indicates aac Accounting System Shell is radius_only, default_method_list, method_list_name and disable about Accounting Service Network.')NEWLINEaacAccountingServiceCommand = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13))NEWLINEaacAccountingServiceCommandAdministrator = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandAdministrator.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandAdministrator.setDescription('This object indicates aac Accounting Command Admin is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandOperator = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandOperator.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandOperator.setDescription('This object indicates aac Accounting Command Operato is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandPoweruser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandPoweruser.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandPoweruser.setDescription('This object indicates aac Accounting Command Power user is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacAccountingServiceCommandUser = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 13, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, -1))).clone(namedValues=NamedValues(("method1", 0), ("method2", 1), ("method3", 2), ("method4", 3), ("disabled", -1))).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandUser.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacAccountingServiceCommandUser.setDescription('This object indicates aac Accounting Command User is method1, method2, method3 , method4 and disable about Accounting Service Command')NEWLINEaacServerPasswordEncryption = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 14, 11, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: aacServerPasswordEncryption.setStatus('current')NEWLINEif mibBuilder.loadTexts: aacServerPasswordEncryption.setDescription('This object is used to configure server password encryption status.')NEWLINEmcastFilterPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1), )NEWLINEif mibBuilder.loadTexts: mcastFilterPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortTable.setDescription('A table to control multicast filtering modes.')NEWLINEmcastFilterPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "mcastFilterPortIndex"))NEWLINEif mibBuilder.loadTexts: mcastFilterPortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortEntry.setDescription('An entry appears in this table for each interface in the mcastFiltertem. Index to the table is the interface index of the port.')NEWLINEmcastFilterPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28)))NEWLINEif mibBuilder.loadTexts: mcastFilterPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortIndex.setDescription('Interface index of the port for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEmcastFilterPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 49, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("forward", 1), ("filter", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: mcastFilterPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: mcastFilterPortType.setDescription('Configures the multicast filtering modes as below : forward -Forwards all unregistered groups. filter -Filters all unregistered groups.')NEWLINEstaticARPTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2), )NEWLINEif mibBuilder.loadTexts: staticARPTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPTable.setDescription('A list of the Static MACs')NEWLINEstaticARPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "staticARPIP"), (0, "DES-1210-28MEbx", "staticARPMac"))NEWLINEif mibBuilder.loadTexts: staticARPEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPEntry.setDescription('A Static MAC entry containing the mac and forwarding port.')NEWLINEstaticARPIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticARPIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPIP.setDescription('The VLAN ID of the static ARP IP.')NEWLINEstaticARPMac = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: staticARPMac.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPMac.setDescription('The MAC address associated of the static ARP entry.')NEWLINEstaticARPRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 34, 2, 1, 5), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: staticARPRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: staticARPRowStatus.setDescription('The status of an entry in the Static ARP Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available. The trunk member port can not set up static ARP.')NEWLINEsysGratuitousARPGlobalSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1))NEWLINEsysGratuitousARPSettings = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2))NEWLINEsysGratuitousARPIPIfStatusUp = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIPIfStatusUp.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIPIfStatusUp.setDescription('This object indicates Send On IP Interface Status Up is enabled or disabled.')NEWLINEsysGratuitousARPDuplicateIPDetected = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPDuplicateIPDetected.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPDuplicateIPDetected.setDescription('This object indicates Send On Duplicate IP Detected is enabled or disabled.')NEWLINEsysGratuitousARPLearning = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPLearning.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPLearning.setDescription('This object indicates Gratuitous ARP Learning is enabled or disabled.')NEWLINEsysGratuitousARPTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1), )NEWLINEif mibBuilder.loadTexts: sysGratuitousARPTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPTable.setDescription('Set/Add Gratuitous ARP interface name and interval time.')NEWLINEsysGratuitousARPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sysGratuitousARPIFName"))NEWLINEif mibBuilder.loadTexts: sysGratuitousARPEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPEntry.setDescription('The entry of gratuitous ARP!')NEWLINEsysGratuitousARPIFName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 24))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIFName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPIFName.setDescription('Interface name.')NEWLINEsysGratuitousARPInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 48, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: sysGratuitousARPInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: sysGratuitousARPInterval.setDescription('Gratuitous ARP interval time for each interface.')NEWLINEagentCPUutilization = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1))NEWLINEagentMEMutilization = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2))NEWLINEagentCPUutilizationIn5sec = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 1), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5sec.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5sec.setDescription('The time scale is set at 5 second intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentCPUutilizationIn1min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn1min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn1min.setDescription('The time scale is set at 1 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentCPUutilizationIn5min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 1, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentCPUutilizationIn5min.setDescription('The time scale is set at 5 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn5sec = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 1), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5sec.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5sec.setDescription('The time scale is set at 5 second intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn1min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 2), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn1min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn1min.setDescription('The time scale is set at 1 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEagentMEMutilizationIn5min = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 100, 2, 3), Integer32()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5min.setStatus('current')NEWLINEif mibBuilder.loadTexts: agentMEMutilizationIn5min.setDescription('The time scale is set at 5 minute intervals. The value will be between 0% (idle) and 100% (very busy).')NEWLINEl2PTState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTState.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTState.setDescription('This object indicates the global state of Layer 2 protocol tunneling.')NEWLINEl2PTPortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2), )NEWLINEif mibBuilder.loadTexts: l2PTPortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortTable.setDescription('A table that cont ains the cable situation for each port.')NEWLINEl2PTEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "l2PTPortIndex"))NEWLINEif mibBuilder.loadTexts: l2PTEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTEntry.setDescription('A list of cable situations for each port on the device.')NEWLINEl2PTPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28)))NEWLINEif mibBuilder.loadTexts: l2PTPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortIndex.setDescription('This object indicates the port number. For all machines give maximum port number.')NEWLINEl2PTPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("uni", 2), ("nni", 3))).clone('none')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTPortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTPortType.setDescription("This object indicates the Layer 2 protocol tunneling port type. The 'none' value indicates that the port is normal. Layer 2 protocol tunneling is disabled on this port. The 'uni' value indicates that the port is connected to the customer site. A Layer 2 PDU received on a UNI port can be tunneled to a remote customer site across the provider network. The 'nni' value indicates that the port is connected to the provider network. A Tunneled Layer 2 PDU received on an NNI port will be restored to its original format.")NEWLINEl2PTProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 2, 1, 3), Bits().clone(namedValues=NamedValues(("stp", 0), ("gvrp", 1), ("macCC", 2), ("macCD", 3)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTProtocol.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTProtocol.setDescription("This object indicates the tunneled protocols on this port. This object can only be applied on a UNI port. If the 'stp' BIT is set, the STP BPDU will be tunneled. If the 'gvrp' BIT is set, the GVRP PDU will be tunneled. If the 'mac-01-00-0C-CC-CC-CC' BIT is set, the PDU with the destination MAC address 01-00-0C-CC-CC-CC will be tunneled . If the 'mac-01-00-0C-CC-CC-CD' BIT is set, then the PDU with the destination MAC address 01-00-0C-CC-CC-CD will be tunneled.")NEWLINEl2PTThresholdTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3), )NEWLINEif mibBuilder.loadTexts: l2PTThresholdTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTThresholdTable.setDescription('This table contains the protocol tunneling threshold of a UNI port.')NEWLINEl2PTThresholdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "l2PTPortIndex"), (0, "DES-1210-28MEbx", "l2PTProtocolIndex"))NEWLINEif mibBuilder.loadTexts: l2PTThresholdEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTThresholdEntry.setDescription('A list with the Layer2 Protocol tunneling threshold.')NEWLINEl2PTProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("stp", 1), ("gvrp", 2), ("macCC", 3), ("macCD", 4))))NEWLINEif mibBuilder.loadTexts: l2PTProtocolIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTProtocolIndex.setDescription('This object indicates the tunneled protocol of the port.')NEWLINEl2PTDropThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 102, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: l2PTDropThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: l2PTDropThreshold.setDescription('This object indicates the drop threshold for a given protocol on a UNI port. If the arrival rate of a tunneled protocol has reached its threshold, the received PDUs of this protocol will be dropped. The value 0 indicates there is no threshold for the protocol.')NEWLINEipv4smtpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpState.setDescription('Enable or Disable SMTP function.')NEWLINEipv4smtpServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 2), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpServerAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpServerAddr.setDescription("SMTP Server's IP Address")NEWLINEipv4smtpServerPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 3), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpServerPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpServerPort.setDescription("SMTP Server's port")NEWLINEipv4smtpSelfMailAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpSelfMailAddr.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ipv4smtpSelfMailAddr.setDescription("The sender's (DUT) mail address .")NEWLINEipv4smtpRecvMailAddrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5), )NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrTable.setDescription("Receivers' mail address table.")NEWLINEipv4smtpRecvMailAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ipv4smtpRecvMailAddrIndex"))NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrEntry.setDescription("Receivers' mail address entry.")NEWLINEipv4smtpRecvMailAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrIndex.setDescription("Receivers' mail address index (1~8).")NEWLINEipv4smtpRecvMailAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddr.setDescription("Receivers' mail address.")NEWLINEipv4smtpRecvMailAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 5, 1, 3), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: ipv4smtpRecvMailAddrStatus.setDescription("Rowstatus of the receiver's mail address.")NEWLINEsysSMTPServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6))NEWLINEsmtpState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpState.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpState.setDescription('Enable or Disable SMTP function.')NEWLINEsmtpServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 2), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddr.setDescription("SMTP Server's IP Address")NEWLINEsmtpServerAddrType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddrType.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddrType.setDescription("SMTP Server's Address type.")NEWLINEsmtpServerAddrInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 4), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerAddrInterfaceName.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerAddrInterfaceName.setDescription('Specifies the interface name when the smtpServerAddrInterfaceName is linklocal address.')NEWLINEsmtpServerPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 5), Integer32()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpServerPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpServerPort.setDescription("SMTP Server's port")NEWLINEsmtpSelfMailAddr = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 6), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpSelfMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpSelfMailAddr.setDescription("The sender's (DUT) mail address .")NEWLINEsmtpRecvMailAddrTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7), )NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrTable.setDescription("Receivers' mail address table.")NEWLINEsmtpRecvMailAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1), ).setIndexNames((0, "DES-1210-28MEbx", "smtpRecvMailAddrIndex"))NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrEntry.setDescription("Receivers' mail address entry.")NEWLINEsmtpRecvMailAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrIndex.setDescription("Receivers' mail address index (1~8).")NEWLINEsmtpRecvMailAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 2), OctetString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddr.setDescription("Receivers' mail address.")NEWLINEsmtpRecvMailAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 40, 6, 7, 1, 3), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: smtpRecvMailAddrStatus.setDescription("Rowstatus of the receiver's mail address.")NEWLINEigmpMulticastVlanStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanStatus.setDescription('Enable/Disable IGMP Multicast Vlan function.')NEWLINEigmpMulticastVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2), )NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTable.setDescription('Information about the IGMP snooping multicast VLAN table.')NEWLINEigmpMulticastVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igmpMulticastVlanid"))NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanEntry.setDescription('The entry of igmpMulticastVlanTable.')NEWLINEigmpMulticastVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanid.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanid.setDescription('This object indicates the VLAN ID of the IGMP snooping multicast VLAN entry.')NEWLINEigmpMulticastVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanName.setDescription('This object indicates the VLAN name of the IGMP snooping multicast VLAN entry.')NEWLINEigmpMulticastVlanSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanSourcePort.setDescription('This object indicates the port list of the source ports of the IGMP snooping multicast VLAN. The source ports will be set as tag ports of the VLAN entry and the IGMP control messages received from the member ports will be forwarded to the source ports.')NEWLINEigmpMulticastVlanMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanMemberPort.setDescription('This object indicates the port list of the member ports of the IGMP snooping multicast VLAN. The source ports will be set as untagged ports of the VLAN entry and the IGMP control messages received from the member ports will be forwarded to the source ports.')NEWLINEigmpMulticastVlanTagMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 5), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTagMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanTagMemberPort.setDescription('This object indicates the port list of the tag member ports of the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanUntaggedSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanUntaggedSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanUntaggedSourcePort.setDescription('This object indicates the port list of the untag source ports of the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanState.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanState.setDescription('This object can be used to enable or disable the IGMP snooping multicast VLAN.')NEWLINEigmpMulticastVlanReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplaceSourceIp.setDescription('The replacement source IP of this multicast VLAN.')NEWLINEigmpMulticastVlanRemapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRemapPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRemapPriority.setDescription('The remap priority of this multicast VLAN.')NEWLINEigmpMulticastVlanReplacePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplacePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanReplacePriority.setDescription('The replacement priority of this multicast VLAN.')NEWLINEigmpMulticastVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 2, 1, 11), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEigmpMulticastVlanGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3), )NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupTable.setDescription('The table containing the IGMP snooping multicast VLAN group information')NEWLINEigmpMulticastVlanGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "igmpMulticastVlanGroupVid"), (0, "DES-1210-28MEbx", "igmpMulticastVlanGroupFromIp"), (0, "DES-1210-28MEbx", "igmpMulticastVlanGroupToIp"))NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupEntry.setDescription('Information about the current IGMP snooping multicast VLAN group.')NEWLINEigmpMulticastVlanGroupVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupVid.setDescription('This object indicates the VID of the IGMP snooping multicast VLAN group.')NEWLINEigmpMulticastVlanGroupFromIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 2), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupFromIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupFromIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEigmpMulticastVlanGroupToIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 3), IpAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupToIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupToIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEigmpMulticastVlanGroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: igmpMulticastVlanGroupStatus.setDescription('This object indicates the status of this entry.')NEWLINEmulticastVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4), )NEWLINEif mibBuilder.loadTexts: multicastVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanTable.setDescription('Information about the IGMP/MLD snooping multicast VLAN table.')NEWLINEmulticastVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1), ).setIndexNames((0, "DES-1210-28MEbx", "multicastVlanid"))NEWLINEif mibBuilder.loadTexts: multicastVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanEntry.setDescription('The entry of multicastVlanTable.')NEWLINEmulticastVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanid.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanid.setDescription('This object indicates the VLAN ID of the IGMP/MLD snooping multicast VLAN entry.')NEWLINEmulticastVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanName.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanName.setDescription('This object indicates the VLAN name of the IGMP/MLD snooping multicast VLAN entry.')NEWLINEmulticastVlanSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 3), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanSourcePort.setDescription('This object indicates the port list of the source ports of the IGMP/MLD snooping multicast VLAN. The source ports will be set as tag ports of the VLAN entry and the IGMP control messages received from themember ports will be forwarded to the source ports.')NEWLINEmulticastVlanMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 4), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanMemberPort.setDescription('This object indicates the port list of the member ports of the IGMP/MLD snooping multicast VLAN. The source ports will be set as untagged ports of the VLAN entry and the IGMP control messages received from themember ports will be forwarded to the source ports.')NEWLINEmulticastVlanTagMemberPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 5), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanTagMemberPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanTagMemberPort.setDescription('This object indicates the port list of the tag member ports of the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanUntaggedSourcePort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 6), PortList()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanUntaggedSourcePort.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanUntaggedSourcePort.setDescription('This object indicates the port list of the untag source ports of the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanState.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanState.setDescription('This object can be used to enable or disable the IGMP/MLD snooping multicast VLAN.')NEWLINEmulticastVlanIgmpReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 8), IpAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanIgmpReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanIgmpReplaceSourceIp.setDescription('The replacement source IP of this IGMP snooping multicast VLAN.')NEWLINEmulticastVlanMldReplaceSourceIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 9), Ipv6Address()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanMldReplaceSourceIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanMldReplaceSourceIp.setDescription('The replacement source IP of this MLD snooping multicast VLAN.')NEWLINEmulticastVlanRemapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7)).clone(-1)).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanRemapPriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanRemapPriority.setDescription('The remap priority of this multicast VLAN.')NEWLINEmulticastVlanReplacePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: multicastVlanReplacePriority.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanReplacePriority.setDescription('The replacement priority of this multicast VLAN.')NEWLINEmulticastVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 4, 1, 12), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEmulticastVlanGroupTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5), )NEWLINEif mibBuilder.loadTexts: multicastVlanGroupTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupTable.setDescription('The table containing the IGMP/MLD snooping multicast VLAN group information')NEWLINEmulticastVlanGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1), ).setIndexNames((0, "DES-1210-28MEbx", "multicastVlanGroupVid"), (0, "DES-1210-28MEbx", "multicastVlanGroupIpType"), (0, "DES-1210-28MEbx", "multicastVlanGroupFromIp"), (0, "DES-1210-28MEbx", "multicastVlanGroupToIp"))NEWLINEif mibBuilder.loadTexts: multicastVlanGroupEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupEntry.setDescription('The entry of multicastVlanGroupTable.')NEWLINEmulticastVlanGroupVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupVid.setDescription('This object indicates the VID of the IGMP/MLD snooping multicast VLAN group.')NEWLINEmulticastVlanGroupIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("iPv4", 1), ("iPv6", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupIpType.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupIpType.setDescription('Type of specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupFromIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 3), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupFromIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupFromIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupToIp = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 4), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupToIp.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupToIp.setDescription('Specifies the multicast address list for this VLAN.')NEWLINEmulticastVlanGroupStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 27, 5, 1, 5), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: multicastVlanGroupStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: multicastVlanGroupStatus.setDescription('This object indicates the status of this entry.')NEWLINEpppoeGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoeGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoeGlobalState.setDescription('PPPoE global state')NEWLINEpppoePortTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2), )NEWLINEif mibBuilder.loadTexts: pppoePortTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortTable.setDescription('A table to control PPPoE features of the device.')NEWLINEpppoePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "pppoePortIndex"))NEWLINEif mibBuilder.loadTexts: pppoePortEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortEntry.setDescription('An entry appears in PPPoE table for each interface in the system.')NEWLINEpppoePortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 6))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: pppoePortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortIndex.setDescription('Interface index of the port for the configuration in this entry applies.')NEWLINEpppoePortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortState.setDescription('PPPoE per port state')NEWLINEpppoePortCircuitIDType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("ip", 0), ("mac", 1), ("udf", 2), ("vendor2", 3), ("vendor3", 4)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDType.setDescription('PPPoE per port circuit ID type')NEWLINEpppoePortUDFString = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortUDFString.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortUDFString.setDescription('PPPoE per port UDF string')NEWLINEpppoePortCircuitIDVendor3String = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDVendor3String.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortCircuitIDVendor3String.setDescription('PPPoE per port circuit ID vendor3 string')NEWLINEpppoePortRemoteIDType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("vendor2", 1), ("vendor3", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDType.setDescription('PPPoE per port remote ID type')NEWLINEpppoePortRemoteIDVendor3String = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 98, 2, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDVendor3String.setStatus('current')NEWLINEif mibBuilder.loadTexts: pppoePortRemoteIDVendor3String.setDescription('PPPoE per port remote ID vendor3 string')NEWLINErmonGlobalState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: rmonGlobalState.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonGlobalState.setDescription('This object is for enabling or disabling RMON function.')NEWLINErmonStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2))NEWLINErmonHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3))NEWLINErmonAlarm = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4))NEWLINErmonEvent = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5))NEWLINErmonStatsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1), )NEWLINEif mibBuilder.loadTexts: rmonStatsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsTable.setDescription('A list of Ethernet statistics entries.')NEWLINErmonStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonStatsIndex"))NEWLINEif mibBuilder.loadTexts: rmonStatsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsEntry.setDescription('A collection of statistics kept for a particular Ethernet interface. As an example, an instance of the etherStatsPkts object might be named etherStatsPkts.1')NEWLINErmonStatsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonStatsIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsIndex.setDescription('The value of this object uniquely identifies this etherStats entry.')NEWLINErmonStatsDataSource = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsDataSource.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsDataSource.setDescription('This object identifies the source of the data that this etherStats entry is configured to analyze. This source can be any ethernet interface on this device. In order to identify a particular interface, this object shall identify the instance of the ifIndex object, defined in RFC 2233 [17], for the desired interface. For example, if an entry were to receive data from interface #1, this object would be set to ifIndex.1. The statistics in this group reflect all packets on the local network segment attached to the identified interface. An agent may or may not be able to tell if fundamental changes to the media of the interface have occurred and necessitate an invalidation of this entry. For example, a hot-pluggable ethernet card could be pulled out and replaced by a token-ring card. In such a case, if the agent has such knowledge of the change, it is recommended that it invalidate this entry. This object may not be modified if the associated etherStatsStatus object is equal to valid(1).')NEWLINErmonStatsOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 3), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonStatsStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 2, 1, 1, 4), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonStatsStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonStatsStatus.setDescription('The status of this etherStats entry.')NEWLINErmonHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1), )NEWLINEif mibBuilder.loadTexts: rmonHistoryTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryTable.setDescription('A list of history control entries.')NEWLINErmonHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonHistoryIndex"))NEWLINEif mibBuilder.loadTexts: rmonHistoryEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryEntry.setDescription('A list of parameters that set up a periodic sampling of statistics. As an example, an instance of the historyControlInterval object might be named historyControlInterval.2')NEWLINErmonHistoryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonHistoryIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryIndex.setDescription('An index that uniquely identifies an entry in the historyControl table. Each such entry defines a set of samples at a particular interval for an interface on the device.')NEWLINErmonHistoryDataSource = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryDataSource.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryDataSource.setDescription('This object identifies the source of the data for which historical data was collected and placed in a media-specific table on behalf of this historyControlEntry. This source can be any interface on this device. In order to identify a particular interface, this object shall identify the instance of the ifIndex object, defined in RFC 2233 [17], for the desired interface. For example, if an entry were to receive data from interface #1, this object would be set to ifIndex.1. The statistics in this group reflect all packets on the local network segment attached to the identified interface. An agent may or may not be able to tell if fundamental changes to the media of the interface have occurred and necessitate an invalidation of this entry. For example, a hot-pluggable ethernet card could be pulled out and replaced by a token-ring card. In such a case, if the agent has such knowledge of the change, it is recommended that it invalidate this entry. This object may not be modified if the associated historyControlStatus object is equal to valid(1).')NEWLINErmonHistoryBucketsRequested = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(50)).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryBucketsRequested.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryBucketsRequested.setDescription('The requested number of discrete time intervals over which data is to be saved in the part of the media-specific table associated with this historyControlEntry. When this object is created or modified, the probe should set historyControlBucketsGranted as closely to this object as is possible for the particular probe implementation and available resources.')NEWLINErmonHistoryInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 3600)).clone(1800)).setUnits('Seconds').setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryInterval.setDescription("The interval in seconds over which the data is sampled for each bucket in the part of the media-specific table associated with this historyControlEntry. This interval can be set to any number of seconds between 1 and 3600 (1 hour). Because the counters in a bucket may overflow at their maximum value with no indication, a prudent manager will take into account the possibility of overflow in any of the associated counters. It is important to consider the minimum time in which any counter could overflow on a particular media type and set the historyControlInterval object to a value less than this interval. This is typically most important for the 'octets' counter in any media-specific table. For example, on an Ethernet network, the etherHistoryOctets counter could overflow in about one hour at the Ethernet's maximum utilization. This object may not be modified if the associated historyControlStatus object is equal to valid(1).")NEWLINErmonHistoryOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 5), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonHistoryStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 3, 1, 1, 6), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonHistoryStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonHistoryStatus.setDescription('The status of this historyControl entry. Each instance of the media-specific table associated with this historyControlEntry will be deleted by the agent if this historyControlEntry is not equal to valid(1).')NEWLINErmonAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1), )NEWLINEif mibBuilder.loadTexts: rmonAlarmTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmTable.setDescription('A list of alarm entries.')NEWLINErmonAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonAlarmIndex"))NEWLINEif mibBuilder.loadTexts: rmonAlarmEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmEntry.setDescription('A list of parameters that set up a periodic checking for alarm conditions. For example, an instance of the alarmValue object might be named alarmValue.8')NEWLINErmonAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonAlarmIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmIndex.setDescription('An index that uniquely identifies an entry in the alarm table. Each such entry defines a diagnostic sample at a particular interval for an object on the device.')NEWLINErmonAlarmInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 2), Integer32()).setUnits('Seconds').setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmInterval.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmInterval.setDescription('The interval in seconds over which the data is sampled and compared with the rising and falling thresholds. When setting this variable, care should be taken in the case of deltaValue sampling - the interval should be set short enough that the sampled variable is very unlikely to increase or decrease by more than 2^31 - 1 during a single sampling interval. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmVariable = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmVariable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmVariable.setDescription('The object identifier of the particular variable to be sampled. Only variables that resolve to an ASN.1 primitive type of INTEGER (INTEGER, Integer32, Counter32, Counter64, Gauge, or TimeTicks) may be sampled. Because SNMP access control is articulated entirely in terms of the contents of MIB views, no access control mechanism exists that can restrict the value of this object to identify only those objects that exist in a particular MIB view. Because there is thus no acceptable means of restricting the read access that could be obtained through the alarm mechanism, the probe must only grant write access to this object in those views that have read access to all objects on the probe. During a set operation, if the supplied variable name is not available in the selected MIB view, a badValue error must be returned. If at any time the variable name of an established alarmEntry is no longer available in the selected MIB view, the probe must change the status of this alarmEntry to invalid(4). This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmSampleType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("absoluteValue", 1), ("deltaValue", 2)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmSampleType.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmSampleType.setDescription('The method of sampling the selected variable and calculating the value to be compared against the thresholds. If the value of this object is absoluteValue(1), the value of the selected variable will be compared directly with the thresholds at the end of the sampling interval. If the value of this object is deltaValue(2), the value of the selected variable at the last sample will be subtracted from the current value, and the difference compared with the thresholds. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmRisingThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 5), Integer32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingThreshold.setDescription('A threshold for the sampled statistic. When the current sampled value is greater than or equal to this threshold, and the value at the last sampling interval was less than this threshold, a single event will be generated. A single event will also be generated if the first sample after this entry becomes valid is greater than or equal to this threshold and the associated alarmStartupAlarm is equal to risingAlarm(1) or risingOrFallingAlarm(3). After a rising event is generated, another such event will not be generated until the sampled value falls below this threshold and reaches the alarmFallingThreshold. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmFallingThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 6), Integer32()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingThreshold.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingThreshold.setDescription('A threshold for the sampled statistic. When the current sampled value is less than or equal to this threshold, and the value at the last sampling interval was greater than this threshold, a single event will be generated. A single event will also be generated if the first sample after this entry becomes valid is less than or equal to this threshold and the associated alarmStartupAlarm is equal to fallingAlarm(2) or risingOrFallingAlarm(3). After a falling event is generated, another such event will not be generated until the sampled value rises above this threshold and reaches the alarmRisingThreshold. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmRisingEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmRisingEventIndex.setDescription('The index of the eventEntry that is used when a rising threshold is crossed. The eventEntry identified by a particular value of this index is the same as identified by the same value of the eventIndex object. If there is no corresponding entry in the eventTable, then no association exists. In particular, if this value is zero, no associated event will be generated, as zero is not a valid event index. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmFallingEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmFallingEventIndex.setDescription('The index of the eventEntry that is used when a falling threshold is crossed. The eventEntry identified by a particular value of this index is the same as identified by the same value of the eventIndex object. If there is no corresponding entry in the eventTable, then no association exists. In particular, if this value is zero, no associated event will be generated, as zero is not a valid event index. This object may not be modified if the associated alarmStatus object is equal to valid(1).')NEWLINErmonAlarmOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 9), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmOwner.setDescription('The entity that configured this entry and is therefore using the resources assigned to it.')NEWLINErmonAlarmStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 4, 1, 1, 10), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonAlarmStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonAlarmStatus.setDescription('The status of this alarm entry.')NEWLINErmonEventTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1), )NEWLINEif mibBuilder.loadTexts: rmonEventTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventTable.setDescription('A list of events to be generated.')NEWLINErmonEventEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "rmonEventIndex"))NEWLINEif mibBuilder.loadTexts: rmonEventEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventEntry.setDescription('A set of parameters that describe an event to be generated when certain conditions are met. As an example, an instance of the eventLastTimeSent object might be named eventLastTimeSent.6')NEWLINErmonEventIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: rmonEventIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventIndex.setDescription('An index that uniquely identifies an entry in the event table. Each such entry defines one event that is to be generated when the appropriate conditions occur.')NEWLINErmonEventDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventDescription.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventDescription.setDescription('A comment describing this event entry.')NEWLINErmonEventType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("log", 2), ("snmptrap", 3), ("logandtrap", 4)))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventType.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventType.setDescription('The type of notification that the probe will make about this event. In the case of log, an entry is made in the log table for each event. In the case of snmp-trap, an SNMP trap is sent to one or more management stations.')NEWLINErmonEventCommunity = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventCommunity.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventCommunity.setDescription('If an SNMP trap is to be sent, it will be sent to the SNMP community specified by this octet string.')NEWLINErmonEventOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 5), OwnerString()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventOwner.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventOwner.setDescription("The entity that configured this entry and is therefore using the resources assigned to it. If this object contains a string starting with 'monitor' and has associated entries in the log table, all connected management stations should retrieve those log entries, as they may have significance to all management stations connected to this device")NEWLINErmonEventStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 22, 5, 1, 1, 6), RmonStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: rmonEventStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: rmonEventStatus.setDescription('The status of this event entry. If this object is not equal to valid(1), all associated log entries shall be deleted by the agent.')NEWLINEneighborTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1), )NEWLINEif mibBuilder.loadTexts: neighborTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborTable.setDescription('A list of the Neighbor Cache Table.')NEWLINEneighborEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "neighborIfindex"), (0, "DES-1210-28MEbx", "neighborIPv6Addr"), (0, "DES-1210-28MEbx", "neighborMACAddr"))NEWLINEif mibBuilder.loadTexts: neighborEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborEntry.setDescription('A Neighbor cache entry containing the ifindex and ipv6 addr.')NEWLINEneighborIfindex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborIfindex.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborIfindex.setDescription('The interface index of the Neighbor entry. Must be conform to the existing interface name.')NEWLINEneighborIPv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborIPv6Addr.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborIPv6Addr.setDescription('Allows the entry of an IP address that will be a Neighbor entry into the Neighbor Cache Table.')NEWLINEneighborMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 3), MacAddress()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborMACAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborMACAddr.setDescription('The MAC address associated of the Neighbor entry.')NEWLINEneighborType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("static", 1), ("dynamic", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborType.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborType.setDescription('The type associated of the Neighbor entry.')NEWLINEneighborCacheState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("static", 1), ("reachable", 2), ("incomplete", 3), ("stale", 4), ("delay", 5), ("probe", 6), ("notinservice", 7)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborCacheState.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborCacheState.setDescription('The type associated of the Neighbor entry.')NEWLINEneighborActiveStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("inactive", 2)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: neighborActiveStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborActiveStatus.setDescription('The active status of the Neighbor entry.')NEWLINEneighborRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 50, 1, 1, 7), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: neighborRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: neighborRowStatus.setDescription('The status of an entry in the Neighbor Cache Table. Only a subset of the rowstatus variables (active, createAndGo, destroy) are available.')NEWLINEdhcpv6RelayControl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1))NEWLINEdhcpv6RelayManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2))NEWLINEdhcpv6RelayOption37 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3))NEWLINEdhcpv6RelayOption38 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4))NEWLINEdhcpv6RelayOption18 = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5))NEWLINEdhcpv6RelayState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayState.setDescription('This object indicates DHCPv6 relay function is enabled or disabled.')NEWLINEdhcpv6RelayHopCount = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayHopCount.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayHopCount.setDescription('This object indicates the maximum number of router hops that the DHCPv6 packets can cross.')NEWLINEdhcpv6RelayInterfaceSettingsTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1), )NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpv6RelayInterfaceSettingsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpv6RelayInterface"), (0, "DES-1210-28MEbx", "dhcpv6RelayServerIP"))NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEdhcpv6RelayInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterface.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterface.setDescription('This object indicates the maximum number of router hops that the DHCPv6 packets can cross.')NEWLINEdhcpv6RelayServerIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 2), Ipv6Address()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayServerIP.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayServerIP.setDescription('This object indicates the DHCP server IP address.')NEWLINEdhcpv6RelayInterfaceSettingsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 2, 1, 1, 99), RowStatus()).setMaxAccess("readcreate")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayInterfaceSettingsRowStatus.setDescription('This object indicates the status of this entry.')NEWLINEdhcpv6RelayOption37State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37State.setDescription('This object indicates DHCPv6 relay option 37 function is enabled or disabled.')NEWLINEdhcpv6RelayOption37CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37CheckState.setDescription('This object indicates DHCPv6 relay option 37 Check function is enabled or disabled.')NEWLINEdhcpv6RelayOption37RemoteIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("cid-with-user-define", 1), ("user-define", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteIDType.setDescription('This object indicates the type of remote ID.')NEWLINEdhcpv6RelayOption37RemoteID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 3, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption37RemoteID.setDescription('This object displays the current remote ID of the device. If RemoteIDType is set to default, the value will be the MAC address of the device, and this object cannot be modified. If RemoteIDType is set to user-defined, a new value can be written to this object.')NEWLINEdhcpv6RelayOpt38Table = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1), )NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Table.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Table.setDescription('A table to control port security features of the device.')NEWLINEdhcpv6RelayOpt38Entry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "dhcpv6RelayOpt38PortIndex"))NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Entry.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38Entry.setDescription('An entry appears in port security table for each interface in the system.')NEWLINEdhcpv6RelayOpt38PortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortIndex.setDescription('The interface index for which the configuration in this entry applies. For all machines give maximum port number.')NEWLINEdhcpv6RelayOpt38PortState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortState.setDescription('Enable / disable option 38 port state.')NEWLINEdhcpv6RelayOpt38PortType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("default", 0), ("user-defined", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortType.setDescription('Configure option 38 port Type.')NEWLINEdhcpv6RelayOpt38PortID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 4, 1, 1, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortID.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOpt38PortID.setDescription('Configure option 38 port ID. Only works when type is user-defined')NEWLINEdhcpv6RelayOption18State = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18State.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18State.setDescription('This object indicates DHCPv6 relay option 18 function is enabled or disabled.')NEWLINEdhcpv6RelayOption18CheckState = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18CheckState.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18CheckState.setDescription('This object indicates DHCPv6 relay option 18 Check function is enabled or disabled.')NEWLINEdhcpv6RelayOption18InterfaceIDType = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 86, 5, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("default", 0), ("cid", 1), ("vendor1", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18InterfaceIDType.setStatus('current')NEWLINEif mibBuilder.loadTexts: dhcpv6RelayOption18InterfaceIDType.setDescription('This object indicates the type of Interface ID.')NEWLINEmacBasedVlanTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1), )NEWLINEif mibBuilder.loadTexts: macBasedVlanTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanTable.setDescription('A table that contains information on Vlan-MAC address mapping.')NEWLINEmacBasedVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "vlanMacMapIndex"))NEWLINEif mibBuilder.loadTexts: macBasedVlanEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanEntry.setDescription('Entry that contains Vlan-MAC address mapping.')NEWLINEvlanMacMapIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacMapIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapIndex.setDescription('Index of cmMacBasedVlanEntry. This object indicates the mac vlan entry for which the configurations in cmMacBasedVlanEntry is to be done.')NEWLINEvlanMacMapAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 2), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapAddr.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapAddr.setDescription('The Mac address for which the Vlan mapping is present in the entry.')NEWLINEvlanMacMapAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 3), MacAddress()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapAddrMask.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapAddrMask.setDescription('The Mac address for which the Vlan mapping is present in the entry.')NEWLINEvlanMacMapVid = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 4), VlanIndex()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapVid.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapVid.setDescription('The Vlan to which the mac address of this entry is mapped to.')NEWLINEvlanMacStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacStatus.setDescription('The status given to the mac-vlan entry.')NEWLINEvlanMacType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: vlanMacType.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacType.setDescription('The type given to the mac-vlan entry.')NEWLINEvlanMacMapRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 1, 1, 99), RowStatus()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: vlanMacMapRowStatus.setStatus('current')NEWLINEif mibBuilder.loadTexts: vlanMacMapRowStatus.setDescription('The row status of the entry.')NEWLINEmacBasedVlanMethod = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 70, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("single", 1), ("range", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: macBasedVlanMethod.setStatus('current')NEWLINEif mibBuilder.loadTexts: macBasedVlanMethod.setDescription('A method of Vlan-MAC address mapping.')NEWLINEsfpVendorInfoTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1), )NEWLINEif mibBuilder.loadTexts: sfpVendorInfoTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorInfoTable.setDescription('This table indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEsfpVendorInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "sfpPortIndex"))NEWLINEif mibBuilder.loadTexts: sfpVendorInfoEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorInfoEntry.setDescription('A list of information indicates the IP address as a destination to forward (relay) DHCP packets to.')NEWLINEsfpPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpPortIndex.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpPortIndex.setDescription('The available of index for fiber ports.')NEWLINEsfpConnectorType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 2), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpConnectorType.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpConnectorType.setDescription('')NEWLINEsfpTranceiverCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 3), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpTranceiverCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpTranceiverCode.setDescription('')NEWLINEsfpBaudRate = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 4), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpBaudRate.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpBaudRate.setDescription('')NEWLINEsfpVendorName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorName.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorName.setDescription('')NEWLINEsfpVendorOui = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorOui.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorOui.setDescription('')NEWLINEsfpVendorPn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 7), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorPn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorPn.setDescription('')NEWLINEsfpVendorRev = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 8), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorRev.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorRev.setDescription('')NEWLINEsfpWavelength = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 9), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpWavelength.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpWavelength.setDescription('')NEWLINEsfpVendorSn = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 10), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpVendorSn.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpVendorSn.setDescription('')NEWLINEsfpDateCode = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 104, 1, 1, 11), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: sfpDateCode.setStatus('current')NEWLINEif mibBuilder.loadTexts: sfpDateCode.setDescription('')NEWLINEddmCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1))NEWLINEddmInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2))NEWLINEddmPowerUnit = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("mw", 0), ("dbm", 1))).clone('mw')).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmPowerUnit.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmPowerUnit.setDescription('This object indicates the TX/RX power global unit.')NEWLINEddmActionMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2), )NEWLINEif mibBuilder.loadTexts: ddmActionMgmtTable.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionMgmtTable.setDescription('This table contains the configuration of the action taken when any parameter exceeds its threshold.')NEWLINEddmActionMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmActionPort"))NEWLINEif mibBuilder.loadTexts: ddmActionMgmtEntry.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionMgmtEntry.setDescription('This is an entry of the swDdmConfigActionTable.')NEWLINEddmActionPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmActionPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmActionPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmActionState = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmActionState.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionState.setDescription('This object indicates the action type.')NEWLINEddmActionShutdown = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("alarm", 1), ("warning", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmActionShutdown.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ddmActionShutdown.setDescription('This object indicates the action type.')NEWLINEddmThresholdMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3), )NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtTable.setDescription('This table contains DDM temperature configuration information.')NEWLINEddmThresholdMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmThresholdPort"), (0, "DES-1210-28MEbx", "ddmThresholdType"))NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdMgmtEntry.setDescription('This is an entry of the swDdmConfigThresholdTable.')NEWLINEddmThresholdPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmThresholdPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmThresholdType = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("temperature", 0), ("voltage", 1), ("bias", 2), ("txPower", 3), ("rxPower", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmThresholdType.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmThresholdType.setDescription('This object indicates the threshold type.')NEWLINEddmHighAlarm = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 3), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmHighAlarm.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmHighAlarm.setDescription('This object indicates the high alarm threshold value to be configured. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmLowAlarm = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 4), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmLowAlarm.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmLowAlarm.setDescription('This object indicates the low alarm threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmHighWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 5), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmHighWarning.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmHighWarning.setDescription('This object indicates the high warning threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmLowWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 1, 3, 1, 6), DisplayString()).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ddmLowWarning.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmLowWarning.setDescription('This object indicates the low warning threshold value to be configured. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEddmStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1))NEWLINEddmStatusTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1), )NEWLINEif mibBuilder.loadTexts: ddmStatusTable.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusTable.setDescription('This table contains the DDM status information.')NEWLINEddmStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1), ).setIndexNames((0, "DES-1210-28MEbx", "ddmStatusPort"))NEWLINEif mibBuilder.loadTexts: ddmStatusEntry.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusEntry.setDescription('This is an entry of the ddmStatusTable.')NEWLINEddmStatusPort = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 28))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmStatusPort.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmStatusPort.setDescription('This object indicates the port. The available of index for fiber ports.')NEWLINEddmTemperature = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmTemperature.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmTemperature.setDescription('This object indicates the real time value of the temperature. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmVoltage = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmVoltage.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmVoltage.setDescription('This object indicates the real time value of the supply voltage. As the value value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmBiasCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 4), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmBiasCurrent.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmBiasCurrent.setDescription('This object indicates the real time value of the tx bias.')NEWLINEddmTxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 5), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmTxPower.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmTxPower.setDescription('This object indicates the real time value of the tx power. As the value is a floating point data type, the DisplayString type is used to define this parameter.')NEWLINEddmRxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 105, 2, 1, 1, 1, 6), DisplayString()).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ddmRxPower.setStatus('current')NEWLINEif mibBuilder.loadTexts: ddmRxPower.setDescription('This object indicates the real time value of the rx power. As the value is a floating data type, the DisplayString type is used to define this parameter.')NEWLINEftpFwTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1))NEWLINEftpConfigTable = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2))NEWLINEftpFwServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwServerIpAddress.setDescription("The FTP server's IPv4 address or IPv6 address is used to upload or download firmware.")NEWLINEftpFwImageFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwImageFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwImageFileName.setDescription('Firmware file name used to upload or download firmware.')NEWLINEftpFwUsername = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwUsername.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwUsername.setDescription('FTP username to login FTP.')NEWLINEftpFwPassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPassword.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPassword.setDescription('FTP password to login FTP.')NEWLINEftpFwPath = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPath.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPath.setDescription('FTP path can find file folder.')NEWLINEftpFwPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwPort.setDescription('FTP port to login FTP.')NEWLINEftpFwFTPOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperation.setDescription('The FTP operates to perform downloading the firmware image to the unit. This object is used in conjunction with FTP settings')NEWLINEftpFwFTPOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpFwFTPOperationStatus.setDescription('The FTP operation status represent firmware backup or upgrade status.')NEWLINEftpConfigServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigServerIpAddress.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigServerIpAddress.setDescription("The FTP server's IPv4 address or IPv6 address is used to upload or download firmware.")NEWLINEftpConfigFileName = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigFileName.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFileName.setDescription('Config file name used to upload or download Config.')NEWLINEftpConfigUsername = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigUsername.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigUsername.setDescription('FTP username to login FTP.')NEWLINEftpConfigPassword = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPassword.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPassword.setDescription('FTP password to login FTP.')NEWLINEftpConfigPath = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPath.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPath.setDescription('FTP path can find file folder.')NEWLINEftpConfigPort = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigPort.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigPort.setDescription('FTP port to login FTP.')NEWLINEftpConfigConfigID = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("configID1", 1), ("configID2", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigConfigID.setStatus('current')NEWLINEif mibBuilder.loadTexts: ftpConfigConfigID.setDescription('Config image id can select imageid1 or imageid2 to flash')NEWLINEftpConfigFTPOperation = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("download", 1), ("upload", 2)))).setMaxAccess("readwrite")NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperation.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperation.setDescription('The FTP operates to perform downloading the config image to the unit. This object is used in conjunction with FTP settings')NEWLINEftpConfigFTPOperationStatus = MibScalar((1, 3, 6, 1, 4, 1, 171, 10, 75, 15, 2, 107, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("success", 1), ("fail", 2), ("progressing", 3), ("transmit", 4)))).setMaxAccess("readonly")NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperationStatus.setStatus('obsolete')NEWLINEif mibBuilder.loadTexts: ftpConfigFTPOperationStatus.setDescription('The FTP operation status represent config backup or upgrade status.')NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", swAuthRadiusServerTable=swAuthRadiusServerTable, stpNewRootTrapStatus=stpNewRootTrapStatus, ipv4sysSNTPDSTEndMon=ipv4sysSNTPDSTEndMon, cpuFilterv6L3RuleProfileNo=cpuFilterv6L3RuleProfileNo, iPv4aacServerAuthKey=iPv4aacServerAuthKey, pppoePortRemoteIDType=pppoePortRemoteIDType, ipv4aclProfileEntry=ipv4aclProfileEntry, sysPortErrPortIndex=sysPortErrPortIndex, ipv4aclQosVlanID=ipv4aclQosVlanID, dlinklldpState=dlinklldpState, laPortControl=laPortControl, cpuFilterProfileStatus=cpuFilterProfileStatus, sfpDateCode=sfpDateCode, impbBlockListMacAddress=impbBlockListMacAddress, swAuthUserName=swAuthUserName, companyDHCPv6Relay=companyDHCPv6Relay, aclL3RuleTcpPshBit=aclL3RuleTcpPshBit, lldpXdot3RemLinkAggEntry=lldpXdot3RemLinkAggEntry, portSecFDBPermanentTable=portSecFDBPermanentTable, aacEnableMethodListEntry=aacEnableMethodListEntry, cpuFilterL3RuleSrcIpAddr=cpuFilterL3RuleSrcIpAddr, trafficCtrlTimeInterval=trafficCtrlTimeInterval, companyQoSGroup=companyQoSGroup, cpuFilterL2RuleDstMacAddrMask=cpuFilterL2RuleDstMacAddrMask, mldsHostTable=mldsHostTable, protocolVlanEntry=protocolVlanEntry, swAuthAuthConfigPortControl=swAuthAuthConfigPortControl, errorSymbolWindow=errorSymbolWindow, ipv4aclUdfOffsetBase1=ipv4aclUdfOffsetBase1, mstCistPortEntry=mstCistPortEntry, iPv4swAuthRadiusServerAuthenticationPort=iPv4swAuthRadiusServerAuthenticationPort, OwnerString=OwnerString, staticAutoLearningList=staticAutoLearningList, VlanIndex=VlanIndex, lldpXdot1RemTable=lldpXdot1RemTable, dhcpBOOTPRelayTimeThreshold=dhcpBOOTPRelayTimeThreshold, ipv4trustedHostEntry=ipv4trustedHostEntry, igmpMulticastVlanRowStatus=igmpMulticastVlanRowStatus, aclL2RuleEntry=aclL2RuleEntry, aclL3RuleAction=aclL3RuleAction, aacAccountingMethod1=aacAccountingMethod1, ftpConfigConfigID=ftpConfigConfigID, tftpCfgTargetServerIpAddress=tftpCfgTargetServerIpAddress, igmpMulticastVlanGroupToIp=igmpMulticastVlanGroupToIp, dhcpBOOTPRelayInterface=dhcpBOOTPRelayInterface, lldpXdot3RemMaxFrameSizeTable=lldpXdot3RemMaxFrameSizeTable, sysDhcpAutoConfigTimeout=sysDhcpAutoConfigTimeout, pppoePortEntry=pppoePortEntry, rmonAlarmFallingEventIndex=rmonAlarmFallingEventIndex, snmpV3GroupSecurityModel=snmpV3GroupSecurityModel, rmonAlarmTable=rmonAlarmTable, sshUserInfoID=sshUserInfoID, snmpTrapCopperLinkUpDown=snmpTrapCopperLinkUpDown, snmpV3CommunityEncryption=snmpV3CommunityEncryption, mldsVlanCfgQuerier=mldsVlanCfgQuerier, ipv4cpuFilterProfileMask=ipv4cpuFilterProfileMask, qinqEntry=qinqEntry, aclUdfOffsetMask2=aclUdfOffsetMask2, neighborActiveStatus=neighborActiveStatus, qosDiffServType31=qosDiffServType31, qosUserPriIndex=qosUserPriIndex, ipv4cpuFilterProfileTable=ipv4cpuFilterProfileTable, ipv4aclQosStatus=ipv4aclQosStatus, sysBPDUAttackRecoverTime=sysBPDUAttackRecoverTime, cosBandwidthCtrlSettings=cosBandwidthCtrlSettings, staticVlanBaseAutoLearnList3k=staticVlanBaseAutoLearnList3k, ipv4sysSNTPDSTStartDay=ipv4sysSNTPDSTStartDay, cableDiagPair1Length=cableDiagPair1Length, ipv4syslogServUDPport=ipv4syslogServUDPport, ipv4sysSNTPTimeSeconds=ipv4sysSNTPTimeSeconds, ipv4aclUdfOffsetBase4=ipv4aclUdfOffsetBase4, lldpXdot3RemLinkAggPortId=lldpXdot3RemLinkAggPortId, ftpConfigServerIpAddress=ftpConfigServerIpAddress, autoFdbMacAddress=autoFdbMacAddress, qosPriSettings=qosPriSettings, lldpPortConfigEntry=lldpPortConfigEntry, lldpXdot3RemPortAutoNegEnabled=lldpXdot3RemPortAutoNegEnabled, ipifV6AddressIpType=ipifV6AddressIpType, ipv4aclUdfOffsetByte4=ipv4aclUdfOffsetByte4, aclProfileArpSenderIpAddrMask=aclProfileArpSenderIpAddrMask, swTimeRangeThursday=swTimeRangeThursday, rmonAlarmStatus=rmonAlarmStatus, igmpMulticastVlanName=igmpMulticastVlanName, cpuFilterL3RuleTable=cpuFilterL3RuleTable, rmonStatsStatus=rmonStatsStatus, rmonHistory=rmonHistory, ddmLowWarning=ddmLowWarning, sshPublKeyRSAAdmin=sshPublKeyRSAAdmin, companySNMPV3=companySNMPV3, staticMac=staticMac, aclL3Rule=aclL3Rule, aacAccountingServiceCommand=aacAccountingServiceCommand, trafficCtrlSettings=trafficCtrlSettings, snmpV3GroupTable=snmpV3GroupTable, ipifV6AddressRowStatus=ipifV6AddressRowStatus, rmonEvent=rmonEvent, sysGratuitousARPEntry=sysGratuitousARPEntry, macNotifyCtrlTable=macNotifyCtrlTable, eoamIfIndex=eoamIfIndex, qinqVlanTranslationSVIDOperation=qinqVlanTranslationSVIDOperation, ddmThresholdMgmtTable=ddmThresholdMgmtTable, stpMaxAge=stpMaxAge, aacServerGroupName=aacServerGroupName, ftpFwImageFileName=ftpFwImageFileName, sshSecurityStatus=sshSecurityStatus, snmpV3viewTreeType=snmpV3viewTreeType, sysLBDVlanLoopEntry=sysLBDVlanLoopEntry, dhcpBOOTPRelayOption82CheckState=dhcpBOOTPRelayOption82CheckState, aclv6L3RuleTable=aclv6L3RuleTable, stpBridgeGlobal=stpBridgeGlobal, neighborMACAddr=neighborMACAddr, laStatus=laStatus, dlinklldpMsgHoldMultiplier=dlinklldpMsgHoldMultiplier, aacAPHttpLoginMethod=aacAPHttpLoginMethod, dhcpv6RelayInterfaceSettingsTable=dhcpv6RelayInterfaceSettingsTable, aclFlowMeterEntry=aclFlowMeterEntry, sysPortMediaType=sysPortMediaType, sysPortMediaTypeOui=sysPortMediaTypeOui, dhcpv6RelayOption37State=dhcpv6RelayOption37State, stpTxHoldCount=stpTxHoldCount, sshMaxSession=sshMaxSession, sysSNTPTimeSeconds=sysSNTPTimeSeconds, swAuthAuthQuietPeriod=swAuthAuthQuietPeriod, sshConnectionTimeout=sshConnectionTimeout, ipv4cpuFilterProfileRuleCount=ipv4cpuFilterProfileRuleCount, securitySSL=securitySSL, bandwidthCtrlSettings=bandwidthCtrlSettings, syslogServSrvStatus=syslogServSrvStatus, sysGratuitousARPGlobalSettings=sysGratuitousARPGlobalSettings, ftpConfigTable=ftpConfigTable, cpuFilterProfileDstPortMask=cpuFilterProfileDstPortMask, cpuFilterv6L3RuleTcpSynBit=cpuFilterv6L3RuleTcpSynBit, cpuFilterProfileMask=cpuFilterProfileMask, ipv4cpuFilterProfileSrcPortMask=ipv4cpuFilterProfileSrcPortMask, impbPortDHCPv6VlanList3k=impbPortDHCPv6VlanList3k, aRPSpoofPreventRowStatus=aRPSpoofPreventRowStatus, aacAuthParamResponseTimeout=aacAuthParamResponseTimeout, iPv4aacServerTimeout=iPv4aacServerTimeout, rmonStatistics=rmonStatistics, sysUser=sysUser, multicastVlanTable=multicastVlanTable, sysLBDRecoverTime=sysLBDRecoverTime, aclv6L3RuleRateLimit=aclv6L3RuleRateLimit, companyAuthGroup=companyAuthGroup, aclFlowMeterBurstSize=aclFlowMeterBurstSize, lldpXdot3RemPowerClass=lldpXdot3RemPowerClass, qosDiffServType10=qosDiffServType10, sfpBaudRate=sfpBaudRate, ipv4snmpV3HostTable=ipv4snmpV3HostTable, cpuFilterL3RuleDstIpAddrMask=cpuFilterL3RuleDstIpAddrMask, aclL3RuleFilterTimeRange=aclL3RuleFilterTimeRange, staticVlanBaseAutoLearnList4k=staticVlanBaseAutoLearnList4k, trafficCtrlAutoRecoverTime=trafficCtrlAutoRecoverTime, macNotifyHistorySize=macNotifyHistorySize, sysGratuitousARPIFName=sysGratuitousARPIFName, cpuFilterL3RuleTcpSynBit=cpuFilterL3RuleTcpSynBit, lldpXdot3RemPowerEntry=lldpXdot3RemPowerEntry, gvrpSettingsLeaveAllTime=gvrpSettingsLeaveAllTime, sysSNTPDSTStartMin=sysSNTPDSTStartMin, aclL3RuleTcpFinBit=aclL3RuleTcpFinBit, impbBindingtrapsign=impbBindingtrapsign, cpuFilterProfileSrcPortMask=cpuFilterProfileSrcPortMask, cableDiagLinkStatus=cableDiagLinkStatus, snmpV3viewTreeName=snmpV3viewTreeName, newRootBrgaddress=newRootBrgaddress, qosDiffServType34=qosDiffServType34, igmpMulticastVlanUntaggedSourcePort=igmpMulticastVlanUntaggedSourcePort, ipv4cpuFilterProfileDstIpAddrMask=ipv4cpuFilterProfileDstIpAddrMask, ipv4sysIpAddr=ipv4sysIpAddr, cpuFilterL3RuleIgmpType=cpuFilterL3RuleIgmpType, snmpV3HostAddress=snmpV3HostAddress, macNotifyCtrlIndex=macNotifyCtrlIndex, mldsVlanRouterVlanId=mldsVlanRouterVlanId, swTimeRangeEndYear=swTimeRangeEndYear, qosTOSType02=qosTOSType02, doSCtrlMirrorPort=doSCtrlMirrorPort, lldpXdot3LocPowerMDISupported=lldpXdot3LocPowerMDISupported, cpuFilterL3RuleAction=cpuFilterL3RuleAction, multicastVlanMldReplaceSourceIp=multicastVlanMldReplaceSourceIp, cpuFilterv6L3RuleAction=cpuFilterv6L3RuleAction, sysMirrorCtrlEgressMirroring=sysMirrorCtrlEgressMirroring, sysSNTPFirstInterfaceName=sysSNTPFirstInterfaceName, trustedHostStatus=trustedHostStatus, impbPortDHCPSnoopingState=impbPortDHCPSnoopingState, iPv4swAuthRadiusServerAddress=iPv4swAuthRadiusServerAddress, ipifV6AddressEntry=ipifV6AddressEntry, stpModuleStatus=stpModuleStatus, cpuFilterL3RuleDscp=cpuFilterL3RuleDscp, mldsVlanMulticastGroupTable=mldsVlanMulticastGroupTable, portSecEntry=portSecEntry, baudRateConfiguration=baudRateConfiguration, lldpXdot1LocProtocolIndex=lldpXdot1LocProtocolIndex, cpuFilterProfileDstIpAddrMaskType=cpuFilterProfileDstIpAddrMaskType, ipv4snmpV3HostStatus=ipv4snmpV3HostStatus, tftpCfgTargetTftpOperationStatus=tftpCfgTargetTftpOperationStatus, trafficCtrlActionMode=trafficCtrlActionMode, syslogServFacility=syslogServFacility, cpuFilterProfileType=cpuFilterProfileType, pppoeGlobalState=pppoeGlobalState, qosDiffServType55=qosDiffServType55, aclQosStatus=aclQosStatus, mstCistPort=mstCistPort, staticMcastVlanID=staticMcastVlanID, igsHostTableHostIPAddress=igsHostTableHostIPAddress, aacLoginMethodListRowStatus=aacLoginMethodListRowStatus, sysSNTPDSTStartHour=sysSNTPDSTStartHour, staticARPRowStatus=staticARPRowStatus, sysPortCtrlMediumType=sysPortCtrlMediumType, mstMstiPortTable=mstMstiPortTable, sysLoginTimeoutInterval=sysLoginTimeoutInterval, lldpXdot1RemVlanNameEntry=lldpXdot1RemVlanNameEntry, laPortChannelMode=laPortChannelMode, ipv4cpuFilterProfileEntry=ipv4cpuFilterProfileEntry, aclL2RuleEtherType=aclL2RuleEtherType, aclQosProtocol=aclQosProtocol, cpuFilterL2RuleTable=cpuFilterL2RuleTable, swAuthRadiusServerTimeout=swAuthRadiusServerTimeout, aclL3RuleTcpRstBit=aclL3RuleTcpRstBit, companyL2PT=companyL2PT, duldRecoverTime=duldRecoverTime, trafficCtrlEntry=trafficCtrlEntry, cpuFilterL3RuleDstIpAddr=cpuFilterL3RuleDstIpAddr, smtpServerAddrInterfaceName=smtpServerAddrInterfaceName, aclL3RuleTos=aclL3RuleTos, tftpCfgTargetInterfaceName=tftpCfgTargetInterfaceName, aclPacketRuleOffsetValue2=aclPacketRuleOffsetValue2, lldpXdot3RemPowerPortClass=lldpXdot3RemPowerPortClass, aacAccountingMethodListIndex=aacAccountingMethodListIndex, iPv4swAuthRadiusServerEntry=iPv4swAuthRadiusServerEntry, aclProfileTable=aclProfileTable, qosTOSType01=qosTOSType01, aacServersInGroup=aacServersInGroup, ipv4aclUdfOffsetMask2=ipv4aclUdfOffsetMask2, sysSNTPDSTRepeatStartMin=sysSNTPDSTRepeatStartMin, snmpV3viewTreeSubtree=snmpV3viewTreeSubtree, stpPortPathCost=stpPortPathCost, lldpXdot3RemPowerPairControlable=lldpXdot3RemPowerPairControlable, qosTOSType03=qosTOSType03, PYSNMP_MODULE_ID=des_1210_28mebx, qinqVlanTranslationCVIDEntry=qinqVlanTranslationCVIDEntry, aclUdfOffsetMask4=aclUdfOffsetMask4, aclL3RuleTable=aclL3RuleTable, sfpVendorOui=sfpVendorOui, igsStatus=igsStatus, impbPortState=impbPortState, autoFdbPort=autoFdbPort, ipv4snmpV3HostCommunityName=ipv4snmpV3HostCommunityName, cpuFilterL2Rule1pPriority=cpuFilterL2Rule1pPriority, lldpXdot3RemPortOperMauType=lldpXdot3RemPortOperMauType, ddmActionState=ddmActionState, aclProfileNo=aclProfileNo, lldpXdot1LocProtocolEntry=lldpXdot1LocProtocolEntry, mldsVlanMulticastGroupIpAddress=mldsVlanMulticastGroupIpAddress, protocolGroupId=protocolGroupId)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", qosDiffServType23=qosDiffServType23, aacAPLoginMethod=aacAPLoginMethod, companyIpifGroup=companyIpifGroup, sysSNTPDSTRepeatEndWeek=sysSNTPDSTRepeatEndWeek, igsHost=igsHost, eoamEntry=eoamEntry, sshCipherSuiteList=sshCipherSuiteList, ddmActionShutdown=ddmActionShutdown, cosBandwidthEffectiveTX=cosBandwidthEffectiveTX, dhcpv6RelayManagement=dhcpv6RelayManagement, rmonEventStatus=rmonEventStatus, snmpV3GroupStatus=snmpV3GroupStatus, Ipv6Address=Ipv6Address, aacEnableMethodListRowStatus=aacEnableMethodListRowStatus, sysSNTPDSTMethod=sysSNTPDSTMethod, aacLoginMethod4=aacLoginMethod4, aacServerTimeout=aacServerTimeout, companyTrapSetting=companyTrapSetting, limitIpMulticastProfileID=limitIpMulticastProfileID, ddmThresholdMgmtEntry=ddmThresholdMgmtEntry, qinqRoleState=qinqRoleState, qosDiffServType01=qosDiffServType01, qinqVlanTranslationCVID=qinqVlanTranslationCVID, sshUserInfoEntry=sshUserInfoEntry, dlinklldpMsgTxInterval=dlinklldpMsgTxInterval, sysGratuitousARPIPIfStatusUp=sysGratuitousARPIPIfStatusUp, sysSave=sysSave, sysRestart=sysRestart, dhcpv6RelayOpt38PortID=dhcpv6RelayOpt38PortID, lldpXdot3LocLinkAggPortId=lldpXdot3LocLinkAggPortId, swAuthRadiusServerAddress=swAuthRadiusServerAddress, igsVlanMulticastGroupMacAddress=igsVlanMulticastGroupMacAddress, sysLBDCtrlIndex=sysLBDCtrlIndex, aclPacketRuleOffsetValue3=aclPacketRuleOffsetValue3, aclv6L3RuleDstIpAddr=aclv6L3RuleDstIpAddr, dot1qVlanManagementOnOff=dot1qVlanManagementOnOff, aacAccountingMethod2=aacAccountingMethod2, securityPortSecurity=securityPortSecurity, impbDhcpSnoopingMacAddress=impbDhcpSnoopingMacAddress, lldpXdot1ConfigProtoVlanEntry=lldpXdot1ConfigProtoVlanEntry, bandwidthCtrlEntry=bandwidthCtrlEntry, igsVlanRobustnessValue=igsVlanRobustnessValue, vlanMacType=vlanMacType, snmpV3TrapFirmUpgrade=snmpV3TrapFirmUpgrade, companyGuestVlan=companyGuestVlan, cpuFilterProfileDstMacAddrMask=cpuFilterProfileDstMacAddrMask, cpuFilterL3RuleTcpUdpDstPort=cpuFilterL3RuleTcpUdpDstPort, ipv4cpuFilterProfileStatus=ipv4cpuFilterProfileStatus, swTimeRangeTuesday=swTimeRangeTuesday, cpuFilterv6L3RuleTcpFinBit=cpuFilterv6L3RuleTcpFinBit, sshMacSuiteList=sshMacSuiteList, mstMstiPort=mstMstiPort, cosBandwidthCtrlEntry=cosBandwidthCtrlEntry, swAuthCtrlPktFwdMode=swAuthCtrlPktFwdMode, l2PTPortTable=l2PTPortTable, aclv6L3RuleReplace1P=aclv6L3RuleReplace1P, sysPortCtrlType=sysPortCtrlType, sysLBDMode=sysLBDMode, pppoePortCircuitIDType=pppoePortCircuitIDType, duldTable=duldTable, qosDiffServType37=qosDiffServType37, ipv4sysSNTPGMTMinutes=ipv4sysSNTPGMTMinutes, sysBPDUAttackCtrlEntry=sysBPDUAttackCtrlEntry, aclL3RuleDscp=aclL3RuleDscp, limitIpMulticastIPType=limitIpMulticastIPType, companyAgentBasicInfo=companyAgentBasicInfo, newRootOlddesignatedroot=newRootOlddesignatedroot, bandwidthEffecTxThreshold=bandwidthEffecTxThreshold, sysSNTPFirstServer=sysSNTPFirstServer, igsVlanRouterTable=igsVlanRouterTable, limitIpMulticastEntryIPType=limitIpMulticastEntryIPType, duldState=duldState, aclv6L3RuleReplaceQueue=aclv6L3RuleReplaceQueue, snmpV3Trap=snmpV3Trap, igsVlanQuerierVersionStatus=igsVlanQuerierVersionStatus, ftpConfigPort=ftpConfigPort, multicastVlanUntaggedSourcePort=multicastVlanUntaggedSourcePort, companyMulticastFilter=companyMulticastFilter, sysGratuitousARPTable=sysGratuitousARPTable, sfpVendorRev=sfpVendorRev, aclUdfOffsetByte3=aclUdfOffsetByte3, aclL3RuleProtocolMask=aclL3RuleProtocolMask, vlanMacMapVid=vlanMacMapVid, lldpXdot1ConfigVlanNameTable=lldpXdot1ConfigVlanNameTable, aacServerGroupIndex=aacServerGroupIndex, aclL3RuleTcpUdpSrcPort=aclL3RuleTcpUdpSrcPort, doSCtrlMirrorRxRate=doSCtrlMirrorRxRate, cpuFilterL2RuleVlanId=cpuFilterL2RuleVlanId, aclL3RulePortList=aclL3RulePortList, sysGratuitousARPInterval=sysGratuitousARPInterval, swAuthUserPassword=swAuthUserPassword, aacServerIndex=aacServerIndex, impbBindingListTable=impbBindingListTable, igsVlanMulticastGroupIpAddress=igsVlanMulticastGroupIpAddress, rmonAlarmRisingThreshold=rmonAlarmRisingThreshold, vlanTrunkEntry=vlanTrunkEntry, lldpXdot3LocMaxFrameSizeEntry=lldpXdot3LocMaxFrameSizeEntry, companyStaticMAC=companyStaticMAC, dhcpv6RelayOption38=dhcpv6RelayOption38, impbPortDHCPMaxEntryIPv6=impbPortDHCPMaxEntryIPv6, stpRootCost=stpRootCost, aclL2RuleReplace1P=aclL2RuleReplace1P, aclQosIndex=aclQosIndex, syslogServTable=syslogServTable, lldpXdot1LocTable=lldpXdot1LocTable, sfpWavelength=sfpWavelength, multicastVlanRemapPriority=multicastVlanRemapPriority, trustedHostIPType=trustedHostIPType, trafficCtrlTrap=trafficCtrlTrap, rmonAlarmEntry=rmonAlarmEntry, qosDiffServTypeGroup=qosDiffServTypeGroup, dhcpOption12HostName=dhcpOption12HostName, companyTimeRangeMgmt=companyTimeRangeMgmt, impbBindingtrap=impbBindingtrap, multicastVlanIgmpReplaceSourceIp=multicastVlanIgmpReplaceSourceIp, qinqVlanTranslationCVIDTable=qinqVlanTranslationCVIDTable, qosUserPriorityTable=qosUserPriorityTable, qosDiffServType04=qosDiffServType04, qosAclPrioritySettings=qosAclPrioritySettings, portSecIndex=portSecIndex, iPv4swAuthRadiusServerAccountingPort=iPv4swAuthRadiusServerAccountingPort, aclUdfOffsetBase2=aclUdfOffsetBase2, stpAdminPortPathCost=stpAdminPortPathCost, aclL2RuleVlanId=aclL2RuleVlanId, ipv4sysSNTPDSTState=ipv4sysSNTPDSTState, trafficControl=trafficControl, cpuFilterv6L3RuleTrafficClass=cpuFilterv6L3RuleTrafficClass, tftpCfgTargetTftpOperation=tftpCfgTargetTftpOperation, ddmActionPort=ddmActionPort, qosDiffServType53=qosDiffServType53, cpuFilterL2AccessID=cpuFilterL2AccessID, dhcpBOOTPRelayInterfaceSettingsEntry=dhcpBOOTPRelayInterfaceSettingsEntry, limitIpMulticastPortTable=limitIpMulticastPortTable, aacServerIPType=aacServerIPType, ftpFwFTPOperationStatus=ftpFwFTPOperationStatus, swTimeRangeSettingEntry=swTimeRangeSettingEntry, qosDiffServType51=qosDiffServType51, sysLBDCtrlEntry=sysLBDCtrlEntry, ipifVLANname=ipifVLANname, igmpMulticastVlanGroupVid=igmpMulticastVlanGroupVid, multicastVlanGroupStatus=multicastVlanGroupStatus, ipv4cpuFilterProfileIPProtocol=ipv4cpuFilterProfileIPProtocol, stpInstance=stpInstance, snmpV3GroupEntry=snmpV3GroupEntry, ipv4cpuFilterProfileNo=ipv4cpuFilterProfileNo, sysSNTPDSTStartDay=sysSNTPDSTStartDay, aclUdfOffsetByte1=aclUdfOffsetByte1, dlinklldpTxDelay=dlinklldpTxDelay, qosDiffServType17=qosDiffServType17, lldpXdot1LocProtoVlanEnabled=lldpXdot1LocProtoVlanEnabled, errorFramePeriodWindow=errorFramePeriodWindow, qosDiffServType06=qosDiffServType06, snmpV3Host=snmpV3Host, gvrpSettingsIngressChecking=gvrpSettingsIngressChecking, sysSNTPDSTStartMon=sysSNTPDSTStartMon, sysBPDUAttackCtrlTable=sysBPDUAttackCtrlTable, macNotificatiotn=macNotificatiotn, qosDiffServType57=qosDiffServType57, companyTftpGroup=companyTftpGroup, swAuthRadiusServer=swAuthRadiusServer, rmonHistoryInterval=rmonHistoryInterval, aclv6L3RuleTcpUdpDstPortMask=aclv6L3RuleTcpUdpDstPortMask, dhcpBOOTPRelayState=dhcpBOOTPRelayState, mldsHost=mldsHost, autoFdbVlanID=autoFdbVlanID, impbPortDHCPv4VlanList2k=impbPortDHCPv4VlanList2k, igsVlanRouterVlanId=igsVlanRouterVlanId, eoamLinkMonitorIfIndex=eoamLinkMonitorIfIndex, swAuthAuthDirection=swAuthAuthDirection, qosDSCPTOSMode=qosDSCPTOSMode, companyTraps=companyTraps, securityTrafficSeg=securityTrafficSeg, cpuFilterv6L3RuleICMPMessageType=cpuFilterv6L3RuleICMPMessageType, companyBPDUAttack=companyBPDUAttack, sysPortMediaTypeDateCode=sysPortMediaTypeDateCode, mldsVlanFastLeave=mldsVlanFastLeave, lldpXdot3RemLinkAggTable=lldpXdot3RemLinkAggTable, aacLoginMethodListTable=aacLoginMethodListTable, mcastFilterPortTable=mcastFilterPortTable, companyDHCPRelay=companyDHCPRelay, aclUdfOffsetByte2=aclUdfOffsetByte2, aacServerRowStatus=aacServerRowStatus, mstCistVlanMapped2k=mstCistVlanMapped2k, l2PTPortType=l2PTPortType, rmonHistoryIndex=rmonHistoryIndex, ftpConfigFTPOperation=ftpConfigFTPOperation, limitIpMulticastEntryTable=limitIpMulticastEntryTable, aRPSpoofPreventPortList=aRPSpoofPreventPortList, sysTrapIMPBViolation=sysTrapIMPBViolation, stpTopologyChangeTrapStatus=stpTopologyChangeTrapStatus, impbPortNDInspectionState=impbPortNDInspectionState, qosDiffServType59=qosDiffServType59, lldpXdot1LocProtoVlanTable=lldpXdot1LocProtoVlanTable, staticARPIP=staticARPIP, snmpV3UserName=snmpV3UserName, eoamRemoteLoopback=eoamRemoteLoopback, aclProfileMask=aclProfileMask, vlanTrunkSystem=vlanTrunkSystem, aclProfileRuleCount=aclProfileRuleCount, qosDiffServType60=qosDiffServType60, snmpV3Community=snmpV3Community, rmonEventDescription=rmonEventDescription, mldsVlanFilterTable=mldsVlanFilterTable, cpuFilterL3RuleProtocolMask=cpuFilterL3RuleProtocolMask, snmpGlobalState=snmpGlobalState, cpuFilterProfileSrcMacAddrMask=cpuFilterProfileSrcMacAddrMask, qosDiffServType12=qosDiffServType12, ipv4trustedHostIpAddr=ipv4trustedHostIpAddr, qosDiffServType62=qosDiffServType62, stpProtocolVersion=stpProtocolVersion, snmpTrapIMPBv2=snmpTrapIMPBv2, limitIpMulticastPortIPType=limitIpMulticastPortIPType, ddmLowAlarm=ddmLowAlarm, ipv4syslogServEntry=ipv4syslogServEntry, aacAPSSHEnableMethod=aacAPSSHEnableMethod, sfpPortIndex=sfpPortIndex, sshAuthenMethodHostKeyAdmin=sshAuthenMethodHostKeyAdmin, aclL2RuleFilterTimeRange=aclL2RuleFilterTimeRange, qosDiffServType38=qosDiffServType38, mldsVlanRouterEntry=mldsVlanRouterEntry, cpuFilterL3RuleICMPMessageCode=cpuFilterL3RuleICMPMessageCode, duplicateIP=duplicateIP, cpuFilterProfile=cpuFilterProfile, companySTP=companySTP, igsVlanQueryMaxResponseTime=igsVlanQueryMaxResponseTime, qosPriSetPortType=qosPriSetPortType, snmpV3CommunityPolicy=snmpV3CommunityPolicy, lldpXdot1RemProtocolIndex=lldpXdot1RemProtocolIndex, mldsVlanRouterTable=mldsVlanRouterTable, gvrpSettingsGVRPState=gvrpSettingsGVRPState, snmpV3UserPrivProtocol=snmpV3UserPrivProtocol, sysBootupConfigID=sysBootupConfigID, swTimeRangeStartDay=swTimeRangeStartDay, agentMEMutilizationIn5min=agentMEMutilizationIn5min, mldsVlanDataDrivenLearningStatus=mldsVlanDataDrivenLearningStatus, qosDiffServType32=qosDiffServType32, companySfpVendorInfo=companySfpVendorInfo, aacEnableMethod3=aacEnableMethod3, eoamTable=eoamTable, aclv6L3RulePortList=aclv6L3RulePortList, swTimeRangeFriday=swTimeRangeFriday, igsVlanRtrPortList=igsVlanRtrPortList, swAuthRadiusServerInterfaceName=swAuthRadiusServerInterfaceName, pppoePortCircuitIDVendor3String=pppoePortCircuitIDVendor3String, mcastFilterPortEntry=mcastFilterPortEntry, aclL2RuleSrcMacAddrMask=aclL2RuleSrcMacAddrMask, snmpV3TrapDuplicateIPDetected=snmpV3TrapDuplicateIPDetected, companyNeighbor=companyNeighbor, cosClassEntry=cosClassEntry, qosUserPriEntry=qosUserPriEntry, aclL3RuleTcpUrgBit=aclL3RuleTcpUrgBit, aacAccountingServiceCommandOperator=aacAccountingServiceCommandOperator, staticMcastEntry=staticMcastEntry, snmpTrapSNMPAuthentication=snmpTrapSNMPAuthentication)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3Rule=cpuFilterL3Rule, impbLogState=impbLogState, mldsVlanReportSuppression=mldsVlanReportSuppression, aclL3RuleTcpUdpDstPortMask=aclL3RuleTcpUdpDstPortMask, ipv4aclProfileDstMacAddrMask=ipv4aclProfileDstMacAddrMask, sysSNTPDSTRepeatStartMon=sysSNTPDSTRepeatStartMon, trustedHostTable=trustedHostTable, staticVlanBaseDisableAutoLearn=staticVlanBaseDisableAutoLearn, cpuFilterL2RuleSrcMacAddrMask=cpuFilterL2RuleSrcMacAddrMask, aclL2RuleDstMacAddrMask=aclL2RuleDstMacAddrMask, aacLoginMethod1=aacLoginMethod1, companyProtocolVlan=companyProtocolVlan, snmpV3TrapLinkUpDown=snmpV3TrapLinkUpDown, sshSessionKeyRekeying=sshSessionKeyRekeying, tftpCfgTargetGroup=tftpCfgTargetGroup, ftpConfigFileName=ftpConfigFileName, stpPortState=stpPortState, cableDiagPair1Status=cableDiagPair1Status, ipv4cpuFilterProfileSrcIpAddrMask=ipv4cpuFilterProfileSrcIpAddrMask, qosDiffServType03=qosDiffServType03, rmonEventTable=rmonEventTable, igsVlanFilterTable=igsVlanFilterTable, aacAccountingServiceShell=aacAccountingServiceShell, limitIpMulticastendIpAddr=limitIpMulticastendIpAddr, lldpXdot3PortConfigEntry=lldpXdot3PortConfigEntry, dhcpv6RelayServerIP=dhcpv6RelayServerIP, pppoePortRemoteIDVendor3String=pppoePortRemoteIDVendor3String, swAuthUser=swAuthUser, sysSerialNumber=sysSerialNumber, qosDiffServType22=qosDiffServType22, swTimeRangeStartHour=swTimeRangeStartHour, sysLBDCtrlTable=sysLBDCtrlTable, mstMstiForcePortState=mstMstiForcePortState, qosDiffServType02=qosDiffServType02, qosDiffServType00=qosDiffServType00, snmpV3TrapIMPBViolation=snmpV3TrapIMPBViolation, impbPortDHCPv6VlanList2k=impbPortDHCPv6VlanList2k, ipv4sysSNTPSecondServer=ipv4sysSNTPSecondServer, swAuthAuthReAuthPeriod=swAuthAuthReAuthPeriod, swAuthRadiusServerStatus=swAuthRadiusServerStatus, impbBlockListPort=impbBlockListPort, impbBlockListEntry=impbBlockListEntry, rmonGlobalState=rmonGlobalState, protocolVlanGroupID=protocolVlanGroupID, syslogServSrvRowStatus=syslogServSrvRowStatus, ipv4cpuFilterProfileSrcMacAddrMask=ipv4cpuFilterProfileSrcMacAddrMask, snmpV3GroupSecurityLevel=snmpV3GroupSecurityLevel, staticARPEntry=staticARPEntry, errorFramePeriodNotifyState=errorFramePeriodNotifyState, stpPortProtocolMigration=stpPortProtocolMigration, sysWebPortNumber=sysWebPortNumber, ftpFwPassword=ftpFwPassword, aacAPTelnetEnableMethod=aacAPTelnetEnableMethod, guestVlanPort=guestVlanPort, sysMACAgingTime=sysMACAgingTime, ipv4aclProfileDstIpAddrMask=ipv4aclProfileDstIpAddrMask, sysLBDInterval=sysLBDInterval, dhcpv6RelayHopCount=dhcpv6RelayHopCount, stpNewRootTraps=stpNewRootTraps, sysGateway=sysGateway, ipifv6DHCPStatus=ipifv6DHCPStatus, igmpMulticastVlanReplacePriority=igmpMulticastVlanReplacePriority, swTimeRangeName=swTimeRangeName, sshUserInfoTable=sshUserInfoTable, staticMcastMac=staticMcastMac, doSCtrlClearFrameCount=doSCtrlClearFrameCount, protocolGroupNameEntry=protocolGroupNameEntry, neighborIPv6Addr=neighborIPv6Addr, agentCPUutilizationIn5min=agentCPUutilizationIn5min, rmonAlarmIndex=rmonAlarmIndex, qosDiffServType35=qosDiffServType35, smtpRecvMailAddrStatus=smtpRecvMailAddrStatus, dhcpServerScreenEnablePortlist=dhcpServerScreenEnablePortlist, limitIpMulticastPortProfileID=limitIpMulticastPortProfileID, impbAutoScanStatus=impbAutoScanStatus, aclL2RuleDstMacAddr=aclL2RuleDstMacAddr, smtpServerAddr=smtpServerAddr, trafficCtrlTable=trafficCtrlTable, authProtocol=authProtocol, igsVlanQueryInterval=igsVlanQueryInterval, igmpMulticastVlanGroupFromIp=igmpMulticastVlanGroupFromIp, rmonHistoryTable=rmonHistoryTable, sysPortDescIndex=sysPortDescIndex, cosWeight=cosWeight, staticMcastTable=staticMcastTable, macBasedVlanTable=macBasedVlanTable, aclv6L3RuleTcpUrgBit=aclv6L3RuleTcpUrgBit, dlinklldpReinitDelay=dlinklldpReinitDelay, impbAutoScanPort=impbAutoScanPort, lldpXdot3LocPowerPortClass=lldpXdot3LocPowerPortClass, aclPacketRuleStatus=aclPacketRuleStatus, sysContactName=sysContactName, lldpXdot1ConfigPortVlanEntry=lldpXdot1ConfigPortVlanEntry, floodfdbOnOff=floodfdbOnOff, eoamDyingGaspEnable=eoamDyingGaspEnable, cableDiagPortIndex=cableDiagPortIndex, impbVlanModeState=impbVlanModeState, snmpV3HostStatus=snmpV3HostStatus, tftpFwTargetTftpOperationStatus=tftpFwTargetTftpOperationStatus, lldpXdot3RemLinkAggStatus=lldpXdot3RemLinkAggStatus, duldMode=duldMode, ipv4aclProfileMask=ipv4aclProfileMask, ipv4cpuFilterProfileDstPortMask=ipv4cpuFilterProfileDstPortMask, vlanTrunkIfIndex=vlanTrunkIfIndex, staticEntry=staticEntry, ftpFwServerIpAddress=ftpFwServerIpAddress, portSecTable=portSecTable, aclv6L3RuleStatus=aclv6L3RuleStatus, igsVlanSnoopStatus=igsVlanSnoopStatus, aclL3RuleTcpUdpDstPort=aclL3RuleTcpUdpDstPort, aclL2ProfileID=aclL2ProfileID, autologoutConfiguration=autologoutConfiguration, portSecLockAddrMode=portSecLockAddrMode, sysPortMediaTypeEntry=sysPortMediaTypeEntry, l2PTThresholdEntry=l2PTThresholdEntry, mldsHostTablePort=mldsHostTablePort, stpPort=stpPort, aacLocalEnablePassword=aacLocalEnablePassword, swAuthAuthConfigPortNumber=swAuthAuthConfigPortNumber, mstInstanceIndex=mstInstanceIndex, mldsHostTableVLANID=mldsHostTableVLANID, aclQosIP6TC=aclQosIP6TC, l2PTState=l2PTState, ipv4trustedHostTable=ipv4trustedHostTable, portSecMLA=portSecMLA, swAuthRadiusServerRetransmit=swAuthRadiusServerRetransmit, mldsVlanQuerier=mldsVlanQuerier, mstCistPortDesignatedBridge=mstCistPortDesignatedBridge, aacServerInfoTable=aacServerInfoTable, swAuthPortAccessControlEntry=swAuthPortAccessControlEntry, sysPortMediaTypeIndex=sysPortMediaTypeIndex, aacLoginMethodListName=aacLoginMethodListName, dhcpBOOTPRelayOption82CircuitIDType=dhcpBOOTPRelayOption82CircuitIDType, ipv4aclProfileDstPortMask=ipv4aclProfileDstPortMask, qosDiffServType16=qosDiffServType16, aclFlowMeterAction=aclFlowMeterAction, stpFowardBPDU=stpFowardBPDU, trustedHostIpMask=trustedHostIpMask, aacServerAuthKey=aacServerAuthKey, cableDiagPair4Status=cableDiagPair4Status, mstCistPortPathCost=mstCistPortPathCost, ipv4sysSNTPDSTStartHour=ipv4sysSNTPDSTStartHour, portSecFDBPermIndex=portSecFDBPermIndex, ipv4aclProfileIPProtocolMask=ipv4aclProfileIPProtocolMask, lldpXdot1Objects=lldpXdot1Objects, mstCistCurrentPortRole=mstCistCurrentPortRole, smtpState=smtpState, igsVlanDataDrivenLearningStatus=igsVlanDataDrivenLearningStatus, syslogServUDPport=syslogServUDPport, swTimeRangeStartMonth=swTimeRangeStartMonth, rmonAlarmFallingThreshold=rmonAlarmFallingThreshold, aclProfileDstMacAddrMask=aclProfileDstMacAddrMask, impbPortAllowZeroIPState=impbPortAllowZeroIPState, cpuFilterL3RuleEntry=cpuFilterL3RuleEntry, ipv4aclUdfOffsetMask1=ipv4aclUdfOffsetMask1, staticVlanBaseAutoLearnList1k=staticVlanBaseAutoLearnList1k, mstInstanceVlanMapped=mstInstanceVlanMapped, ipv4syslogServFacility=ipv4syslogServFacility, aclPacketProfileID=aclPacketProfileID, qosDiffServType20=qosDiffServType20, sshMaxAuthFailAttempts=sshMaxAuthFailAttempts, aacEnableMethod2=aacEnableMethod2, sysMirrorCtrlIngressMirroring=sysMirrorCtrlIngressMirroring, rmonAlarmSampleType=rmonAlarmSampleType, multicastVlanGroupIpType=multicastVlanGroupIpType, sysBPDUAttackPortMode=sysBPDUAttackPortMode, sysPortCtrlTable=sysPortCtrlTable, snmpV3UserEntry=snmpV3UserEntry, sysSNTPDSTRepeatEndMon=sysSNTPDSTRepeatEndMon, tftpCfgTargetTftpIncrement=tftpCfgTargetTftpIncrement, mstMstiPortPathCost=mstMstiPortPathCost, aclFlowMeterRule=aclFlowMeterRule, cpuFilterL2Rule=cpuFilterL2Rule, securityIpMacPortBinding=securityIpMacPortBinding, sysSNTPSecondInterfaceName=sysSNTPSecondInterfaceName, smtpSelfMailAddr=smtpSelfMailAddr, snmpV3Group=snmpV3Group, mstMstiPortAdminPathCost=mstMstiPortAdminPathCost, cosBandwidthEffectiveRX=cosBandwidthEffectiveRX, dot1qVlanPVIDAutoAssignOnOff=dot1qVlanPVIDAutoAssignOnOff, mstCistVlanMapped3k=mstCistVlanMapped3k, vlanTrunkState=vlanTrunkState, swAuthAuthMaxReq=swAuthAuthMaxReq, dhcpLocalRelayTable=dhcpLocalRelayTable, aclv6L3RuleTrafficClass=aclv6L3RuleTrafficClass, ftpConfigFTPOperationStatus=ftpConfigFTPOperationStatus, limitIpMulticastPortMaxGrp=limitIpMulticastPortMaxGrp, impbPortIpInspectionState=impbPortIpInspectionState, ftpFwPort=ftpFwPort, aclv6L3RuleSrcIpAddr=aclv6L3RuleSrcIpAddr, ddmThresholdPort=ddmThresholdPort, igmpMulticastVlanEntry=igmpMulticastVlanEntry, companyFTPGroup=companyFTPGroup, aclL2RuleVlanIdMask=aclL2RuleVlanIdMask, companyStaticARP=companyStaticARP, tftpCfgTargetTftpConfigID=tftpCfgTargetTftpConfigID, igsVlanFilterVlanId=igsVlanFilterVlanId, sysLBDVlanLoopTable=sysLBDVlanLoopTable, sysDhcpAutoImage=sysDhcpAutoImage, sysTrapStatus=sysTrapStatus, mldsVlanMulticastGroupMacAddress=mldsVlanMulticastGroupMacAddress, sysPortCtrlOperStatus=sysPortCtrlOperStatus, dhcpBOOTPRelayOption82RemoteIDType=dhcpBOOTPRelayOption82RemoteIDType, LldpManAddress=LldpManAddress, ddmHighWarning=ddmHighWarning, gvrpSettingsAcceptableFrameType=gvrpSettingsAcceptableFrameType, ddmActionMgmtTable=ddmActionMgmtTable, qosDiffServType50=qosDiffServType50, lldpXdot3RemPowerMDISupported=lldpXdot3RemPowerMDISupported, protocolVlanTable=protocolVlanTable, snmpV3UserStatus=snmpV3UserStatus, lldpXdot1LocVlanNameEntry=lldpXdot1LocVlanNameEntry, sysSNTPDSTEndDay=sysSNTPDSTEndDay, aclL2Rule1pPriority=aclL2Rule1pPriority, stpBridgeMaxAge=stpBridgeMaxAge, aclL2AccessID=aclL2AccessID, gvrpSettingsPVID=gvrpSettingsPVID, staticVlanID=staticVlanID, ipv4sysSNTPDSTEndHour=ipv4sysSNTPDSTEndHour, aacAccountingMethodListRowStatus=aacAccountingMethodListRowStatus, cpuFilterL2RuleEtherType=cpuFilterL2RuleEtherType, ipv4smtpRecvMailAddrStatus=ipv4smtpRecvMailAddrStatus, impbAutoScanMacAddress=impbAutoScanMacAddress, lldpXdot1ConfigPortVlanTxEnable=lldpXdot1ConfigPortVlanTxEnable, impbPortDHCPMaxEntryIPv4=impbPortDHCPMaxEntryIPv4, ipv4syslogServSrvRowStatus=ipv4syslogServSrvRowStatus, mstConfigurationIdentification=mstConfigurationIdentification, tftpCfgTargetImageFileName=tftpCfgTargetImageFileName, oldDesignatedRoot=oldDesignatedRoot, dhcpBOOTPRelayOption82Policy=dhcpBOOTPRelayOption82Policy, mstCistVlanMapped=mstCistVlanMapped, swAuthAuthTxPeriod=swAuthAuthTxPeriod, aacAccountingServiceCommandAdministrator=aacAccountingServiceCommandAdministrator, sfpVendorName=sfpVendorName, aclUdfOffsetByte4=aclUdfOffsetByte4, iPv4swAuthRadiusServerKey=iPv4swAuthRadiusServerKey, snmpV3ViewTreeTable=snmpV3ViewTreeTable, cpuFilterL3RuleAccessID=cpuFilterL3RuleAccessID, filterDHCPServerVlanList=filterDHCPServerVlanList, impbAutoScanIpAddressFrom=impbAutoScanIpAddressFrom, laPortControlTable=laPortControlTable, dhcpBOOTPRelayOption82State=dhcpBOOTPRelayOption82State, aclv6L3RuleProtocol=aclv6L3RuleProtocol, sysSNTPSecondServer=sysSNTPSecondServer, dhcpv6RelayInterfaceSettingsRowStatus=dhcpv6RelayInterfaceSettingsRowStatus, mldsVlanQueryInterval=mldsVlanQueryInterval, stpBridgeForwardDelay=stpBridgeForwardDelay, mldsVlanFilterVlanId=mldsVlanFilterVlanId, companyTrafficMgmt=companyTrafficMgmt, ipv4snmpV3HostAddress=ipv4snmpV3HostAddress, sysBPDUAttackPortState=sysBPDUAttackPortState, des_1210_28mebx=des_1210_28mebx, sysPortMediaTypePn=sysPortMediaTypePn, aacServerInterfaceName=aacServerInterfaceName)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", laPortChannelTable=laPortChannelTable, mldsVlanMulticastGroupPortList=mldsVlanMulticastGroupPortList, rmonHistoryOwner=rmonHistoryOwner, sysBPDUAttackLog=sysBPDUAttackLog, aacAPConsoleEnableMethod=aacAPConsoleEnableMethod, multicastVlanMemberPort=multicastVlanMemberPort, cableDiagPair2Length=cableDiagPair2Length, qosEffectiveDefaultPriority=qosEffectiveDefaultPriority, ipv4aclQosTCPUDPPort=ipv4aclQosTCPUDPPort, sysPortCtrlSpeed=sysPortCtrlSpeed, igmpMulticastVlanTagMemberPort=igmpMulticastVlanTagMemberPort, ddmPowerUnit=ddmPowerUnit, sysTrapDHCPServerScreening=sysTrapDHCPServerScreening, ipv4syslogServIndex=ipv4syslogServIndex, lldpXdot3RemPowerPairs=lldpXdot3RemPowerPairs, igsVlanMulticastGroupEntry=igsVlanMulticastGroupEntry, aclProfileSrcIpAddrMaskType=aclProfileSrcIpAddrMaskType, cpuFilterv6L3RuleStatus=cpuFilterv6L3RuleStatus, lldpXdot3LocLinkAggEntry=lldpXdot3LocLinkAggEntry, qosDiffServType05=qosDiffServType05, dhcpServerScreenLogSuppressDuration=dhcpServerScreenLogSuppressDuration, dhcpv6RelayOption37RemoteID=dhcpv6RelayOption37RemoteID, sysBPDUAttackCtrlIndex=sysBPDUAttackCtrlIndex, lldpXdot3Config=lldpXdot3Config, iPv4aacServerInfoEntry=iPv4aacServerInfoEntry, mldsVlanQueryMaxResponseTime=mldsVlanQueryMaxResponseTime, aclL3RuleICMPMessageCode=aclL3RuleICMPMessageCode, staticARPTable=staticARPTable, LldpPortNumber=LldpPortNumber, lldpXdot1RemoteData=lldpXdot1RemoteData, mstiRevisionLevel=mstiRevisionLevel, sslCipherSuiteList=sslCipherSuiteList, sysTrapIP=sysTrapIP, cpuFilterv6L3RuleTable=cpuFilterv6L3RuleTable, cosBandwidthCtrlClassIndex=cosBandwidthCtrlClassIndex, mldsVlanSnoopStatus=mldsVlanSnoopStatus, aclPacketRuleTable=aclPacketRuleTable, protocolGroupTable=protocolGroupTable, stpPortFowardBPDU=stpPortFowardBPDU, cpuFilterProfileIPProtocol=cpuFilterProfileIPProtocol, ipv4aclQosMACAddr=ipv4aclQosMACAddr, sslSecurityHttpStatus=sslSecurityHttpStatus, aclL3RuleReplaceDSCP=aclL3RuleReplaceDSCP, snmpV3viewTreeStatus=snmpV3viewTreeStatus, protocolGroupGID=protocolGroupGID, snmpV3GroupWriteViewName=snmpV3GroupWriteViewName, aacServerAuthProtocol=aacServerAuthProtocol, dhcpLocalRelaySettingsState=dhcpLocalRelaySettingsState, dhcpBOOTPRelayControl=dhcpBOOTPRelayControl, cableDiagAction=cableDiagAction, aacServerInfoEntry=aacServerInfoEntry, neighborTable=neighborTable, eoamLinkMonitor=eoamLinkMonitor, ipv4aclUdfOffsetMask3=ipv4aclUdfOffsetMask3, qosDiffServType25=qosDiffServType25, securityDhcpServerScreen=securityDhcpServerScreen, sfpVendorInfoEntry=sfpVendorInfoEntry, multicastVlanReplacePriority=multicastVlanReplacePriority, ipv4sysSNTPFirstServer=ipv4sysSNTPFirstServer, sshUserInfoUserName=sshUserInfoUserName, mstCistForcePortState=mstCistForcePortState, dhcpBOOTPRelayOption82RemoteID=dhcpBOOTPRelayOption82RemoteID, ipv4sysIpAddrCfgMode=ipv4sysIpAddrCfgMode, aclProfileSrcPortMask=aclProfileSrcPortMask, cpuFilterL3RuleTcpRstBit=cpuFilterL3RuleTcpRstBit, mcastFilterPortIndex=mcastFilterPortIndex, cpuFilterL2RuleStatus=cpuFilterL2RuleStatus, mcastFilterPortType=mcastFilterPortType, impbAutoScanVlanId=impbAutoScanVlanId, impbAutoScanCurrentStatus=impbAutoScanCurrentStatus, qosDiffServType45=qosDiffServType45, cosBandwidthValue=cosBandwidthValue, lldpXdot3LocPortOperMauType=lldpXdot3LocPortOperMauType, mldsRouterPortPurgeInterval=mldsRouterPortPurgeInterval, aacLoginMethodListEntry=aacLoginMethodListEntry, ftpFwPath=ftpFwPath, tftpCfgServerIpAddress=tftpCfgServerIpAddress, staticVlanBaseAutoLearnList2k=staticVlanBaseAutoLearnList2k, aclL3RuleReplaceQueue=aclL3RuleReplaceQueue, companyLLDPSetting=companyLLDPSetting, laPortActorTimeout=laPortActorTimeout, iPv4aacServerIndex=iPv4aacServerIndex, cpuFilterL3RuleStatus=cpuFilterL3RuleStatus, snmpV3UserGroupName=snmpV3UserGroupName, aclProfile=aclProfile, snmpV3TrapRSTPStateChange=snmpV3TrapRSTPStateChange, rmonStatsTable=rmonStatsTable, swAuthRadiusServerIndex=swAuthRadiusServerIndex, lldpXdot1RemProtoVlanEntry=lldpXdot1RemProtoVlanEntry, aacEnableMethod4=aacEnableMethod4, cpuFilterL3RuleTcpUdpSrcPortMask=cpuFilterL3RuleTcpUdpSrcPortMask, autoFdbIPAddress=autoFdbIPAddress, qosDefaultUserPriEntry=qosDefaultUserPriEntry, limitIpMulticastProfileStatus=limitIpMulticastProfileStatus, aclL2RuleInPortList=aclL2RuleInPortList, lldpXdot1RemProtoVlanId=lldpXdot1RemProtoVlanId, lldpXdot1RemProtocolTable=lldpXdot1RemProtocolTable, macBasedVlanEntry=macBasedVlanEntry, newRootMSTibridgeregionalroot=newRootMSTibridgeregionalroot, dhcpv6RelayInterface=dhcpv6RelayInterface, aclFlowMeterStatus=aclFlowMeterStatus, ipv4smtpRecvMailAddrIndex=ipv4smtpRecvMailAddrIndex, sysPortDescMediumType=sysPortDescMediumType, mstInstanceVlanMapped2k=mstInstanceVlanMapped2k, swAuthUserTable=swAuthUserTable, sysFirmwareVersion=sysFirmwareVersion, aclQosAssignClass=aclQosAssignClass, swTimeRangeEndMonth=swTimeRangeEndMonth, tftpConfigTftpOperation=tftpConfigTftpOperation, mstCistPortAdminPathCost=mstCistPortAdminPathCost, ddmTxPower=ddmTxPower, miscReset=miscReset, companyDuld=companyDuld, lldpPortConfigTLVsTxEnable=lldpPortConfigTLVsTxEnable, aacAPConsoleLoginMethod=aacAPConsoleLoginMethod, sysPortUpLinkTime=sysPortUpLinkTime, aacEnableMethodListTable=aacEnableMethodListTable, duldSystem=duldSystem, syslogEnable=syslogEnable, sysPortErrTable=sysPortErrTable, cableDiagPair4Length=cableDiagPair4Length, ipv4sysIpSubnetMask=ipv4sysIpSubnetMask, swAuthAuthCapability=swAuthAuthCapability, companyMiscGroup=companyMiscGroup, telnetUDPPort=telnetUDPPort, qosDiffServType63=qosDiffServType63, qosDiffServType28=qosDiffServType28, lldpXdot1RemProtoVlanEnabled=lldpXdot1RemProtoVlanEnabled, igsHostTablePort=igsHostTablePort, qosDiffServType07=qosDiffServType07, cosBandwidthCtrlPortIndex=cosBandwidthCtrlPortIndex, lldpXdot1ConfigProtocolTxEnable=lldpXdot1ConfigProtocolTxEnable, telnetsettingManagementOnOff=telnetsettingManagementOnOff, rmonEventIndex=rmonEventIndex, rmonStatsDataSource=rmonStatsDataSource, companySecurity=companySecurity, mstSetVlanList=mstSetVlanList, sshAuthenMethodPassWordAdmin=sshAuthenMethodPassWordAdmin, snmpV3TrapBPDUAttack=snmpV3TrapBPDUAttack, sfpTranceiverCode=sfpTranceiverCode, swAuthMode=swAuthMode, dhcpServerScreenEnableVlanlist=dhcpServerScreenEnableVlanlist, staticMcastEgressPorts=staticMcastEgressPorts, qosDiffServType15=qosDiffServType15, igsVlanRouterEntry=igsVlanRouterEntry, dhcpv6RelayOption18CheckState=dhcpv6RelayOption18CheckState, aclL2RuleReplaceDSCP=aclL2RuleReplaceDSCP, igmpMulticastVlanTable=igmpMulticastVlanTable, lldpXdot1LocPortVlanId=lldpXdot1LocPortVlanId, ipv4smtpRecvMailAddrEntry=ipv4smtpRecvMailAddrEntry, ipv4syslogServTable=ipv4syslogServTable, doSCtrlMirrorReplace1P=doSCtrlMirrorReplace1P, limitIpMulticastProfileEntry=limitIpMulticastProfileEntry, sysIpAddr=sysIpAddr, ipv4cpuFilterProfileIPProtocolMask=ipv4cpuFilterProfileIPProtocolMask, cpuFilterL3RuleTcpUdpDstPortMask=cpuFilterL3RuleTcpUdpDstPortMask, cpuFilterL2RuleSrcMacAddr=cpuFilterL2RuleSrcMacAddr, mstMstiPortPriority=mstMstiPortPriority, aclFlowMeterProfileID=aclFlowMeterProfileID, qosTOSType04=qosTOSType04, rmonAlarmInterval=rmonAlarmInterval, aclUdfOffsetMask1=aclUdfOffsetMask1, rmonAlarmRisingEventIndex=rmonAlarmRisingEventIndex, snmpV3HostVersion=snmpV3HostVersion, eoamLinkMonitorEntry=eoamLinkMonitorEntry, dhcpLocalRelayEnablePortlist=dhcpLocalRelayEnablePortlist, swAuthRadiusServerKey=swAuthRadiusServerKey, staticTable=staticTable, companySyslog=companySyslog, qosDiffServType36=qosDiffServType36, sysSNTPDSTRepeatStartWeek=sysSNTPDSTRepeatStartWeek, aclv6L3RuleProfileNo=aclv6L3RuleProfileNo, cpuFilterv6L3RuleICMPMessageCode=cpuFilterv6L3RuleICMPMessageCode, cableDiagPair3Status=cableDiagPair3Status, aclPacketRuleOffsetValue2Mask=aclPacketRuleOffsetValue2Mask, tftpConfigFileName=tftpConfigFileName, dot1qVlanForbiddenPorts=dot1qVlanForbiddenPorts, multicastVlanSourcePort=multicastVlanSourcePort, stpBridgePriority=stpBridgePriority, sysJumboFrameEnable=sysJumboFrameEnable, ipv4sysSNTPDSTStartMon=ipv4sysSNTPDSTStartMon, lldpXdot3LocPortAutoNegSupported=lldpXdot3LocPortAutoNegSupported, dhcpv6RelayOpt38PortIndex=dhcpv6RelayOpt38PortIndex, trustedHostRowStatus=trustedHostRowStatus, syslogServInterfaceName=syslogServInterfaceName, limitIpMulticastPortState=limitIpMulticastPortState, companySMTP=companySMTP, portSecFDBPermanentEntry=portSecFDBPermanentEntry, neighborEntry=neighborEntry, cpuFilterv6L3RuleTcpUdpDstPort=cpuFilterv6L3RuleTcpUdpDstPort, lldpXdot3LocPortEntry=lldpXdot3LocPortEntry, mldsHostEntry=mldsHostEntry, igsHostPortPurgeInterval=igsHostPortPurgeInterval, snmpV3TrapPortSecurity=snmpV3TrapPortSecurity, sysPortErrPortState=sysPortErrPortState, lldpXdot1RemVlanNameTable=lldpXdot1RemVlanNameTable, dhcpBOOTPRelayHopCount=dhcpBOOTPRelayHopCount, impbBlockListVlanId=impbBlockListVlanId, ddmActionMgmtEntry=ddmActionMgmtEntry, stpPortHelloTime=stpPortHelloTime, RmonStatus=RmonStatus, cpuFilterL3RuleProfileNo=cpuFilterL3RuleProfileNo, ddmRxPower=ddmRxPower, ipv4aclQosTable=ipv4aclQosTable, cpuFilterv6L3RuleTcpUdpSrcPortMask=cpuFilterv6L3RuleTcpUdpSrcPortMask, ddmCtrl=ddmCtrl, companyLimitIp=companyLimitIp, syslogServerGroup=syslogServerGroup, sysType=sysType, sysCommandLogging=sysCommandLogging, igsVlanQuerier=igsVlanQuerier, qosDiffServType21=qosDiffServType21, aacServerAccountingPort=aacServerAccountingPort, ipv4aclQosIndex=ipv4aclQosIndex, snmpV3HostCommunityName=snmpV3HostCommunityName, lldpXdot1RemProtocolEntry=lldpXdot1RemProtocolEntry, impbAutoScanBinding=impbAutoScanBinding, eoamState=eoamState, sysLBDVlanLoopIndex=sysLBDVlanLoopIndex, vlanMacStatus=vlanMacStatus, trafficSegIfIndex=trafficSegIfIndex, qinqVlanTranslationCVIDRowStatus=qinqVlanTranslationCVIDRowStatus, multicastVlanEntry=multicastVlanEntry, igmpMulticastVlanGroupTable=igmpMulticastVlanGroupTable, cpuFilterL2RuleEntry=cpuFilterL2RuleEntry, duldDiscoveryTime=duldDiscoveryTime, doSCtrlTable=doSCtrlTable, aacEnableMethodListName=aacEnableMethodListName, igsRouterPortPurgeInterval=igsRouterPortPurgeInterval, dhcpBOOTPRelayServerIP=dhcpBOOTPRelayServerIP, syslogSettingGroup=syslogSettingGroup, snmpTrapRSTPStateChange=snmpTrapRSTPStateChange, dhcpv6RelayOpt38PortType=dhcpv6RelayOpt38PortType, ipv4syslogServSeverity=ipv4syslogServSeverity, swAuthRadiusServerAccountingPort=swAuthRadiusServerAccountingPort, aclv6L3RuleTcpPshBit=aclv6L3RuleTcpPshBit, limitIpMulticaststartIpAddr=limitIpMulticaststartIpAddr, dosCtrlTrapLogState=dosCtrlTrapLogState, cosScheduleMechanism=cosScheduleMechanism, lldpXdot3LocPowerClass=lldpXdot3LocPowerClass, guestVlanDelState=guestVlanDelState, impbAutoScanEntry=impbAutoScanEntry, autoFdbTable=autoFdbTable, lldpXdot1RemVlanName=lldpXdot1RemVlanName, sysSNTPDSTEndMon=sysSNTPDSTEndMon, ipv4aclProfileSrcIpAddrMask=ipv4aclProfileSrcIpAddrMask, impbPortDHCPv4VlanList1k=impbPortDHCPv4VlanList1k, lldpXdot1ConfigProtoVlanTxEnable=lldpXdot1ConfigProtoVlanTxEnable, qosDiffServType19=qosDiffServType19, l2PTThresholdTable=l2PTThresholdTable, ipifV6AddressIpPrefix=ipifV6AddressIpPrefix, swTimeRangeStartMinute=swTimeRangeStartMinute, snmpTrapLBD=snmpTrapLBD, aclProfileType=aclProfileType)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3RuleICMPMessageType=cpuFilterL3RuleICMPMessageType, pppoePortState=pppoePortState, companyVLANTrunk=companyVLANTrunk, snmpV3UserTable=snmpV3UserTable, sysSNTPDSTRepeatStartHour=sysSNTPDSTRepeatStartHour, aclv6L3RuleICMPMessageType=aclv6L3RuleICMPMessageType, sysPortMediaTypeRev=sysPortMediaTypeRev, mstiBridgeRegionalRoot=mstiBridgeRegionalRoot, mldsHostPortPurgeInterval=mldsHostPortPurgeInterval, dot1qVlanUntaggedPorts=dot1qVlanUntaggedPorts, lldpXdot1LocProtocolTable=lldpXdot1LocProtocolTable, igmpMulticastVlanReplaceSourceIp=igmpMulticastVlanReplaceSourceIp, dhcpLocalRelaySettingsVLANID=dhcpLocalRelaySettingsVLANID, aclQosEntry=aclQosEntry, igsVlanReportSuppression=igsVlanReportSuppression, laAlgorithm=laAlgorithm, swAuthUserStatus=swAuthUserStatus, companyRMON=companyRMON, dhcpBOOTPRelayInterfaceSettingsTable=dhcpBOOTPRelayInterfaceSettingsTable, companyQinQ=companyQinQ, aclL3RuleProfileNo=aclL3RuleProfileNo, rmonEventCommunity=rmonEventCommunity, sysSNTPDSTOffset=sysSNTPDSTOffset, aclProfileDstIpAddrMask=aclProfileDstIpAddrMask, sysFromIP=sysFromIP, swAuthPortAccessCtrl=swAuthPortAccessCtrl, qinqVLANTranslation=qinqVLANTranslation, ipv4smtpRecvMailAddrTable=ipv4smtpRecvMailAddrTable, ftpFwUsername=ftpFwUsername, bandwidthCtrlTable=bandwidthCtrlTable, vlanMacMapAddrMask=vlanMacMapAddrMask, igmpMulticastVlanRemapPriority=igmpMulticastVlanRemapPriority, qosDiffServType27=qosDiffServType27, lldpXdot1LocEntry=lldpXdot1LocEntry, cpuFilterv6L3RuleTcpRstBit=cpuFilterv6L3RuleTcpRstBit, cpuFilterL3RuleTcpUdpSrcPort=cpuFilterL3RuleTcpUdpSrcPort, iPv4aacServerIPAddr=iPv4aacServerIPAddr, dhcpv6RelayOption18InterfaceIDType=dhcpv6RelayOption18InterfaceIDType, smtpServerAddrType=smtpServerAddrType, mldsVlanGrpQueryInterval=mldsVlanGrpQueryInterval, aclQosTCPUDPPort=aclQosTCPUDPPort, sysFirmwareInfomation=sysFirmwareInfomation, swTimeRangeRowStatus=swTimeRangeRowStatus, ddmStatusPort=ddmStatusPort, lldpXdot1ConfigProtocolTable=lldpXdot1ConfigProtocolTable, aclL3RuleDstIpAddrMask=aclL3RuleDstIpAddrMask, doSCtrlEntry=doSCtrlEntry, dhcpBOOTPRelayManagement=dhcpBOOTPRelayManagement, eoamMode=eoamMode, aacLoginMethod3=aacLoginMethod3, impbAutoScanTable=impbAutoScanTable, aclQosVlanID=aclQosVlanID, ipv4aclQosType=ipv4aclQosType, multicastVlanGroupVid=multicastVlanGroupVid, stpForwardDelay=stpForwardDelay, iPv4aacServerRowStatus=iPv4aacServerRowStatus, igmpMulticastVlanStatus=igmpMulticastVlanStatus, lldpXdot3LocPortAutoNegAdvertisedCap=lldpXdot3LocPortAutoNegAdvertisedCap, sysPortCtrlFlowControlOper=sysPortCtrlFlowControlOper, mldsStatus=mldsStatus, aacAPSSHLoginMethod=aacAPSSHLoginMethod, ipv4trustedHostRowStatus=ipv4trustedHostRowStatus, pppoePortIndex=pppoePortIndex, sshUserInfoHostName=sshUserInfoHostName, aclPacketAccessID=aclPacketAccessID, snmpV3UserPrivProtocolPassword=snmpV3UserPrivProtocolPassword, sysTrapPortSecurity=sysTrapPortSecurity, d_link=d_link, swAuthRadiusIPType=swAuthRadiusIPType, aacEnableMethod1=aacEnableMethod1, macNotifyInfo=macNotifyInfo, iPv4swAuthRadiusServerTable=iPv4swAuthRadiusServerTable, lldpXdot1RemVlanId=lldpXdot1RemVlanId, stpPortRestrictedTCN=stpPortRestrictedTCN, aclv6L3RuleFilterTimeRange=aclv6L3RuleFilterTimeRange, dot1qVlanManagementid=dot1qVlanManagementid, qosUserPriClass=qosUserPriClass, aclUdfOffsetBase1=aclUdfOffsetBase1, aclPacketRuleFilterTimeRange=aclPacketRuleFilterTimeRange, multicastVlanState=multicastVlanState, aclUdfOffsetBase4=aclUdfOffsetBase4, companyMacNotify=companyMacNotify, companyCableDiagnostic=companyCableDiagnostic, mldsHostTableGroupAddress=mldsHostTableGroupAddress, autoFdbStatus=autoFdbStatus, snmpV3CommunityEntry=snmpV3CommunityEntry, ipv4aclQosEntry=ipv4aclQosEntry, swAuthAuthReAuthentication=swAuthAuthReAuthentication, gvrpSettingsLeaveTime=gvrpSettingsLeaveTime, ipv4smtpSelfMailAddr=ipv4smtpSelfMailAddr, lldpXdot1Config=lldpXdot1Config, aacAuthenAdminState=aacAuthenAdminState, qosDiffServType43=qosDiffServType43, lldpXdot1LocVlanId=lldpXdot1LocVlanId, filterDHCPServerEntry=filterDHCPServerEntry, cpuFilterv6L3RuleTcpUdpSrcPort=cpuFilterv6L3RuleTcpUdpSrcPort, LldpPowerPortClass=LldpPowerPortClass, trafficCtrlCountDown=trafficCtrlCountDown, sysSNTPDSTRepeatStartWeekDay=sysSNTPDSTRepeatStartWeekDay, aclL3RuleICMPMessageType=aclL3RuleICMPMessageType, mstCistStatus=mstCistStatus, sysIpSubnetMask=sysIpSubnetMask, ddmStatusEntry=ddmStatusEntry, aacServerIPAddr=aacServerIPAddr, snmpV3UserVersion=snmpV3UserVersion, mldsHostTableHostIPAddress=mldsHostTableHostIPAddress, aclProfileDstIpAddrMaskType=aclProfileDstIpAddrMaskType, lldpXdot3LocPortTable=lldpXdot3LocPortTable, agentMEMutilizationIn5sec=agentMEMutilizationIn5sec, igsVlanCfgQuerier=igsVlanCfgQuerier, doSCtrlFrameCount=doSCtrlFrameCount, aclPacketRuleOffsetValue1=aclPacketRuleOffsetValue1, cosClassIndex=cosClassIndex, errorFrameWindow=errorFrameWindow, mldsVlanMulticastGroupEntry=mldsVlanMulticastGroupEntry, aacServerGroupRowStatus=aacServerGroupRowStatus, rmonStatsOwner=rmonStatsOwner, snmpV3TrapWarmStart=snmpV3TrapWarmStart, macNotifyInterval=macNotifyInterval, sysVersion=sysVersion, sysSafeGuardEnable=sysSafeGuardEnable, portSecState=portSecState, cpuFilterv6L3RuleSrcIpAddr=cpuFilterv6L3RuleSrcIpAddr, qinqGlobalStatus=qinqGlobalStatus, sysTrapDuplicateIPDetected=sysTrapDuplicateIPDetected, sysLBDVlanLoopPorts=sysLBDVlanLoopPorts, qinqTable=qinqTable, aRPSpoofPreventTable=aRPSpoofPreventTable, companyEoam=companyEoam, protocolGroupRowStatus=protocolGroupRowStatus, agentMEMutilization=agentMEMutilization, dhcpBOOTPRelayEnablePortlist=dhcpBOOTPRelayEnablePortlist, swTimeRangeSaturday=swTimeRangeSaturday, mstiConfigurationName=mstiConfigurationName, dhcpBOOTPRelayInterfaceSettingsRowStatus=dhcpBOOTPRelayInterfaceSettingsRowStatus, cosBandwidthCtrlTable=cosBandwidthCtrlTable, vlanMacMapAddr=vlanMacMapAddr, eoamSystem=eoamSystem, aclL3RuleProtocol=aclL3RuleProtocol, tftpFwTargetServerIpType=tftpFwTargetServerIpType, staticDisableAutoLearn=staticDisableAutoLearn, traps=traps, aclUdfOffsetMask3=aclUdfOffsetMask3, staticMcastIpAddr=staticMcastIpAddr, multicastVlanid=multicastVlanid, errorFrameSecondsWindow=errorFrameSecondsWindow, lldpXdot1ConfigVlanNameEntry=lldpXdot1ConfigVlanNameEntry, impbPortDHCPv6VlanList4k=impbPortDHCPv6VlanList4k, cpuFilterv6L3RuleTcpAckBit=cpuFilterv6L3RuleTcpAckBit, lldpXdot3LocPowerPairControlable=lldpXdot3LocPowerPairControlable, agentCPUutilizationIn5sec=agentCPUutilizationIn5sec, qosDiffServType61=qosDiffServType61, sfpVendorPn=sfpVendorPn, staticVlanBaseTable=staticVlanBaseTable, lldpXdot3PortConfigTLVsTxEnable=lldpXdot3PortConfigTLVsTxEnable, stpBridgeHelloTime=stpBridgeHelloTime, macNotifyInfoDiscription=macNotifyInfoDiscription, lldpXdot3LocMaxFrameSizeTable=lldpXdot3LocMaxFrameSizeTable, aclProfileDstPortMask=aclProfileDstPortMask, sysPortCtrlEntry=sysPortCtrlEntry, aclPacketRuleRateLimit=aclPacketRuleRateLimit, ipv4aclProfileSrcPortMask=ipv4aclProfileSrcPortMask, ipifSupportV4V6Info=ipifSupportV4V6Info, sysPortDescriptionTable=sysPortDescriptionTable, aclProfileArpSenderMacAddrMask=aclProfileArpSenderMacAddrMask, sysSNTPSecondType=sysSNTPSecondType, impbPortArpInspectionState=impbPortArpInspectionState, aclv6L3RuleAccessID=aclv6L3RuleAccessID, limitIpMulticastPortEntry=limitIpMulticastPortEntry, igsVlanMulticastGroupTable=igsVlanMulticastGroupTable, impbBlockListIpAddress=impbBlockListIpAddress, companyACLGroup=companyACLGroup, portSecFDBPermMac=portSecFDBPermMac, aacAPAuthMethodGroup=aacAPAuthMethodGroup, sysHardwareVersion=sysHardwareVersion, aclv6L3RuleICMPMessageCode=aclv6L3RuleICMPMessageCode, ftpConfigPassword=ftpConfigPassword, ipv4aclUdfOffsetByte3=ipv4aclUdfOffsetByte3, dhcpBOOTPRelayOption82CircuitID=dhcpBOOTPRelayOption82CircuitID, qosDiffServType48=qosDiffServType48, l2PTDropThreshold=l2PTDropThreshold, companyMldsGroup=companyMldsGroup, mstCistBridgePriority=mstCistBridgePriority, companyDHCPLocalRelay=companyDHCPLocalRelay, sysPortCtrlIndex=sysPortCtrlIndex, lldpXdot3LocPowerMDIEnabled=lldpXdot3LocPowerMDIEnabled, protocolVlanRowStatus=protocolVlanRowStatus, aclQosMACAddr=aclQosMACAddr, mldsVlanFbdRtrPortList=mldsVlanFbdRtrPortList, aclv6L3RuleTcpRstBit=aclv6L3RuleTcpRstBit, igsHostTableGroupAddress=igsHostTableGroupAddress, aclL3RuleReplace1P=aclL3RuleReplace1P, sysLBDPortLoopStatus=sysLBDPortLoopStatus, ipv4smtpRecvMailAddr=ipv4smtpRecvMailAddr, ipv4aclUdfOffsetBase2=ipv4aclUdfOffsetBase2, cpuFilterProfileIPProtocolMask=cpuFilterProfileIPProtocolMask, aacLoginMethodListIndex=aacLoginMethodListIndex, vlanMacMapIndex=vlanMacMapIndex, stpRootBridge=stpRootBridge, bandwidthCtrlIndex=bandwidthCtrlIndex, aclL3RuleTcpAckBit=aclL3RuleTcpAckBit, aclv6L3RuleDstIpAddrMask=aclv6L3RuleDstIpAddrMask, rmonHistoryEntry=rmonHistoryEntry, aacAccountingServiceSystem=aacAccountingServiceSystem, laPortChannelIfIndex=laPortChannelIfIndex, dhcpLocalRelayTableEntry=dhcpLocalRelayTableEntry, rmonEventType=rmonEventType, aacAccountingServiceCommandPoweruser=aacAccountingServiceCommandPoweruser, sysPortErrEntry=sysPortErrEntry, qinqTrustCVIDState=qinqTrustCVIDState, aclL3RuleTcpUdpSrcPortMask=aclL3RuleTcpUdpSrcPortMask, doSCtrlState=doSCtrlState, PortList=PortList, ipv4cpuFilterProfileDstMacAddrMask=ipv4cpuFilterProfileDstMacAddrMask, qosDiffServTOS=qosDiffServTOS, aclFlowMeterRate=aclFlowMeterRate, aacAPEnableMethod=aacAPEnableMethod, qosDefaultUserPri=qosDefaultUserPri, qinqSystem=qinqSystem, macNotifyCtrlEntry=macNotifyCtrlEntry, dot1qVlanEntry=dot1qVlanEntry, lldpXdot1ConfigPortVlanTable=lldpXdot1ConfigPortVlanTable, macBasedVlanMethod=macBasedVlanMethod, aclv6L3RuleTcpFinBit=aclv6L3RuleTcpFinBit, multicastVlanName=multicastVlanName, dhcpv6RelayOption37=dhcpv6RelayOption37, lldpXdot3RemMaxFrameSizeEntry=lldpXdot3RemMaxFrameSizeEntry, dhcpv6RelayOption18State=dhcpv6RelayOption18State, swAuthStatus=swAuthStatus, companyIgsGroup=companyIgsGroup, neighborIfindex=neighborIfindex, sysPortMediaTypeVendorName=sysPortMediaTypeVendorName, aclv6L3RuleProtocolMask=aclv6L3RuleProtocolMask, mldsDataDrivenLearningMaxLearnedEntryVlaue=mldsDataDrivenLearningMaxLearnedEntryVlaue, stpPortPriority=stpPortPriority, doSCtrlActionType=doSCtrlActionType, ipv4aclUdfOffsetMask4=ipv4aclUdfOffsetMask4, impbAutoScanIpAddress=impbAutoScanIpAddress, aclPacketRuleOffsetValue4=aclPacketRuleOffsetValue4, swTimeRangeMonday=swTimeRangeMonday, aclv6L3RuleTcpUdpSrcPortMask=aclv6L3RuleTcpUdpSrcPortMask, aacAccountingMethodListEntry=aacAccountingMethodListEntry, impbBindingListRowStatus=impbBindingListRowStatus, ddmStatusTable=ddmStatusTable, lldpXdot1LocProtocolId=lldpXdot1LocProtocolId, cpuFilterL2ProfileID=cpuFilterL2ProfileID, companyGVRPGroup=companyGVRPGroup, aclL3RuleEntry=aclL3RuleEntry, Timeout=Timeout, aclv6L3RuleTcpSynBit=aclv6L3RuleTcpSynBit, sysSNTPState=sysSNTPState, errorFrameSecondsThreshold=errorFrameSecondsThreshold, snmpV3GroupName=snmpV3GroupName, lldpXdot1ConfigVlanNameTxEnable=lldpXdot1ConfigVlanNameTxEnable)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", ftpConfigPath=ftpConfigPath, ipv4aclUdfOffsetByte2=ipv4aclUdfOffsetByte2, snmpV3GroupNotifyViewName=snmpV3GroupNotifyViewName, snmpV3UserAuthProtocolPassword=snmpV3UserAuthProtocolPassword, BridgeId=BridgeId, aclPacketRuleOffsetValue3Mask=aclPacketRuleOffsetValue3Mask, vlanMacMapRowStatus=vlanMacMapRowStatus, laSystem=laSystem, dlink_DES1210SeriesProd=dlink_DES1210SeriesProd, protocolGroupNameTable=protocolGroupNameTable, ipv4aclProfileType=ipv4aclProfileType, ddmThresholdType=ddmThresholdType, ddmInfo=ddmInfo, iPv4aacServerInfoTable=iPv4aacServerInfoTable, limitIpMulticastProfileTable=limitIpMulticastProfileTable, aclv6L3RuleSrcIpAddrMask=aclv6L3RuleSrcIpAddrMask, lldpXdot1RemProtoVlanTable=lldpXdot1RemProtoVlanTable, multicastVlanGroupTable=multicastVlanGroupTable, autoFdbEntry=autoFdbEntry, limitIpMulticastEntryProfileID=limitIpMulticastEntryProfileID, companySystem=companySystem, aclProfileUdfOffsetMap=aclProfileUdfOffsetMap, impbPortDHCPv6VlanList1k=impbPortDHCPv6VlanList1k, sysSNTPGMTMinutes=sysSNTPGMTMinutes, mldsVlanMulticastGroupVlanId=mldsVlanMulticastGroupVlanId, aclL3RuleSrcIpAddr=aclL3RuleSrcIpAddr, aclL3RuleStatus=aclL3RuleStatus, stpPortRestrictedRole=stpPortRestrictedRole, lldpPortConfigNotificationEnable=lldpPortConfigNotificationEnable, aclFlowMeterReplaceDscp=aclFlowMeterReplaceDscp, aclv6L3RuleEntry=aclv6L3RuleEntry, rmonAlarmOwner=rmonAlarmOwner, qosTOSType00=qosTOSType00, ipv4sysIprouteHops=ipv4sysIprouteHops, limitIpMulticastProfileName=limitIpMulticastProfileName, mldsVlanRtrPortList=mldsVlanRtrPortList, cpuFilterL3RuleTcpFinBit=cpuFilterL3RuleTcpFinBit, macNotifyPortStatus=macNotifyPortStatus, rmonEventOwner=rmonEventOwner, mstResetVlanList=mstResetVlanList, cpuFilterv6L3RuleProtocol=cpuFilterv6L3RuleProtocol, aclProfileSrcMacAddrMask=aclProfileSrcMacAddrMask, tftpFwServerIpAddress=tftpFwServerIpAddress, swAuthAuthServerTimeout=swAuthAuthServerTimeout, lldpXdot3LocLinkAggStatus=lldpXdot3LocLinkAggStatus, agentCPUutilization=agentCPUutilization, cableDiagEntry=cableDiagEntry, cpuFilterL2RuleAction=cpuFilterL2RuleAction, cpuFilterL3RuleTcpUrgBit=cpuFilterL3RuleTcpUrgBit, pppoePortTable=pppoePortTable, securityTrustedHost=securityTrustedHost, syslogSaveMode=syslogSaveMode, dhcpv6RelayOption18=dhcpv6RelayOption18, eoamReceivedRemoteLoopback=eoamReceivedRemoteLoopback, impbDhcpSnoopingTable=impbDhcpSnoopingTable, aacAccountingMethod4=aacAccountingMethod4, swAuthRadiusServerEntry=swAuthRadiusServerEntry, impbBindingListPort=impbBindingListPort, snmpTrapBPDUAttack=snmpTrapBPDUAttack, duldOperState=duldOperState, snmpV3CommunityStatus=snmpV3CommunityStatus, dhcpv6RelayState=dhcpv6RelayState, aacAPTelnetLoginMethod=aacAPTelnetLoginMethod, cpuFilterL3RuleProtocol=cpuFilterL3RuleProtocol, ipv4aclProfileNo=ipv4aclProfileNo, rmonHistoryDataSource=rmonHistoryDataSource, sysPortType=sysPortType, mstMstiBridgeEntry=mstMstiBridgeEntry, aclL3RuleSrcIpAddrMask=aclL3RuleSrcIpAddrMask, swTimeRangeSunday=swTimeRangeSunday, stpPortStatus=stpPortStatus, igmpMulticastVlanid=igmpMulticastVlanid, dhcpRelayVlanSettingsVLANID=dhcpRelayVlanSettingsVLANID, bandwidthEffecRxThreshold=bandwidthEffecRxThreshold, impbPortForwardDHCPPktState=impbPortForwardDHCPPktState, sysPortDescriptionEntry=sysPortDescriptionEntry, aclPacketRuleOffsetValue4Mask=aclPacketRuleOffsetValue4Mask, lldpXdot1LocProtoVlanSupported=lldpXdot1LocProtoVlanSupported, aclL2RuleAction=aclL2RuleAction, aacAccountingServiceIndex=aacAccountingServiceIndex, sysSize=sysSize, swTimeRangeSettingTable=swTimeRangeSettingTable, sysSNTPDSTRepeatEndHour=sysSNTPDSTRepeatEndHour, aclL3RuleDstIpAddr=aclL3RuleDstIpAddr, aclL3RuleAccessID=aclL3RuleAccessID, swAuthenCtrl=swAuthenCtrl, ipv4aclQosIPAddr=ipv4aclQosIPAddr, lldpXdot1LocVlanName=lldpXdot1LocVlanName, limitIpMulticastEntry=limitIpMulticastEntry, aclProfileEntry=aclProfileEntry, qosDiffServType33=qosDiffServType33, LldpLinkAggStatusMap=LldpLinkAggStatusMap, igmpMulticastVlanMemberPort=igmpMulticastVlanMemberPort, aclPacketRuleInPortList=aclPacketRuleInPortList, lldpXdot3RemMaxFrameSize=lldpXdot3RemMaxFrameSize, ipv4dhcpOption12HostName=ipv4dhcpOption12HostName, pppoePortUDFString=pppoePortUDFString, aRPSpoofPreventIpAddr=aRPSpoofPreventIpAddr, l2PTProtocol=l2PTProtocol, multicastVlanGroupFromIp=multicastVlanGroupFromIp, filterDHCPServerTable=filterDHCPServerTable, sysSMTPServerGroup=sysSMTPServerGroup, cosOutputSchedule=cosOutputSchedule, lldpXdot3PortConfigTable=lldpXdot3PortConfigTable, multicastVlanTagMemberPort=multicastVlanTagMemberPort, lldpXdot3RemPortEntry=lldpXdot3RemPortEntry, ipv4syslogServSrvStatus=ipv4syslogServSrvStatus, swTimeRangeEndHour=swTimeRangeEndHour, companyLA=companyLA, snmpV3TrapColdStart=snmpV3TrapColdStart, lldpPortConfigTable=lldpPortConfigTable, swTimeRangeStartYear=swTimeRangeStartYear, qosDiffServType40=qosDiffServType40, aclPacketRuleReplaceDSCP=aclPacketRuleReplaceDSCP, limitIpMulticastStatus=limitIpMulticastStatus, snmpV3ViewTree=snmpV3ViewTree, stpPortEntry=stpPortEntry, impbBindingtraplog=impbBindingtraplog, cpuFilterv6L3RuleEntry=cpuFilterv6L3RuleEntry, errorFrameThreshold=errorFrameThreshold, lldpXdot3RemPowerTable=lldpXdot3RemPowerTable, protocolGroupProtocolValue=protocolGroupProtocolValue, aacLoginMethod2=aacLoginMethod2, sysUpdateTime=sysUpdateTime, companyMacBasedVlan=companyMacBasedVlan, snmpV3CommunityName=snmpV3CommunityName, igsHostTable=igsHostTable, qosPriSettingsTable=qosPriSettingsTable, cpuFilterv6L3RuleTcpUdpDstPortMask=cpuFilterv6L3RuleTcpUdpDstPortMask, qinqOuterTPID=qinqOuterTPID, lldpPortConfigPortNum=lldpPortConfigPortNum, guestVlanName=guestVlanName, impbDhcpSnoopingEntry=impbDhcpSnoopingEntry, aclQosTable=aclQosTable, sysTrapLBD=sysTrapLBD, LacpKey=LacpKey, qosPriSetPortIndex=qosPriSetPortIndex, qosDiffServType29=qosDiffServType29, ipv4sysSNTPState=ipv4sysSNTPState, cpuFilterL3RuleTcpAckBit=cpuFilterL3RuleTcpAckBit, ipv4aclUdfOffsetByte1=ipv4aclUdfOffsetByte1, aclL2RuleTable=aclL2RuleTable, lldpXdot3RemoteData=lldpXdot3RemoteData, cableDiagPair3Length=cableDiagPair3Length, cpuFilterProfileNo=cpuFilterProfileNo, mstMstiStatus=mstMstiStatus, sysBPDUAttackStateEnable=sysBPDUAttackStateEnable, qosDiffServType44=qosDiffServType44, trafficCtrlIndex=trafficCtrlIndex, companyCPUInterfaceFilterGroup=companyCPUInterfaceFilterGroup, qosDefaultPriority=qosDefaultPriority, companyGratuitousARP=companyGratuitousARP, qosDiffServType47=qosDiffServType47, ipv4aclProfileUdfOffsetMap=ipv4aclProfileUdfOffsetMap, ipifV6AddressIpAddr=ipifV6AddressIpAddr, snmpTrapFirmUpgrade=snmpTrapFirmUpgrade, impbVlanModeVlanList=impbVlanModeVlanList, dhcpv6RelayOption37RemoteIDType=dhcpv6RelayOption37RemoteIDType, bandwidthCtrlTxThreshold=bandwidthCtrlTxThreshold, aclL2RuleStatus=aclL2RuleStatus, dhcpv6RelayOpt38PortState=dhcpv6RelayOpt38PortState, lldpXdot1RemEntry=lldpXdot1RemEntry, cableDiagStatus=cableDiagStatus, mldsVlanFilterEntry=mldsVlanFilterEntry, duldEntry=duldEntry, qosDiffServType18=qosDiffServType18, lldpXdot1LocalData=lldpXdot1LocalData, agentMEMutilizationIn1min=agentMEMutilizationIn1min, laPortActorActivity=laPortActorActivity, companyMirror=companyMirror, sysPortMediaTypeSn=sysPortMediaTypeSn, swAuthPortAccessControlTable=swAuthPortAccessControlTable, aclv6L3RuleTcpUdpSrcPort=aclv6L3RuleTcpUdpSrcPort, aacAccountingMethodListName=aacAccountingMethodListName, impbPortDHCPv4VlanList4k=impbPortDHCPv4VlanList4k, swTimeRangeIndex=swTimeRangeIndex, tftpFwTargetInterfaceName=tftpFwTargetInterfaceName, multicastVlanRowStatus=multicastVlanRowStatus, impbAutoScanIpAddressTo=impbAutoScanIpAddressTo, ipifv6NSRetransmitTime=ipifv6NSRetransmitTime, mstMstiInstanceIndex=mstMstiInstanceIndex, limitIpMulticastPortID=limitIpMulticastPortID, eoamLinkMonitorTable=eoamLinkMonitorTable, impbPortDHCPv6SetVlanList=impbPortDHCPv6SetVlanList, impbDhcpSnoopingIpAddress=impbDhcpSnoopingIpAddress, cpuFilterProfileSrcIpAddrMask=cpuFilterProfileSrcIpAddrMask, swTimeRangeEndDay=swTimeRangeEndDay, mstCistVlanMapped4k=mstCistVlanMapped4k, gvrpGVRPGlobalSettingsOnOff=gvrpGVRPGlobalSettingsOnOff, dhcpv6RelayInterfaceSettingsEntry=dhcpv6RelayInterfaceSettingsEntry, snmpV3UserAuthProtocol=snmpV3UserAuthProtocol, lldpXdot3RemPowerMDIEnabled=lldpXdot3RemPowerMDIEnabled, qosTOSType06=qosTOSType06, ipv4smtpServerPort=ipv4smtpServerPort, aacAccountingMethod3=aacAccountingMethod3, laPortControlIndex=laPortControlIndex, gvrpSettingsPortControlIndex=gvrpSettingsPortControlIndex, aacServerPasswordEncryption=aacServerPasswordEncryption, sysBPDUAttackPortStatus=sysBPDUAttackPortStatus, qosUserPriority=qosUserPriority, impbDhcpSnoopingLeaseTime=impbDhcpSnoopingLeaseTime, iPv4aacServerRetryCount=iPv4aacServerRetryCount, ipv4aclProfileRuleCount=ipv4aclProfileRuleCount, dhcpv6RelayOpt38Entry=dhcpv6RelayOpt38Entry, companyDoSCtrl=companyDoSCtrl, protocolVlanVID=protocolVlanVID, ddmHighAlarm=ddmHighAlarm, sysSwitchName=sysSwitchName, portSecFDBPermVlanID=portSecFDBPermVlanID, ipv4aclProfileTable=ipv4aclProfileTable, des_1210_28me=des_1210_28me, igsVlanFastLeave=igsVlanFastLeave, iPv4swAuthRadiusServerRetransmit=iPv4swAuthRadiusServerRetransmit, miscStatisticsReset=miscStatisticsReset, ipv4sysSNTPDSTStartMin=ipv4sysSNTPDSTStartMin, lldpXdot3LocalData=lldpXdot3LocalData, mstInstanceVlanMapped4k=mstInstanceVlanMapped4k, trustedHostEntry=trustedHostEntry, ftpConfigUsername=ftpConfigUsername, igsDataDrivenLearningMaxLearnedEntryVlaue=igsDataDrivenLearningMaxLearnedEntryVlaue, multicastVlanGroupToIp=multicastVlanGroupToIp, ipv4dhcpOption12Status=ipv4dhcpOption12Status, errorFrameNotifyState=errorFrameNotifyState, qosDiffServType39=qosDiffServType39, aacAuthParamAttempt=aacAuthParamAttempt, ipifV6AddressMainIndex=ipifV6AddressMainIndex, sysTrapTwistedPortEvent=sysTrapTwistedPortEvent, staticStatus=staticStatus, sysMirrorTargetPort=sysMirrorTargetPort, qinqIfIndex=qinqIfIndex, mldsVlanRobustnessValue=mldsVlanRobustnessValue, swAuthUserEntry=swAuthUserEntry, errorSymbolNotifyState=errorSymbolNotifyState, tftpFwTftpOperationStatus=tftpFwTftpOperationStatus, qosDiffServType30=qosDiffServType30, cpuFilterL2RuleDstMacAddr=cpuFilterL2RuleDstMacAddr, lldpPortConfigAdminStatus=lldpPortConfigAdminStatus, agentCPUutilizationIn1min=agentCPUutilizationIn1min, ipv4snmpV3HostVersion=ipv4snmpV3HostVersion, sysGratuitousARPLearning=sysGratuitousARPLearning, ipv4smtpServerAddr=ipv4smtpServerAddr, aacServerAuthPort=aacServerAuthPort, qosTOSGroup=qosTOSGroup, ddmTemperature=ddmTemperature, cpuFilterv6L3RuleDstIpAddrMask=cpuFilterv6L3RuleDstIpAddrMask, sshUserInfoAuth=sshUserInfoAuth, impbBlockListStatus=impbBlockListStatus, ipv4aclProfileIPProtocol=ipv4aclProfileIPProtocol, ipv4aclProfileStatus=ipv4aclProfileStatus, lldpXdot1RemPortVlanId=lldpXdot1RemPortVlanId, sysSNTPServerTable=sysSNTPServerTable, sysSNTPDSTEndMin=sysSNTPDSTEndMin, qosDefaultUserPriTable=qosDefaultUserPriTable, rmonEventEntry=rmonEventEntry)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", dot1qVlanAdvertisementStatus=dot1qVlanAdvertisementStatus, lldpXdot3LocPowerTable=lldpXdot3LocPowerTable, qosDiffServType26=qosDiffServType26, aclv6L3RuleTcpAckBit=aclv6L3RuleTcpAckBit, filterDHCPServerRowStatus=filterDHCPServerRowStatus, impbPortIndex=impbPortIndex, ipv4trustedHostIpMask=ipv4trustedHostIpMask, ddmVoltage=ddmVoltage, aacAPHttpEnableMethod=aacAPHttpEnableMethod, swAuthAuthSuppTimeout=swAuthAuthSuppTimeout, snmpV3TrapSNMPAuthentication=snmpV3TrapSNMPAuthentication, sysPortErrPortReason=sysPortErrPortReason, staticVlanBaseEnableAutoLearn=staticVlanBaseEnableAutoLearn, gvrpSettingsJoinTime=gvrpSettingsJoinTime, macNotifyState=macNotifyState, aacServerGroupEntry=aacServerGroupEntry, igmpMulticastVlanGroupStatus=igmpMulticastVlanGroupStatus, mldsVlan=mldsVlan, impbPortDHCPv4SetVlanList=impbPortDHCPv4SetVlanList, qosTOSType05=qosTOSType05, ddmBiasCurrent=ddmBiasCurrent, cpuFilterv6L3RuleProtocolMask=cpuFilterv6L3RuleProtocolMask, qosDiffServType13=qosDiffServType13, mldsSystem=mldsSystem, staticARPMac=staticARPMac, ipv4sysSNTPDSTEndMin=ipv4sysSNTPDSTEndMin, qosTOSType07=qosTOSType07, rmonHistoryStatus=rmonHistoryStatus, tftpFwTargetTftpOperation=tftpFwTargetTftpOperation, aclQosIPv6Addr=aclQosIPv6Addr, igsVlan=igsVlan, qosDiffServType09=qosDiffServType09, lldpXdot1LocVlanNameTable=lldpXdot1LocVlanNameTable, ipv4sysIprouteGateway=ipv4sysIprouteGateway, duldLinkStatus=duldLinkStatus, stpPortTable=stpPortTable, gvrpSettingsTable=gvrpSettingsTable, dot1qVlanName=dot1qVlanName, ipifName=ipifName, trafficSegMemberList=trafficSegMemberList, swTimeRangeEndMinute=swTimeRangeEndMinute, cpuFilterv6L3RuleDstIpAddr=cpuFilterv6L3RuleDstIpAddr, sysSNTPDSTRepeatEndMin=sysSNTPDSTRepeatEndMin, sysTrapFirmUpgradeEvent=sysTrapFirmUpgradeEvent, qosDiffServType46=qosDiffServType46, l2PTPortIndex=l2PTPortIndex, aRPSpoofPreventMacAddress=aRPSpoofPreventMacAddress, cpuFilterProfileDstIpAddrMask=cpuFilterProfileDstIpAddrMask, aacAccountingServiceNetwork=aacAccountingServiceNetwork, sysPortCtrlMDI=sysPortCtrlMDI, iPv4swAuthRadiusServerStatus=iPv4swAuthRadiusServerStatus, dlink_products=dlink_products, impbBindingListMacAddress=impbBindingListMacAddress, dhcpBOOTPRelayManagementOption82=dhcpBOOTPRelayManagementOption82, aacEnableMethodListIndex=aacEnableMethodListIndex, sysSNTPPollInterval=sysSNTPPollInterval, lldpXdot3Objects=lldpXdot3Objects, sysPortCtrlCapability=sysPortCtrlCapability, mstMstiPortEntry=mstMstiPortEntry, snmpV3GroupReadViewName=snmpV3GroupReadViewName, ftpFwFTPOperation=ftpFwFTPOperation, mstMstiBridgeTable=mstMstiBridgeTable, aclProfileIPProtocol=aclProfileIPProtocol, securitySSH=securitySSH, aclL2RuleReplaceQueue=aclL2RuleReplaceQueue, qosDiffServType08=qosDiffServType08, lldpXdot3RemPortAutoNegAdvertisedCap=lldpXdot3RemPortAutoNegAdvertisedCap, trafficSegTable=trafficSegTable, snmpV3TrapDHCPServerScreening=snmpV3TrapDHCPServerScreening, mstMstiCurrentPortRole=mstMstiCurrentPortRole, dhcpv6RelayOption37CheckState=dhcpv6RelayOption37CheckState, igmpMulticastVlanSourcePort=igmpMulticastVlanSourcePort, stpInstancePortTable=stpInstancePortTable, trafficCtrlThreshold=trafficCtrlThreshold, trustedHostIpAddr=trustedHostIpAddr, ipv4snmpV3HostEntry=ipv4snmpV3HostEntry, cpuFilterv6L3RuleSrcIpAddrMask=cpuFilterv6L3RuleSrcIpAddrMask, staticPort=staticPort, companySNTPSetting=companySNTPSetting, cableDiagPortType=cableDiagPortType, snmpV3HostTable=snmpV3HostTable, aclPacketRuleReplace1P=aclPacketRuleReplace1P, igsSystem=igsSystem, dlinklldpConfigManAddrPortsTxEnable=dlinklldpConfigManAddrPortsTxEnable, impbRoamingState=impbRoamingState, sysLocationName=sysLocationName, vlanTrunkGlobalStatus=vlanTrunkGlobalStatus, rmonHistoryBucketsRequested=rmonHistoryBucketsRequested, lldpXdot3LocPowerEntry=lldpXdot3LocPowerEntry, smtpRecvMailAddrTable=smtpRecvMailAddrTable, sysPortMediaTypeTable=sysPortMediaTypeTable, sysMirrorStatus=sysMirrorStatus, syslogServEntry=syslogServEntry, aclPacketRuleOffsetValue1Mask=aclPacketRuleOffsetValue1Mask, snmpV3IPType=snmpV3IPType, securityARPSpoofPrevent=securityARPSpoofPrevent, lldpXdot3RemPortAutoNegSupported=lldpXdot3RemPortAutoNegSupported, aclv6L3RuleTcpUdpDstPort=aclv6L3RuleTcpUdpDstPort, cpuFilterv6L3RuleTcpUrgBit=cpuFilterv6L3RuleTcpUrgBit, igsVlanRouterPortList=igsVlanRouterPortList, syslogServIndex=syslogServIndex, impbPortDHCPv4VlanList3k=impbPortDHCPv4VlanList3k, companyLBD=companyLBD, aclProfileStatus=aclProfileStatus, sysWebState=sysWebState, sysIpAddrCfgMode=sysIpAddrCfgMode, rmonAlarmVariable=rmonAlarmVariable, stpRootPort=stpRootPort, sysGroupInterval=sysGroupInterval, qosDiffServType52=qosDiffServType52, tftpConfigTftpOperationStatus=tftpConfigTftpOperationStatus, aclv6L3RuleReplaceDSCP=aclv6L3RuleReplaceDSCP, lldpXdot3RemPortTable=lldpXdot3RemPortTable, ipv4smtpState=ipv4smtpState, errorFramePeriodThreshold=errorFramePeriodThreshold, protocolGroupName=protocolGroupName, PortLaMode=PortLaMode, igsVlanFbdRtrPortList=igsVlanFbdRtrPortList, ipv4sysSNTPDSTEndDay=ipv4sysSNTPDSTEndDay, qinqVLANTranslationState=qinqVLANTranslationState, snmpTrapGratuitousArp=snmpTrapGratuitousArp, igsVlanMulticastGroupVlanId=igsVlanMulticastGroupVlanId, aclFlowMeterAccessID=aclFlowMeterAccessID, dhcpRelayVlanTable=dhcpRelayVlanTable, companyDot1qVlanGroup=companyDot1qVlanGroup, portSecFDBPermPort=portSecFDBPermPort, cpuFilterProfileRuleCount=cpuFilterProfileRuleCount, snmpV3HostInterfaceName=snmpV3HostInterfaceName, ipifv6DefaultGateway=ipifv6DefaultGateway, cpuFilterProfileTable=cpuFilterProfileTable, aacAccountingServiceCommandUser=aacAccountingServiceCommandUser, cpuFilterProfileEntry=cpuFilterProfileEntry, duldIfIndex=duldIfIndex, protocolGroupEntry=protocolGroupEntry, stpPortEdge=stpPortEdge, snmpTrapPortSecurity=snmpTrapPortSecurity, l2PTProtocolIndex=l2PTProtocolIndex, smtpServerPort=smtpServerPort, ipifV6AddressTable=ipifV6AddressTable, trafficSegEntry=trafficSegEntry, qosDiffServType49=qosDiffServType49, aclQosType=aclQosType, vlanTrunkTable=vlanTrunkTable, cosClassTable=cosClassTable, mstCistPortTable=mstCistPortTable, tftpCfgTargetServerIpType=tftpCfgTargetServerIpType, qosDiffServType42=qosDiffServType42, dhcpRelayVlanTableEntry=dhcpRelayVlanTableEntry, aacServerGroupTable=aacServerGroupTable, dot1qVlanAsyOnOff=dot1qVlanAsyOnOff, protocolGroupFrameType=protocolGroupFrameType, laPortChannelMasterPort=laPortChannelMasterPort, aacAccountingMethodListTable=aacAccountingMethodListTable, l2PTEntry=l2PTEntry, igsReportToAllPort=igsReportToAllPort, neighborRowStatus=neighborRowStatus, brgAddress=brgAddress, qinqVlanTranslationSVID=qinqVlanTranslationSVID, cpuFilterL3RulePortList=cpuFilterL3RulePortList, lldpXdot3LocPowerPairs=lldpXdot3LocPowerPairs, impbPortProtocolState=impbPortProtocolState, qosPriSettingsEntry=qosPriSettingsEntry, filterDHCPServerIpAddr=filterDHCPServerIpAddr, sysGratuitousARPDuplicateIPDetected=sysGratuitousARPDuplicateIPDetected, tftpFwImageFileName=tftpFwImageFileName, ipv4aclProfileArpSenderIpAddrMask=ipv4aclProfileArpSenderIpAddrMask, syslogServAddr=syslogServAddr, sysPortCtrlFlowControl=sysPortCtrlFlowControl, aclv6L3RuleAction=aclv6L3RuleAction, lldpXdot1LocProtoVlanId=lldpXdot1LocProtoVlanId, sysPortErrPortStatus=sysPortErrPortStatus, mldsVlanRouterPortList=mldsVlanRouterPortList, laPortControlEntry=laPortControlEntry, iPv4swAuthRadiusServerTimeout=iPv4swAuthRadiusServerTimeout, ipv4aclQosProtocol=ipv4aclQosProtocol, snmpTrapWarmStart=snmpTrapWarmStart, dhcpRelayVlanSettingsState=dhcpRelayVlanSettingsState, multicastVlanGroupEntry=multicastVlanGroupEntry, autoRefreshConfiguration=autoRefreshConfiguration, filterDHCPServerPortList=filterDHCPServerPortList, topologyChange=topologyChange, securityAAC=securityAAC, lldpXdot1RemProtocolId=lldpXdot1RemProtocolId, cpuFilterProfileSrcIpAddrMaskType=cpuFilterProfileSrcIpAddrMaskType, syslogServAddrType=syslogServAddrType, ipv4syslogServerGroup=ipv4syslogServerGroup, cpuFilterv6L3RulePortList=cpuFilterv6L3RulePortList, mstCistPortPriority=mstCistPortPriority, swTimeRangeDate=swTimeRangeDate, sysDhcpAutoConfiguration=sysDhcpAutoConfiguration, sysLBDStateEnable=sysLBDStateEnable, tftpFwTargetGroup=tftpFwTargetGroup, sysSNTPDSTState=sysSNTPDSTState, igsVlanGrpQueryInterval=igsVlanGrpQueryInterval, snmpV3CommunityTable=snmpV3CommunityTable, tftpFwTftpOperation=tftpFwTftpOperation, companyDDM=companyDDM, qosDiffServType24=qosDiffServType24, igmpMulticastVlanState=igmpMulticastVlanState, aRPSpoofPreventEntry=aRPSpoofPreventEntry, snmpTrapDHCPScreen=snmpTrapDHCPScreen, smtpRecvMailAddrIndex=smtpRecvMailAddrIndex, cableDiagPair2Status=cableDiagPair2Status, aclPacketRuleReplaceQueue=aclPacketRuleReplaceQueue, impbSettingTable=impbSettingTable, impbDHCPv6PrefixDelegationSnoopState=impbDHCPv6PrefixDelegationSnoopState, protocolVlanPort=protocolVlanPort, mstMstiPortDesignatedBridge=mstMstiPortDesignatedBridge, lldpXdot1LocProtoVlanEntry=lldpXdot1LocProtoVlanEntry, sysTrapSystemEvent=sysTrapSystemEvent, ipv4aclQosAssignClass=ipv4aclQosAssignClass, lldpXdot3LocPortAutoNegEnabled=lldpXdot3LocPortAutoNegEnabled, igsVlanFilterEntry=igsVlanFilterEntry, aclProfileSrcIpAddrMask=aclProfileSrcIpAddrMask, igsHostTableVLANID=igsHostTableVLANID, aclL3RuleIgmpType=aclL3RuleIgmpType, swAuthRadiusServerAuthenticationPort=swAuthRadiusServerAuthenticationPort, sysSNTPDSTEndHour=sysSNTPDSTEndHour, lldpXdot1RemProtoVlanSupported=lldpXdot1RemProtoVlanSupported, ipv4aclProfileSrcMacAddrMask=ipv4aclProfileSrcMacAddrMask, sysTrapFiberPortEvent=sysTrapFiberPortEvent, ipv4aclUdfOffsetBase3=ipv4aclUdfOffsetBase3, lldpXdot3LocMaxFrameSize=lldpXdot3LocMaxFrameSize, iPv4aacServerAuthProtocol=iPv4aacServerAuthProtocol, trafficCtrlType=trafficCtrlType, sfpConnectorType=sfpConnectorType, companyPPPoE=companyPPPoE, syslogSaveMinutes=syslogSaveMinutes, errorFrameSecondsNotifyState=errorFrameSecondsNotifyState, cpuFilterL2RuleInPortList=cpuFilterL2RuleInPortList, ipifv6AutolinkloStatus=ipifv6AutolinkloStatus, impbBindingListEntry=impbBindingListEntry, iPv4aacServerAuthPort=iPv4aacServerAuthPort, aclProfileIPProtocolMask=aclProfileIPProtocolMask, smtpRecvMailAddrEntry=smtpRecvMailAddrEntry, laPortChannelEntry=laPortChannelEntry, tftpFwTargetServerIpAddress=tftpFwTargetServerIpAddress, rmonStatsIndex=rmonStatsIndex, ftpFwTable=ftpFwTable, laPortChannelMemberList=laPortChannelMemberList, aclPacketRule=aclPacketRule, qosDiffServType54=qosDiffServType54, cpuFilterv6L3RuleTcpPshBit=cpuFilterv6L3RuleTcpPshBit, sysARPAgingTime=sysARPAgingTime, errorSymbolThreshold=errorSymbolThreshold, qosDefaultUserPriPortIndex=qosDefaultUserPriPortIndex, aclPacketRuleAction=aclPacketRuleAction, aclL2RuleSrcMacAddr=aclL2RuleSrcMacAddr, qosDiffServType56=qosDiffServType56, snmpV3HostEntry=snmpV3HostEntry, swTimeRangeWednesday=swTimeRangeWednesday, dhcpOption12Status=dhcpOption12Status, filterDHCPServerClientMacAddr=filterDHCPServerClientMacAddr, aclL2RuleRateLimit=aclL2RuleRateLimit)NEWLINEmibBuilder.exportSymbols("DES-1210-28MEbx", cpuFilterL3RuleTcpPshBit=cpuFilterL3RuleTcpPshBit, sysGratuitousARPSettings=sysGratuitousARPSettings, igsVlanMulticastGroupPortList=igsVlanMulticastGroupPortList, snmpV3ViewTreeEntry=snmpV3ViewTreeEntry, sshUserInfoHostIp=sshUserInfoHostIp, autoFdbTimeStamp=autoFdbTimeStamp, mstVlanMstiMappingTable=mstVlanMstiMappingTable, igsHostEntry=igsHostEntry, sshAuthenMethodPubKeyAdmin=sshAuthenMethodPubKeyAdmin, dot1qVlanRowStatus=dot1qVlanRowStatus, staticMcastStatus=staticMcastStatus, impbDhcpSnoopingPort=impbDhcpSnoopingPort, aclL2Rule=aclL2Rule, aclFlowMeterTable=aclFlowMeterTable, sysPortDescString=sysPortDescString, aclUdfOffsetBase3=aclUdfOffsetBase3, ipv4cpuFilterProfileType=ipv4cpuFilterProfileType, sfpVendorSn=sfpVendorSn, snmpTrapColdStart=snmpTrapColdStart, impbBindingListIpAddress=impbBindingListIpAddress, mstMstiBridgePriority=mstMstiBridgePriority, dot1qVlanEgressPorts=dot1qVlanEgressPorts, cpuFilterL3RuleSrcIpAddrMask=cpuFilterL3RuleSrcIpAddrMask, aclL3RuleRateLimit=aclL3RuleRateLimit, gvrpSettingsEntry=gvrpSettingsEntry, mstInstanceVlanMapped3k=mstInstanceVlanMapped3k, doSCtrlType=doSCtrlType, aclL3RuleTcpSynBit=aclL3RuleTcpSynBit, bandwidthCtrlRxThreshold=bandwidthCtrlRxThreshold, sysTrapStateChangeEvent=sysTrapStateChangeEvent, ipifv6GlobalStatus=ipifv6GlobalStatus, rmonStatsEntry=rmonStatsEntry, stpPortAdminP2P=stpPortAdminP2P, mstVlanMstiMappingEntry=mstVlanMstiMappingEntry, iPv4swAuthRadiusServerIndex=iPv4swAuthRadiusServerIndex, qosDiffServType11=qosDiffServType11, syslogServSeverity=syslogServSeverity, dhcpv6RelayControl=dhcpv6RelayControl, sslCiphers=sslCiphers, aclQosIPAddr=aclQosIPAddr, lldpXdot1ConfigProtoVlanTable=lldpXdot1ConfigProtoVlanTable, qosDiffServType58=qosDiffServType58, ipv4sysGateway=ipv4sysGateway, impbBlockListTable=impbBlockListTable, aclPacketRuleEntry=aclPacketRuleEntry, eoamCriticalEventEnable=eoamCriticalEventEnable, snmpV3TrapLBD=snmpV3TrapLBD, sfpVendorInfoTable=sfpVendorInfoTable, ipv4aclProfileArpSenderMacAddrMask=ipv4aclProfileArpSenderMacAddrMask, dot1qVlanTable=dot1qVlanTable, lldpXdot1ConfigProtocolEntry=lldpXdot1ConfigProtocolEntry, igmpMulticastVlanGroupEntry=igmpMulticastVlanGroupEntry, cpuFilterv6L3RuleAccessID=cpuFilterv6L3RuleAccessID, sysLBDPortStatus=sysLBDPortStatus, snmpV3EngineID=snmpV3EngineID, aacServerRetryCount=aacServerRetryCount, smtpRecvMailAddr=smtpRecvMailAddr, cableDiagTable=cableDiagTable, neighborType=neighborType, ipv4syslogServAddr=ipv4syslogServAddr, tftpFwTargetImageFileName=tftpFwTargetImageFileName, dhcpv6RelayOpt38Table=dhcpv6RelayOpt38Table, ddmStatus=ddmStatus, snmpV3viewTreeMask=snmpV3viewTreeMask, companyISMVLAN=companyISMVLAN, lldpXdot3LocLinkAggTable=lldpXdot3LocLinkAggTable, sysSNTPDSTRepeatEndWeekDay=sysSNTPDSTRepeatEndWeekDay, ipv4sysSNTPDSTOffset=ipv4sysSNTPDSTOffset, neighborCacheState=neighborCacheState, igsVlanDataDrivenLearningAgeOutStatus=igsVlanDataDrivenLearningAgeOutStatus, impbSettingEntry=impbSettingEntry, snmpV3User=snmpV3User, laPortActorPortPriority=laPortActorPortPriority, dhcpLocalRelayGlobalState=dhcpLocalRelayGlobalState, companyStaticMcast=companyStaticMcast, rmonAlarm=rmonAlarm, sysSNTPFirstType=sysSNTPFirstType, qosDiffServType14=qosDiffServType14, qosDiffServType41=qosDiffServType41, ipv4sysSNTPPollInterval=ipv4sysSNTPPollInterval)NEWLINE |
## This file is part of ScapyNEWLINE## See http://www.secdev.org/projects/scapy for more informationsNEWLINE## Copyright (C) Philippe Biondi <[email protected]>NEWLINE## Copyright (C) Gabriel Potter <[email protected]>NEWLINE## This program is published under a GPLv2 licenseNEWLINENEWLINE"""NEWLINEPython 2 and 3 link classes.NEWLINE"""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEimport base64NEWLINEimport binasciiNEWLINENEWLINEimport scapy.modules.six as sixNEWLINENEWLINE###########NEWLINE# Python3 #NEWLINE###########NEWLINENEWLINEdef cmp_to_key(mycmp):NEWLINE # TODO remove me once all 'key=cmp_to_key(..)' has been fixed in utils6.py, automaton.pyNEWLINE """Convert a cmp= function into a key= function.NEWLINE To use with sort()NEWLINENEWLINE e.g: def stg_cmp(a, b):NEWLINE return a == bNEWLINE list.sort(key=cmp_to_key(stg_cmp))NEWLINE """NEWLINE class K(object):NEWLINE def __init__(self, obj, *args):NEWLINE self.obj = objNEWLINE def __lt__(self, other):NEWLINE return mycmp(self.obj, other.obj) < 0NEWLINE def __gt__(self, other):NEWLINE return mycmp(self.obj, other.obj) > 0NEWLINE def __eq__(self, other):NEWLINE return mycmp(self.obj, other.obj) == 0NEWLINE def __le__(self, other):NEWLINE return mycmp(self.obj, other.obj) <= 0 NEWLINE def __ge__(self, other):NEWLINE return mycmp(self.obj, other.obj) >= 0NEWLINE def __ne__(self, other):NEWLINE return mycmp(self.obj, other.obj) != 0NEWLINE return KNEWLINENEWLINEdef cmp(a, b):NEWLINE """Old Python 2 function"""NEWLINE return (a > b) - (a < b)NEWLINENEWLINENEWLINEif six.PY2:NEWLINE def orb(x):NEWLINE """Return ord(x) when necessary."""NEWLINE if isinstance(x, basestring):NEWLINE return ord(x)NEWLINE return xNEWLINEelse:NEWLINE def orb(x):NEWLINE """Return ord(x) when necessary."""NEWLINE if isinstance(x, (bytes, str)):NEWLINE return ord(x)NEWLINE return xNEWLINENEWLINENEWLINEif six.PY2:NEWLINE def raw(x):NEWLINE """Convert a str, a packet to bytes"""NEWLINE if x is None:NEWLINE return NoneNEWLINE if hasattr(x, "__bytes__"):NEWLINE return x.__bytes__()NEWLINE try:NEWLINE return chr(x)NEWLINE except (ValueError, TypeError):NEWLINE return str(x)NEWLINENEWLINE def plain_str(x):NEWLINE """Convert basic byte objects to str"""NEWLINE return x if isinstance(x, basestring) else str(x)NEWLINENEWLINE def chb(x):NEWLINE """Same than chr() but encode as bytes.NEWLINENEWLINE """NEWLINE if isinstance(x, bytes):NEWLINE return xNEWLINE else:NEWLINE if hasattr(x, "__int__") and not isinstance(x, int):NEWLINE return bytes(chr(int(x)))NEWLINE return bytes(chr(x))NEWLINEelse:NEWLINE def raw(x):NEWLINE """Convert a str, an int, a list of ints, a packet to bytes"""NEWLINE try:NEWLINE return bytes(x)NEWLINE except TypeError:NEWLINE return bytes(x, encoding="utf8")NEWLINENEWLINE def plain_str(x):NEWLINE """Convert basic byte objects to str"""NEWLINE if isinstance(x, bytes):NEWLINE return x.decode('utf8')NEWLINE return x if isinstance(x, str) else str(x)NEWLINENEWLINE def chb(x):NEWLINE """Same than chr() but encode as bytes.NEWLINENEWLINE """NEWLINE if isinstance(x, bytes):NEWLINE return xNEWLINE else:NEWLINE if hasattr(x, "__int__") and not isinstance(x, int):NEWLINE return bytes([int(x)])NEWLINE return bytes([x])NEWLINENEWLINEdef bytes_hex(x):NEWLINE """Hexify a str or a bytes object"""NEWLINE return binascii.b2a_hex(raw(x))NEWLINENEWLINEdef hex_bytes(x):NEWLINE """De-hexify a str or a byte object"""NEWLINE return binascii.a2b_hex(raw(x))NEWLINENEWLINEdef base64_bytes(x):NEWLINE """Turn base64 into bytes"""NEWLINE if six.PY2:NEWLINE return base64.decodestring(x)NEWLINE return base64.decodebytes(raw(x))NEWLINENEWLINEdef bytes_base64(x):NEWLINE """Turn bytes into base64"""NEWLINE if six.PY2:NEWLINE return base64.encodestring(x).replace('\n', '')NEWLINE return base64.encodebytes(raw(x)).replace(b'\n', b'')NEWLINE |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ==============================================================================NEWLINE"""Tests for the cost analyzer."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEfrom tensorflow.python.framework import constant_opNEWLINEfrom tensorflow.python.framework import meta_graphNEWLINEfrom tensorflow.python.framework import opsNEWLINEfrom tensorflow.python.framework import test_utilNEWLINEfrom tensorflow.python.grappler import model_analyzerNEWLINEfrom tensorflow.python.ops import math_opsNEWLINEfrom tensorflow.python.platform import testNEWLINENEWLINENEWLINEclass PyWrapOptimizeGraphTest(test.TestCase):NEWLINENEWLINE @test_util.run_deprecated_v1NEWLINE def testBasic(self):NEWLINE """Make sure arguments can be passed correctly."""NEWLINE a = constant_op.constant([10, 11], name="a")NEWLINE b = constant_op.constant([10], name="b")NEWLINE c = math_ops.add(a, b, name="c")NEWLINE d = math_ops.add_n([a, c], name="d")NEWLINE train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)NEWLINE train_op.append(d)NEWLINE mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph())NEWLINENEWLINE report = model_analyzer.GenerateModelReport(mg)NEWLINENEWLINE # Check the report headersNEWLINE self.assertTrue(b"a [Const]" in report)NEWLINE self.assertTrue(b"a [Const]" in report)NEWLINE self.assertTrue(b"c [Add]" in report)NEWLINE self.assertTrue(b"d [AddN]" in report)NEWLINENEWLINE # Also print the report to make it easier to debugNEWLINE print("{}".format(report))NEWLINENEWLINE @test_util.run_deprecated_v1NEWLINE def testDebugMode(self):NEWLINE """Make sure arguments can be passed correctly."""NEWLINE a = constant_op.constant([10, 11], name="a")NEWLINE b = constant_op.constant([10], name="b")NEWLINE c = math_ops.add(a, b, name="c")NEWLINE train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)NEWLINE train_op.append(c)NEWLINE mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph())NEWLINENEWLINE report = model_analyzer.GenerateModelReport(mg, debug=True)NEWLINENEWLINE # Check the report headersNEWLINE self.assertTrue(b"input 0 (int32) has known value" in report)NEWLINE self.assertTrue(b"input 1 (int32) has known value" in report)NEWLINENEWLINE # Also print the report to make it easier to debugNEWLINE print("{}".format(report))NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE test.main()NEWLINE |
import ioNEWLINEimport jsonNEWLINEimport unittestNEWLINEimport tempfileNEWLINEfrom base64 import b64encodeNEWLINENEWLINEfrom ukbrest import appNEWLINEimport pandas as pdNEWLINENEWLINEfrom tests.settings import POSTGRESQL_ENGINENEWLINEfrom tests.utils import get_repository_path, DBTestNEWLINEfrom ukbrest.common.pheno2sql import Pheno2SQLNEWLINEfrom ukbrest.common.utils.auth import PasswordHasherNEWLINENEWLINENEWLINEclass TestRestApiPhenotype(DBTest):NEWLINE def _make_yaml_request(self, yaml_def, section, n_expected_rows, expected_columns):NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_def), 'data.yaml'),NEWLINE 'section': section,NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert pheno_file.shape == (n_expected_rows, len(expected_columns)), pheno_file.shapeNEWLINENEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE return pheno_fileNEWLINENEWLINE def setUp(self, filename=None, load_data=True, wipe_database=True, **kwargs):NEWLINE if wipe_database:NEWLINE super(TestRestApiPhenotype, self).setUp()NEWLINE NEWLINE # Load dataNEWLINE p2sql = self._get_p2sql(filename, **kwargs)NEWLINENEWLINE if load_data:NEWLINE p2sql.load_data()NEWLINENEWLINE app.app.config['pheno2sql'] = p2sqlNEWLINENEWLINE # ConfigureNEWLINE self.configureApp()NEWLINENEWLINE def _get_p2sql(self, filename, **kwargs):NEWLINE if filename is None:NEWLINE csv_file = get_repository_path('pheno2sql/example02.csv')NEWLINE elif isinstance(filename, (tuple, list)):NEWLINE csv_file = tuple([get_repository_path(f) for f in filename])NEWLINE elif isinstance(filename, str):NEWLINE csv_file = get_repository_path(filename)NEWLINE else:NEWLINE raise ValueError('filename unknown type')NEWLINENEWLINE if 'db_uri' not in kwargs:NEWLINE kwargs['db_uri'] = POSTGRESQL_ENGINENEWLINENEWLINE if 'n_columns_per_table' not in kwargs:NEWLINE kwargs['n_columns_per_table'] = 2NEWLINENEWLINE return Pheno2SQL(csv_file, **kwargs)NEWLINENEWLINE def configureApp(self, app_func=None):NEWLINE app.app.config['testing'] = TrueNEWLINE app.app.config['auth'] = NoneNEWLINENEWLINE if app_func is not None:NEWLINE app_func(app.app)NEWLINENEWLINE self.app = app.app.test_client()NEWLINENEWLINE def configureAppWithAuth(self, user_pass_line):NEWLINE f = tempfile.NamedTemporaryFile(delete=False)NEWLINE f.close()NEWLINENEWLINE with open(f.name, 'w') as fi:NEWLINE fi.write(user_pass_line)NEWLINENEWLINE ph = PasswordHasher(f.name, method='pbkdf2:sha256')NEWLINENEWLINE def conf(a):NEWLINE a.config['auth'] = ph.setup_http_basic_auth()NEWLINENEWLINE self.configureApp(conf)NEWLINENEWLINE def _get_http_basic_auth_header(self, user, password):NEWLINE return {'Authorization': 'Basic %s' % b64encode(f'{user}:{password}'.encode()).decode("ascii")}NEWLINENEWLINE def test_not_found(self):NEWLINE response = self.app.get('/ukbrest/api/v1.0/')NEWLINE assert response.status_code == 404, response.status_codeNEWLINENEWLINE def test_phenotype_fields(self):NEWLINE # PrepareNEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype/fields')NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE fields = json.loads(response.data.decode('utf-8'))NEWLINE assert len(fields) == 8NEWLINENEWLINE def test_phenotype_fields_http_auth_no_credentials(self):NEWLINE # PrepareNEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype/fields',NEWLINE # headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_fields_http_auth_with_credentials(self):NEWLINE # PrepareNEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype/fields',NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE fields = json.loads(response.data.decode('utf-8'))NEWLINE assert len(fields) == 8NEWLINENEWLINE def test_phenotype_fields_http_auth_multiple_users(self):NEWLINE # PrepareNEWLINE self.configureAppWithAuth(NEWLINE 'user: thepassword2\n'NEWLINE 'another_user: another_password'NEWLINE )NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype/fields',NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE fields = json.loads(response.data.decode('utf-8'))NEWLINE assert len(fields) == 8NEWLINENEWLINE # Run 2NEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype/fields',NEWLINE headers=self._get_http_basic_auth_header('another_user', 'another_password'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE fields = json.loads(response.data.decode('utf-8'))NEWLINE assert len(fields) == 8NEWLINENEWLINE def test_phenotype_query_single_column_format_csv(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE csv_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), index_col='eid', dtype=str)NEWLINE assert csv_file is not NoneNEWLINE assert not csv_file.emptyNEWLINE assert csv_file.shape == (4, 1)NEWLINENEWLINE assert csv_file.index.name == 'eid'NEWLINE assert len(csv_file.index) == 4NEWLINE assert all(x in csv_file.index for x in range(1, 4 + 1))NEWLINENEWLINE assert len(csv_file.columns) == len(columns)NEWLINE assert all(x in columns for x in csv_file.columns)NEWLINENEWLINE assert csv_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert csv_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert csv_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert csv_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE def test_phenotype_query_error_column_does_not_exist(self):NEWLINE # PrepareNEWLINE columns = ['nonexistent_column']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINENEWLINE # with self.app:NEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 400, response.status_codeNEWLINE data = json.load(io.StringIO(response.data.decode('utf-8')))NEWLINENEWLINE assert 'message' in data, dataNEWLINE assert 'column "nonexistent_column" does not exist' in data['message'], data['message']NEWLINENEWLINE assert 'output' not in data, dataNEWLINENEWLINE def test_phenotype_query_error_column_does_not_exist_standard_column_name(self):NEWLINE # PrepareNEWLINE columns = ['c999_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINENEWLINE # with self.app:NEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 400, response.status_codeNEWLINE data = json.load(io.StringIO(response.data.decode('utf-8')))NEWLINENEWLINE assert 'status_code' in data, dataNEWLINE assert data['status_code'] == 400, data['status_code']NEWLINENEWLINE assert 'error_type' in data, dataNEWLINE assert data['error_type'] == 'SQL_EXECUTION_ERROR'NEWLINENEWLINE assert 'message' in data, dataNEWLINE assert 'column "c999_0_0" does not exist' in data['message'], data['message']NEWLINENEWLINE assert 'output' not in data, dataNEWLINENEWLINE def test_phenotype_query_error_cannot_connect_to_database(self):NEWLINE # PrepareNEWLINE self.setUp(load_data=False, db_uri='postgresql://test:test@wronghost:5432/ukb')NEWLINENEWLINE columns = ['c21_0_0', 'invalid value here']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINENEWLINE # with self.app:NEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 500, response.status_codeNEWLINE data = json.load(io.StringIO(response.data.decode('utf-8')))NEWLINENEWLINE assert 'status_code' in data, dataNEWLINE assert data['status_code'] == 500, data['status_code']NEWLINENEWLINE assert 'error_type' in data, dataNEWLINE assert data['error_type'] == 'UNKNOWN', data['error_type']NEWLINENEWLINE assert 'message' in data, dataNEWLINE assert 'psycopg2.OperationalError' in data['message'], data['message']NEWLINE assert 'wronghost' in data['message'], data['message']NEWLINENEWLINE def test_phenotype_query_multiple_column_format_csv(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE csv_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), index_col='eid', dtype=str)NEWLINE assert csv_file is not NoneNEWLINE assert not csv_file.emptyNEWLINE assert csv_file.shape == (4, 2)NEWLINENEWLINE assert csv_file.index.name == 'eid'NEWLINE assert len(csv_file.index) == 4NEWLINE assert all(x in csv_file.index for x in range(1, 4 + 1))NEWLINENEWLINE assert len(csv_file.columns) == len(columns)NEWLINE assert all(x in columns for x in csv_file.columns)NEWLINENEWLINE assert csv_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert csv_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert csv_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert csv_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE assert csv_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert csv_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert csv_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert csv_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_multiple_column_format_pheno(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_multiple_column_renaming(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0 as c21', 'c31_0_0 c31', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c21', 'c31', 'c48_0_0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21'] == 'Option number 4'NEWLINENEWLINE assert pheno_file.loc[1, 'c31'] == '2012-01-05'NEWLINE assert pheno_file.loc[2, 'c31'] == '2015-12-30'NEWLINE assert pheno_file.loc[3, 'c31'] == '2007-03-19'NEWLINE assert pheno_file.loc[4, 'c31'] == '2002-05-09'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_filtering_with_column_no_mentioned_in_select(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0 as c21', 'c21_2_0 c21_2']NEWLINE filtering = ["c46_0_0 < 0", "c48_0_0 > '2011-01-01'"]NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'filters': filtering,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape[0] == 2NEWLINE assert pheno_file.shape[1] == 2 + 1 # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 2NEWLINE assert all(x in pheno_file.index for x in (1, 2))NEWLINENEWLINE expected_columns = ['IID'] + ['c21', 'c21_2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINENEWLINE assert pheno_file.loc[1, 'c21'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21'] == 'Option number 2'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_2'] == 'Yes'NEWLINE assert pheno_file.loc[2, 'c21_2'] == 'No'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan_using_columns_renaming_with_as(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0 as c34', 'c46_0_0 as c46', 'c47_0_0 as c47']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c34', 'c46', 'c47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34'] == '21'NEWLINE assert pheno_file.loc[2, 'c34'] == '12'NEWLINE assert pheno_file.loc[3, 'c34'] == '1'NEWLINE assert pheno_file.loc[4, 'c34'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46'] == '-9', pheno_file.loc[1, 'c46']NEWLINE assert pheno_file.loc[2, 'c46'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan_using_columns_renaming_with_as_uppercase(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0 as c34', 'c46_0_0 AS c46', 'c47_0_0 as c47']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c34', 'c46', 'c47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34'] == '21'NEWLINE assert pheno_file.loc[2, 'c34'] == '12'NEWLINE assert pheno_file.loc[3, 'c34'] == '1'NEWLINE assert pheno_file.loc[4, 'c34'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46'] == '-9', pheno_file.loc[1, 'c46']NEWLINE assert pheno_file.loc[2, 'c46'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan_using_columns_renaming_with_space(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0 as c34', 'c46_0_0 c46', 'c47_0_0 as c47']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c34', 'c46', 'c47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34'] == '21'NEWLINE assert pheno_file.loc[2, 'c34'] == '12'NEWLINE assert pheno_file.loc[3, 'c34'] == '1'NEWLINE assert pheno_file.loc[4, 'c34'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46'] == '-9', pheno_file.loc[1, 'c46']NEWLINE assert pheno_file.loc[2, 'c46'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_integer_values_with_nan_using_reg_exp(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example06_nan_integer.csv')NEWLINENEWLINE columns = ['c34_0_0 as c34']NEWLINE reg_exp_columns = ['c4[67]_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c34', 'c46_0_0', 'c47_0_0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34'] == '21'NEWLINE assert pheno_file.loc[2, 'c34'] == '12'NEWLINE assert pheno_file.loc[3, 'c34'] == '1'NEWLINE assert pheno_file.loc[4, 'c34'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9', pheno_file.loc[1, 'c46']NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE def test_phenotype_query_multiple_column_create_field_from_integer(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0', 'c46_0_0^2 as squared']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 4 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x.split()[-1] in pheno_file.columns for x in expected_columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE # square results in float typeNEWLINE assert pheno_file.loc[1, 'squared'] == '81.0'NEWLINE assert pheno_file.loc[2, 'squared'] == '4.0'NEWLINE assert pheno_file.loc[3, 'squared'] == '49.0'NEWLINE assert pheno_file.loc[4, 'squared'] == '16.0'NEWLINENEWLINE def test_phenotype_query_multiple_column_create_field_from_integer_return_integer(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0', 'c46_0_0 + 1 as sum']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 4 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x.split()[-1] in pheno_file.columns for x in expected_columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE # square results in float typeNEWLINE assert pheno_file.loc[1, 'sum'] == '-8'NEWLINE assert pheno_file.loc[2, 'sum'] == '-1'NEWLINE assert pheno_file.loc[3, 'sum'] == '-6'NEWLINE assert pheno_file.loc[4, 'sum'] == '5'NEWLINENEWLINE def test_phenotype_query_multiple_column_create_field_from_float(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0', 'c47_0_0^2 as squared']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 4 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x.split()[-1] in pheno_file.columns for x in expected_columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c34_0_0'] == '21'NEWLINE assert pheno_file.loc[2, 'c34_0_0'] == '12'NEWLINE assert pheno_file.loc[3, 'c34_0_0'] == '1'NEWLINE assert pheno_file.loc[4, 'c34_0_0'] == '17'NEWLINENEWLINE assert pheno_file.loc[1, 'c46_0_0'] == '-9'NEWLINE assert pheno_file.loc[2, 'c46_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c46_0_0'] == '-7'NEWLINE assert pheno_file.loc[4, 'c46_0_0'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINE assert pheno_file.loc[3, 'c47_0_0'] == '-5.32471'NEWLINE assert pheno_file.loc[4, 'c47_0_0'] == '55.19832'NEWLINENEWLINE # square results in float typeNEWLINE assert pheno_file.loc[1, 'squared'] == '2075.1778489744'NEWLINE assert pheno_file.loc[2, 'squared'] == '0.3075922521'NEWLINE assert pheno_file.loc[3, 'squared'] == '28.3525365841'NEWLINE assert pheno_file.loc[4, 'squared'] == '3046.8545308224'NEWLINENEWLINE def test_phenotype_query_multiple_column_create_field_from_str(self):NEWLINE # PrepareNEWLINE columns = ['c34_0_0', 'c46_0_0', 'c47_0_0', 'c21_0_0', '(c21_0_0 || \' end \' || eid) as result']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 5 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x.split()[-1] in pheno_file.columns for x in expected_columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE # square results in float typeNEWLINE assert pheno_file.loc[1, 'result'] == 'Option number 1 end 1'NEWLINE assert pheno_file.loc[2, 'result'] == 'Option number 2 end 2'NEWLINE assert pheno_file.loc[3, 'result'] == 'Option number 3 end 3'NEWLINE assert pheno_file.loc[4, 'result'] == 'Option number 4 end 4'NEWLINENEWLINE def test_phenotype_query_format_pheno_missing_data(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c21_1_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE # na_values='' is necessary to not overwrite NA strings hereNEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t',NEWLINE na_values='', keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_1_0'] == 'No response'NEWLINE assert pheno_file.loc[2, 'c21_1_0'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c21_1_0'] == 'Of course'NEWLINE assert pheno_file.loc[4, 'c21_1_0'] == 'I don\'t know'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_format_pheno_missing_date(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example05_missing_date.csv')NEWLINENEWLINE columns = ['c21_0_0', 'c21_1_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'text/plink2'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE # na_values='' is necessary to not overwrite NA strings hereNEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t',NEWLINE na_values='', keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_multiple_column_no_format(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (4, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 4NEWLINE assert all(x in pheno_file.index for x in range(1, 4 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2010-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '2011-02-15'NEWLINENEWLINE def test_phenotype_query_multiple_column_format_not_supported(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters, headers={'accept': 'application/json'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 400, response.status_codeNEWLINE data = json.load(io.StringIO(response.data.decode('utf-8')))NEWLINENEWLINE assert 'status_code' in data, dataNEWLINE assert data['status_code'] == 400, data['status_code']NEWLINENEWLINE assert 'error_type' in data, dataNEWLINE assert data['error_type'] == 'UNKNOWN', data['error_type']NEWLINENEWLINE assert 'message' in data, dataNEWLINE assert 'are supported' in str(data['message']), data['message']NEWLINE assert 'text/plink2' in str(data['message']), data['message']NEWLINENEWLINE def test_phenotype_query_with_filtering(self):NEWLINE # PrepareNEWLINE columns = ['c21_0_0', 'c21_2_0', 'c47_0_0', 'c48_0_0']NEWLINE filtering = ["c48_0_0 > '2011-01-01'", "c21_2_0 <> ''"]NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'filters': filtering,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape[0] == 2NEWLINE assert pheno_file.shape[1] == 4 + 1 # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 2NEWLINE assert all(x in pheno_file.index for x in (1, 2))NEWLINENEWLINE expected_columns = ['IID'] + columnsNEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_2_0'] == 'Yes'NEWLINE assert pheno_file.loc[2, 'c21_2_0'] == 'No'NEWLINENEWLINE assert pheno_file.loc[1, 'c47_0_0'] == '45.55412'NEWLINE assert pheno_file.loc[2, 'c47_0_0'] == '-0.55461'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2011-08-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2016-11-30'NEWLINENEWLINE def test_phenotype_query_columns_with_regular_expression_and_standard_columns(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example09_with_arrays.csv')NEWLINENEWLINE columns = ['c21_0_0', 'c48_0_0']NEWLINE reg_exp_columns = ['c84_0_\d+']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 5 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 5NEWLINE assert all(x in pheno_file.index for x in range(1, 5 + 1))NEWLINENEWLINE expected_columns = ['IID'] + columns + ['c84_0_0', 'c84_0_1', 'c84_0_2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINE assert pheno_file.loc[5, 'IID'] == '5'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == "Option number 4"NEWLINE assert pheno_file.loc[5, 'c21_0_0'] == "Option number 5"NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2010-07-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2017-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2020-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '1990-02-15'NEWLINE assert pheno_file.loc[5, 'c48_0_0'] == '1999-10-11'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_0'] == '11', pheno_file.loc[1, 'c84_0_0']NEWLINE assert pheno_file.loc[2, 'c84_0_0'] == '-21'NEWLINE assert pheno_file.loc[3, 'c84_0_0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'c84_0_0'] == '41'NEWLINE assert pheno_file.loc[5, 'c84_0_0'] == '51'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_1'] == '1', pheno_file.loc[1, 'c84_0_1']NEWLINE assert pheno_file.loc[2, 'c84_0_1'] == '99'NEWLINE assert pheno_file.loc[3, 'c84_0_1'] == '98'NEWLINE assert pheno_file.loc[4, 'c84_0_1'] == '-37'NEWLINE assert pheno_file.loc[5, 'c84_0_1'] == '36'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_2'] == '999'NEWLINE assert pheno_file.loc[2, 'c84_0_2'] == '152'NEWLINE assert pheno_file.loc[3, 'c84_0_2'] == '-68'NEWLINE assert pheno_file.loc[4, 'c84_0_2'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c84_0_2'] == '-445'NEWLINENEWLINE def test_phenotype_query_columns_with_regular_expression_only(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example09_with_arrays.csv')NEWLINENEWLINE reg_exp_columns = ['c84_0_\d+']NEWLINENEWLINE parameters = {NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 3 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 5NEWLINE assert all(x in pheno_file.index for x in range(1, 5 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c84_0_0', 'c84_0_1', 'c84_0_2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINE assert pheno_file.loc[5, 'IID'] == '5'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_0'] == '11', pheno_file.loc[1, 'c84_0_0']NEWLINE assert pheno_file.loc[2, 'c84_0_0'] == '-21'NEWLINE assert pheno_file.loc[3, 'c84_0_0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'c84_0_0'] == '41'NEWLINE assert pheno_file.loc[5, 'c84_0_0'] == '51'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_1'] == '1', pheno_file.loc[1, 'c84_0_1']NEWLINE assert pheno_file.loc[2, 'c84_0_1'] == '99'NEWLINE assert pheno_file.loc[3, 'c84_0_1'] == '98'NEWLINE assert pheno_file.loc[4, 'c84_0_1'] == '-37'NEWLINE assert pheno_file.loc[5, 'c84_0_1'] == '36'NEWLINENEWLINE assert pheno_file.loc[1, 'c84_0_2'] == '999'NEWLINE assert pheno_file.loc[2, 'c84_0_2'] == '152'NEWLINE assert pheno_file.loc[3, 'c84_0_2'] == '-68'NEWLINE assert pheno_file.loc[4, 'c84_0_2'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c84_0_2'] == '-445'NEWLINENEWLINE def test_phenotype_query_columns_pheno2sql_instance_not_loaded(self):NEWLINE """This test uses a different Pheno2SQL instance without previous loading"""NEWLINENEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 8 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert len(pheno_file.index) == 5NEWLINE assert all(x in pheno_file.index for x in range(1, 5 + 1))NEWLINENEWLINE expected_columns = ['IID'] + ['c21_0_0', 'c21_1_0', 'c48_0_0', 'c120', 'c150', 'c100_0_0', 'c100_1_0', 'c100_2_0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1, 'IID'] == '1'NEWLINE assert pheno_file.loc[2, 'IID'] == '2'NEWLINE assert pheno_file.loc[3, 'IID'] == '3'NEWLINE assert pheno_file.loc[4, 'IID'] == '4'NEWLINE assert pheno_file.loc[5, 'IID'] == '5'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_0_0'] == 'Option number 1'NEWLINE assert pheno_file.loc[2, 'c21_0_0'] == 'Option number 2'NEWLINE assert pheno_file.loc[3, 'c21_0_0'] == 'Option number 3'NEWLINE assert pheno_file.loc[4, 'c21_0_0'] == 'Option number 4'NEWLINE assert pheno_file.loc[5, 'c21_0_0'] == 'Option number 5'NEWLINENEWLINE assert pheno_file.loc[1, 'c21_1_0'] == 'No response'NEWLINE assert pheno_file.loc[2, 'c21_1_0'] == 'NA'NEWLINE assert pheno_file.loc[3, 'c21_1_0'] == 'Of course'NEWLINE assert pheno_file.loc[4, 'c21_1_0'] == "I don't know"NEWLINE assert pheno_file.loc[5, 'c21_1_0'] == 'Maybe'NEWLINENEWLINE assert pheno_file.loc[1, 'c48_0_0'] == '2010-07-14'NEWLINE assert pheno_file.loc[2, 'c48_0_0'] == '2017-11-30'NEWLINE assert pheno_file.loc[3, 'c48_0_0'] == '2020-01-01'NEWLINE assert pheno_file.loc[4, 'c48_0_0'] == '1990-02-15'NEWLINE assert pheno_file.loc[5, 'c48_0_0'] == '1999-10-11'NEWLINENEWLINE assert pheno_file.loc[1, 'c100_0_0'] == '-9', pheno_file.loc[1, 'c100_0_0']NEWLINE assert pheno_file.loc[2, 'c100_0_0'] == '-2'NEWLINE assert pheno_file.loc[3, 'c100_0_0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'c100_0_0'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c100_0_0'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[1, 'c100_1_0'] == '3', pheno_file.loc[1, 'c100_1_0']NEWLINE assert pheno_file.loc[2, 'c100_1_0'] == '3'NEWLINE assert pheno_file.loc[3, 'c100_1_0'] == '-4'NEWLINE assert pheno_file.loc[4, 'c100_1_0'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c100_1_0'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[1, 'c100_2_0'] == 'NA', pheno_file.loc[1, 'c100_2_0']NEWLINE assert pheno_file.loc[2, 'c100_2_0'] == '1'NEWLINE assert pheno_file.loc[3, 'c100_2_0'] == '-10'NEWLINE assert pheno_file.loc[4, 'c100_2_0'] == 'NA'NEWLINE assert pheno_file.loc[5, 'c100_2_0'] == 'NA'NEWLINENEWLINE def test_phenotype_query_http_basic_auth_is_null(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE def configure_http_auth(theapp):NEWLINE theapp.config['auth'] = NoneNEWLINENEWLINE self.configureApp(configure_http_auth)NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE def test_phenotype_query_http_basic_auth_no_user_pass(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get('/ukbrest/api/v1.0/phenotype', query_string=parameters)NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_query_http_basic_auth_with_user_pass(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters,NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', na_values='',NEWLINE keep_default_na=False, index_col='FID', dtype=str)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 8 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE def test_phenotype_query_http_basic_auth_with_wrong_pass(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE self.configureAppWithAuth('user: anotherpass')NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters,NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2')NEWLINE )NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_query_http_basic_auth_with_wrong_user(self):NEWLINE # PrepareNEWLINE csv01 = get_repository_path('pheno2sql/example08_01.csv')NEWLINE csv02 = get_repository_path('pheno2sql/example08_02.csv')NEWLINE csvs = (csv01, csv02)NEWLINENEWLINE # first load dataNEWLINE self.setUp(csvs)NEWLINENEWLINE # then create another instance without executing load_data methodNEWLINE self.setUp(csvs, load_data=False, wipe_database=False)NEWLINENEWLINE self.configureAppWithAuth('anotheruser: thepassword2')NEWLINENEWLINE columns = ['c48_0_0', 'c120_0_0 as c120', 'c150_0_0 c150']NEWLINE reg_exp_columns = ['c21_[01]_0', 'c100_\d_0']NEWLINENEWLINE parameters = {NEWLINE 'columns': columns,NEWLINE 'ecolumns': reg_exp_columns,NEWLINE }NEWLINENEWLINE # RunNEWLINE response = self.app.get(NEWLINE '/ukbrest/api/v1.0/phenotype',NEWLINE query_string=parameters,NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE # unauthorizedNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_query_yaml_get_covariates(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE covariates:NEWLINE field_name_34: c34_0_0NEWLINE field_name_47: c47_0_0NEWLINE NEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0NEWLINE instance2: c21_2_0NEWLINE """NEWLINENEWLINE # RunNEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000020, 1000030, 1000040, 1000050))NEWLINENEWLINE expected_columns = ['IID'] + ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[1000010, 'field_name_47'] == '41.55312'NEWLINENEWLINE assert pheno_file.loc[1000020, 'IID'] == '1000020'NEWLINE assert pheno_file.loc[1000020, 'field_name_34'] == '34'NEWLINE assert pheno_file.loc[1000020, 'field_name_47'] == '-10.51461'NEWLINENEWLINE assert pheno_file.loc[1000030, 'IID'] == '1000030'NEWLINE assert pheno_file.loc[1000030, 'field_name_34'] == '0'NEWLINE assert pheno_file.loc[1000030, 'field_name_47'] == '-35.31471'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[1000040, 'field_name_47'] == '5.20832'NEWLINENEWLINE assert pheno_file.loc[1000050, 'IID'] == '1000050'NEWLINE assert pheno_file.loc[1000050, 'field_name_34'] == '-4'NEWLINE assert pheno_file.loc[1000050, 'field_name_47'] == 'NA'NEWLINENEWLINE def test_phenotype_query_yaml_get_covariates_http_auth_with_no_credentials(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE yaml_data = b"""NEWLINE covariates:NEWLINE field_name_34: c34_0_0NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0NEWLINE instance2: c21_2_0NEWLINE """NEWLINENEWLINE # RunNEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 401, response.status_codeNEWLINENEWLINE def test_phenotype_query_yaml_get_covariates_http_auth_with_credentials(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE self.configureAppWithAuth('user: thepassword2')NEWLINENEWLINE yaml_data = b"""NEWLINE covariates:NEWLINE field_name_34: c34_0_0NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0NEWLINE instance2: c21_2_0NEWLINE """NEWLINENEWLINE # RunNEWLINE response = self.app.post(NEWLINE '/ukbrest/api/v1.0/query',NEWLINE data={NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE },NEWLINE headers=self._get_http_basic_auth_header('user', 'thepassword2'),NEWLINE )NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 2 + 1) # plus IIDNEWLINENEWLINE def test_phenotype_query_yaml_get_fields(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE # RunNEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (5, 3 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000020, 1000030, 1000040, 1000050))NEWLINENEWLINE expected_columns = ['IID'] + ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == 'NA'NEWLINENEWLINE def test_phenotype_query_yaml_filter_samples_with_include_only(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINE NEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 2NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000040)), pheno_file.index.tolist()NEWLINENEWLINE expected_columns = ['IID'] + ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == 'NA'NEWLINENEWLINE #NEWLINE # Ask covariatesNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000040))NEWLINENEWLINE expected_columns = ['IID'] + ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[1000010, 'field_name_47'] == '41.55312'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[1000040, 'field_name_47'] == '5.20832'NEWLINENEWLINE def test_phenotype_query_yaml_filter_samples_condition_breaking_for_fields_and_covariates(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINE - c46_0_0 < 0 or c46_0_0 = 4 or c46_0_0 = 1NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 2NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3 + 1), pheno_file.shape # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000040)), pheno_file.index.tolist()NEWLINENEWLINE expected_columns = ['IID'] + ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == 'NA'NEWLINENEWLINE #NEWLINE # Ask covariatesNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE })NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), sep='\t', index_col='FID', dtype=str,NEWLINE na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 2 + 1) # plus IIDNEWLINENEWLINE assert pheno_file.index.name == 'FID'NEWLINE assert all(x in pheno_file.index for x in (1000010, 1000040))NEWLINENEWLINE expected_columns = ['IID'] + ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINE # column orderNEWLINE assert pheno_file.columns.tolist()[0] == 'IID'NEWLINENEWLINE assert pheno_file.loc[1000010, 'IID'] == '1000010'NEWLINE assert pheno_file.loc[1000010, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[1000010, 'field_name_47'] == '41.55312'NEWLINENEWLINE assert pheno_file.loc[1000040, 'IID'] == '1000040'NEWLINE assert pheno_file.loc[1000040, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[1000040, 'field_name_47'] == '5.20832'NEWLINENEWLINE def test_phenotype_query_yaml_specify_bgenie_format(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE 'missing_code': '-999',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'instance0'] == '-999', pheno_file.loc[0, 'instance0']NEWLINE assert pheno_file.loc[0, 'instance1'] == '-999'NEWLINE assert pheno_file.loc[0, 'instance2'] == '-999'NEWLINENEWLINE assert pheno_file.loc[1, 'instance0'] == '-999'NEWLINE assert pheno_file.loc[1, 'instance1'] == '-999'NEWLINE assert pheno_file.loc[1, 'instance2'] == '-999'NEWLINENEWLINE assert pheno_file.loc[2, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[2, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[2, 'instance2'] == '-999'NEWLINENEWLINE assert pheno_file.loc[3, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[3, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[3, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[4, 'instance0'] == '-999'NEWLINE assert pheno_file.loc[4, 'instance1'] == '-999'NEWLINE assert pheno_file.loc[4, 'instance2'] == '-999'NEWLINENEWLINE #NEWLINE # Ask covariatesNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE 'missing_code': '-999',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 2)NEWLINENEWLINE expected_columns = ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'field_name_34'] == '-999'NEWLINE assert pheno_file.loc[0, 'field_name_47'] == '-999'NEWLINENEWLINE assert pheno_file.loc[1, 'field_name_34'] == '-999'NEWLINE assert pheno_file.loc[1, 'field_name_47'] == '-999'NEWLINENEWLINE assert pheno_file.loc[2, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[2, 'field_name_47'] == '5.20832'NEWLINENEWLINE assert pheno_file.loc[3, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[3, 'field_name_47'] == '41.55312'NEWLINENEWLINE assert pheno_file.loc[4, 'field_name_34'] == '-999'NEWLINE assert pheno_file.loc[4, 'field_name_47'] == '-999'NEWLINENEWLINE def test_phenotype_query_yaml_specify_csv_format(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 2NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE #NEWLINE # Ask covariatesNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'covariates',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 2)NEWLINENEWLINE expected_columns = ['field_name_34', 'field_name_47']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000040, 'field_name_34'] == '3'NEWLINE assert pheno_file.loc[1000040, 'field_name_47'] == '5.20832'NEWLINENEWLINE assert pheno_file.loc[1000010, 'field_name_34'] == '-33'NEWLINE assert pheno_file.loc[1000010, 'field_name_47'] == '41.55312'NEWLINENEWLINE def test_phenotype_query_yaml_specify_bgenie_format_missing_code_default(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'instance0'] == 'NA'NEWLINE assert pheno_file.loc[0, 'instance1'] == 'NA'NEWLINE assert pheno_file.loc[0, 'instance2'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[1, 'instance0'] == 'NA'NEWLINE assert pheno_file.loc[1, 'instance1'] == 'NA'NEWLINE assert pheno_file.loc[1, 'instance2'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[2, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[2, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[2, 'instance2'] == 'NA'NEWLINENEWLINE assert pheno_file.loc[3, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[3, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[3, 'instance2'] == 'Yes'NEWLINENEWLINE assert pheno_file.loc[4, 'instance0'] == 'NA'NEWLINE assert pheno_file.loc[4, 'instance1'] == 'NA'NEWLINE assert pheno_file.loc[4, 'instance2'] == 'NA'NEWLINENEWLINE def test_phenotype_query_yaml_specify_csv_format_missing_code_changed(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example10/example10_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example10/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c47_0_0 > 0NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE fields:NEWLINE instance0: c21_0_0NEWLINE instance1: c21_1_0 NEWLINE instance2: c21_2_0 NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 2NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'fields',NEWLINE 'missing_code': '-999',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['instance0', 'instance1', 'instance2']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000040, 'instance0'] == 'Option number 4'NEWLINE assert pheno_file.loc[1000040, 'instance1'] == "I don't know"NEWLINE assert pheno_file.loc[1000040, 'instance2'] == '-999'NEWLINENEWLINE assert pheno_file.loc[1000010, 'instance0'] == 'Option number 1'NEWLINE assert pheno_file.loc[1000010, 'instance1'] == 'No response'NEWLINE assert pheno_file.loc[1000010, 'instance2'] == 'Yes'NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_first_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=10)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c34_0_0 >= -5NEWLINE NEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [N308]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == '0' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == '1' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_second_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=20)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c34_0_0 >= -5NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == '1' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_different_filter_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=20)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c31_0_0 > '2001-01-01'NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_filter_includes_nulls_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=20)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c31_0_0 is null or c31_0_0 > '2001-01-01'NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_multiple_filters_using_like_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=20)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c31_0_0 is null or c31_0_0 > '2001-01-01'NEWLINE - c21_2_0 not like '%%obab%%'NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_fields_in_filters_are_in_different_tables_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c21_1_0 not like '%%respo%%'NEWLINE - c47_0_0 > 0NEWLINENEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [Q750]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == '1' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == 'NA' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_different_data_field_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - eid not in (select eid from events where field_id = 84 and event in ('Q750'))NEWLINE NEWLINE data:NEWLINE disease0:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [1114]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['disease0']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'disease0'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'disease0'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'disease0'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'disease0'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'disease0'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'disease0'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_different_disease_name_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - eid not in (select eid from events where field_id = 84 and event in ('Q750'))NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [1114]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_coding_not_list_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - eid not in (select eid from events where field_id = 84 and event in ('Q750'))NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == 'NA' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_coding_not_list_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - eid not in (select eid from events where field_id = 84 and event in ('Q750'))NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE # assert pheno_file.loc[1000030, 'another_disease_name'] == '0' # 1000030NEWLINE # assert pheno_file.loc['1000040', 'another_disease_name'] == 'NA' # 1000040NEWLINE # assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '0' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_many_codings_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe')NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [1114, 1701]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == '0' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_many_codings_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe')NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [1114, 1701]NEWLINE """NEWLINENEWLINE # text/csv does not fetch all samples in 'samples' table by defaultNEWLINE N_EXPECTED_SAMPLES = 5NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE # assert pheno_file.loc['1000050', 'another_disease_name'] == 'NA' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '0' # 1000030NEWLINE # assert pheno_file.loc['1000040', 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '0' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_many_data_fields_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c21_2_0 is null or lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '1' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_by_coding_many_data_fields_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - c21_2_0 is null or lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 7NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000040, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_filters_not_referencing_table_bgenie(self):NEWLINE """This test forces a global table to obtain eid from for controls"""NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - 1 = 1NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '1' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_filters_not_referencing_table_csv(self):NEWLINE """This test forces a global table to obtain eid from for controls"""NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - 1 = 1NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 7NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000040, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_no_filters_csv(self):NEWLINE """This test forces a global table to obtain eid from for controls"""NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 7NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000040, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_disease_many_columns_bgenie(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 > -10NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE second_column:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 6NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/bgenie'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_table(io.StringIO(response.data.decode('utf-8')), sep=' ', header=0,NEWLINE dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name', 'second_column', 'third_column']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[0, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[2, 'another_disease_name'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'another_disease_name'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[5, 'another_disease_name'] == '1' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE assert pheno_file.loc[0, 'second_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'second_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[2, 'second_column'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'second_column'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'second_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'second_column'] == '0' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE assert pheno_file.loc[0, 'third_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1, 'third_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[2, 'third_column'] == 'NA' # 1000040NEWLINE assert pheno_file.loc[3, 'third_column'] == 'NA' # 1000010NEWLINE assert pheno_file.loc[4, 'third_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[5, 'third_column'] == '1' # 1000070NEWLINE # 1000060 is "not genotyped" (it is not listed in BGEN's samples file)NEWLINENEWLINE def test_phenotype_query_yaml_disease_many_columns_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 > -10NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE case_control:NEWLINE 85:NEWLINE coding: [978, 1701]NEWLINE 84:NEWLINE coding: [Z876, Z678]NEWLINE second_column:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name', 'second_column', 'third_column']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINENEWLINE assert pheno_file.loc[1000050, 'second_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'second_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'second_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'second_column'] == '0' # 1000070NEWLINENEWLINE assert pheno_file.loc[1000050, 'third_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'third_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'third_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'third_column'] == '1' # 1000070NEWLINENEWLINE def test_phenotype_query_yaml_disease_sql_alone_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10NEWLINENEWLINE data:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 > 0NEWLINE 0: c46_0_0 < 0NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['mydisease']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'mydisease'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'mydisease'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'mydisease'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'mydisease'] == '1' # 1000070NEWLINENEWLINE @unittest.skip("We should check if there are repeated eid values, like in this case, due to bad specification of conditions for categories")NEWLINE def test_phenotype_query_yaml_disease_sql_conflicting_duplicated_samples_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10NEWLINENEWLINE data:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 >= 1NEWLINE 0: c46_0_0 <= 1NEWLINE """NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 400, response.status_codeNEWLINENEWLINE def test_phenotype_query_yaml_disease_sql_with_many_columns_csv(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # Here I emulate case_control with sqlNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 > -10NEWLINENEWLINE data:NEWLINE another_disease_name:NEWLINE sql:NEWLINE 1: >NEWLINE eid in (select eid from events where field_id = 85 and event in ('978', '1701'))NEWLINE ORNEWLINE eid in (select eid from events where field_id = 84 and event in ('Z876', 'Z678'))NEWLINE 0: >NEWLINE eid not in (NEWLINE (select eid from events where field_id = 85 and event in ('978', '1701'))NEWLINE unionNEWLINE (select eid from events where field_id = 84 and event in ('Z876', 'Z678'))NEWLINE )NEWLINE second_column:NEWLINE case_control:NEWLINE 85:NEWLINE coding: 1114NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 3), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name', 'second_column', 'third_column']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINENEWLINE assert pheno_file.loc[1000050, 'second_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'second_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'second_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'second_column'] == '0' # 1000070NEWLINENEWLINE assert pheno_file.loc[1000050, 'third_column'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'third_column'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'third_column'] == '1' # 1000020NEWLINE assert pheno_file.loc[1000070, 'third_column'] == '1' # 1000070NEWLINENEWLINE def test_phenotype_query_yaml_disease_sql_no_filters_csv(self):NEWLINE """This test forces a global table to obtain eid from for controls"""NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case the filters are not necessary, but it is forced to avoid a problem with joining that willNEWLINE # be tested in another unit testNEWLINE yaml_data = b"""NEWLINE data:NEWLINE another_disease_name:NEWLINE sql:NEWLINE 1: >NEWLINE eid in (select eid from events where field_id = 85 and event in ('978', '1701'))NEWLINE ORNEWLINE eid in (select eid from events where field_id = 84 and event in ('Z876', 'Z678'))NEWLINE 0: >NEWLINE eid not in (NEWLINE (select eid from events where field_id = 85 and event in ('978', '1701'))NEWLINE unionNEWLINE (select eid from events where field_id = 84 and event in ('Z876', 'Z678'))NEWLINE )NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 7NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['another_disease_name']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'another_disease_name'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'another_disease_name'] == '1' # 1000030NEWLINE assert pheno_file.loc[1000040, 'another_disease_name'] == '0' # 1000040NEWLINE assert pheno_file.loc[1000010, 'another_disease_name'] == '1' # 1000010NEWLINE assert pheno_file.loc[1000020, 'another_disease_name'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'another_disease_name'] == '1' # 1000070NEWLINE assert pheno_file.loc[1000060, 'another_disease_name'] == '1' # 1000060NEWLINENEWLINE def test_phenotype_query_yaml_samples_filters_condition_breaking_for_data(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE data:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 > 0NEWLINE 0: c46_0_0 < 0NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 4NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, 1), pheno_file.shapeNEWLINENEWLINE expected_columns = ['mydisease']NEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'mydisease'] == '1' # 1000050NEWLINE assert pheno_file.loc[1000030, 'mydisease'] == '0' # 1000030NEWLINE assert pheno_file.loc[1000020, 'mydisease'] == '0' # 1000020NEWLINE assert pheno_file.loc[1000070, 'mydisease'] == '1' # 1000070NEWLINENEWLINE def test_phenotype_query_yaml_samples_including_numerical(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE data:NEWLINE continuous_data: c47_0_0NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINE expected_columns = ['continuous_data']NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, len(expected_columns)), pheno_file.shapeNEWLINENEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'continuous_data'] == 'NA'NEWLINE assert pheno_file.loc[1000030, 'continuous_data'] == '-35.31471'NEWLINE assert pheno_file.loc[1000020, 'continuous_data'] == '-10.51461'NEWLINE assert pheno_file.loc[1000060, 'continuous_data'] == '-0.5864'NEWLINE assert pheno_file.loc[1000070, 'continuous_data'] == '3.5584'NEWLINENEWLINE def test_phenotype_query_yaml_samples_including_numerical_integer(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE data:NEWLINE integer_data:NEWLINE (case when c46_0_0 < -5 then NULL else c46_0_0 end)NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINE expected_columns = ['integer_data']NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, len(expected_columns)), pheno_file.shapeNEWLINENEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'integer_data'] == '1'NEWLINE assert pheno_file.loc[1000030, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000020, 'integer_data'] == '-2'NEWLINE assert pheno_file.loc[1000060, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000070, 'integer_data'] == '2'NEWLINENEWLINE def test_phenotype_query_yaml_samples_including_categorical_and_numerical(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE data:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 > 0NEWLINE 0: c46_0_0 < 0NEWLINE NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINE NEWLINE continuous_data:NEWLINE c47_0_0NEWLINE NEWLINE integer_data: (case when c46_0_0 < 0 then NULL else c46_0_0 end)NEWLINE """NEWLINENEWLINE N_EXPECTED_SAMPLES = 5NEWLINE expected_columns = ['mydisease', 'third_column', 'continuous_data', 'integer_data']NEWLINENEWLINE #NEWLINE # Ask fieldsNEWLINE #NEWLINE response = self.app.post('/ukbrest/api/v1.0/query', data=NEWLINE {NEWLINE 'file': (io.BytesIO(yaml_data), 'data.yaml'),NEWLINE 'section': 'data',NEWLINE }, headers={'accept': 'text/csv'})NEWLINENEWLINE # ValidateNEWLINE assert response.status_code == 200, response.status_codeNEWLINENEWLINE pheno_file = pd.read_csv(io.StringIO(response.data.decode('utf-8')), header=0,NEWLINE index_col='eid', dtype=str, na_values='', keep_default_na=False)NEWLINENEWLINE assert pheno_file is not NoneNEWLINE assert not pheno_file.emptyNEWLINE assert pheno_file.shape == (N_EXPECTED_SAMPLES, len(expected_columns)), pheno_file.shapeNEWLINENEWLINE assert len(pheno_file.columns) == len(expected_columns)NEWLINE assert all(x in expected_columns for x in pheno_file.columns)NEWLINENEWLINE assert pheno_file.loc[1000050, 'mydisease'] == '1'NEWLINE assert pheno_file.loc[1000030, 'mydisease'] == '0'NEWLINE assert pheno_file.loc[1000020, 'mydisease'] == '0'NEWLINE assert pheno_file.loc[1000060, 'mydisease'] == 'NA'NEWLINE assert pheno_file.loc[1000070, 'mydisease'] == '1'NEWLINENEWLINE assert pheno_file.loc[1000050, 'third_column'] == '1'NEWLINE assert pheno_file.loc[1000030, 'third_column'] == '0'NEWLINE assert pheno_file.loc[1000020, 'third_column'] == '1'NEWLINE assert pheno_file.loc[1000060, 'third_column'] == '0'NEWLINE assert pheno_file.loc[1000070, 'third_column'] == '1'NEWLINENEWLINE assert pheno_file.loc[1000050, 'continuous_data'] == 'NA'NEWLINE assert pheno_file.loc[1000030, 'continuous_data'] == '-35.31471'NEWLINE assert pheno_file.loc[1000020, 'continuous_data'] == '-10.51461'NEWLINE assert pheno_file.loc[1000060, 'continuous_data'] == '-0.5864'NEWLINE assert pheno_file.loc[1000070, 'continuous_data'] == '3.5584'NEWLINENEWLINE assert pheno_file.loc[1000050, 'integer_data'] == '1'NEWLINE assert pheno_file.loc[1000030, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000020, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000060, 'integer_data'] == 'NA'NEWLINE assert pheno_file.loc[1000070, 'integer_data'] == '2'NEWLINENEWLINE def test_phenotype_query_yaml_multiple_files_in_one_yaml(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # in this case there is an or condition that could break all if it is not surrounding by ()NEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINENEWLINE my_first_dataset:NEWLINE mydisease:NEWLINE sql:NEWLINE 1: c46_0_0 > 0NEWLINE 0: c46_0_0 < 0NEWLINENEWLINE continuous_data:NEWLINE c47_0_0NEWLINENEWLINE my_second_dataset:NEWLINE third_column:NEWLINE case_control:NEWLINE 84:NEWLINE coding: [E103, Z678]NEWLINENEWLINE integer_data: (case when c46_0_0 < 0 then NULL else c46_0_0 end)NEWLINE """NEWLINENEWLINE # covariatesNEWLINE data_fetched =\NEWLINE self._make_yaml_request(NEWLINE yaml_data, 'covariates', 5,NEWLINE ['field_name_34', 'field_name_47']NEWLINE )NEWLINENEWLINE assert data_fetched.loc[1000020, 'field_name_34'] == '34'NEWLINE assert data_fetched.loc[1000030, 'field_name_34'] == '-6'NEWLINE assert data_fetched.loc[1000050, 'field_name_34'] == '-4'NEWLINE assert data_fetched.loc[1000060, 'field_name_34'] == 'NA'NEWLINE assert data_fetched.loc[1000070, 'field_name_34'] == '-5'NEWLINENEWLINE # my_first_datasetNEWLINE data_fetched =\NEWLINE self._make_yaml_request(NEWLINE yaml_data, 'my_first_dataset', 5,NEWLINE ['mydisease', 'continuous_data']NEWLINE )NEWLINENEWLINE assert data_fetched.loc[1000050, 'mydisease'] == '1'NEWLINE assert data_fetched.loc[1000030, 'mydisease'] == '0'NEWLINE assert data_fetched.loc[1000020, 'mydisease'] == '0'NEWLINE assert data_fetched.loc[1000060, 'mydisease'] == 'NA'NEWLINE assert data_fetched.loc[1000070, 'mydisease'] == '1'NEWLINENEWLINE assert data_fetched.loc[1000050, 'continuous_data'] == 'NA'NEWLINE assert data_fetched.loc[1000030, 'continuous_data'] == '-35.31471'NEWLINE assert data_fetched.loc[1000020, 'continuous_data'] == '-10.51461'NEWLINE assert data_fetched.loc[1000060, 'continuous_data'] == '-0.5864'NEWLINE assert data_fetched.loc[1000070, 'continuous_data'] == '3.5584'NEWLINENEWLINE # my_second_datasetNEWLINE data_fetched =\NEWLINE self._make_yaml_request(NEWLINE yaml_data, 'my_second_dataset', 5,NEWLINE ['third_column', 'integer_data']NEWLINE )NEWLINENEWLINE assert data_fetched.loc[1000050, 'third_column'] == '1'NEWLINE assert data_fetched.loc[1000030, 'third_column'] == '0'NEWLINE assert data_fetched.loc[1000020, 'third_column'] == '1'NEWLINE assert data_fetched.loc[1000060, 'third_column'] == '0'NEWLINE assert data_fetched.loc[1000070, 'third_column'] == '1'NEWLINENEWLINE assert data_fetched.loc[1000050, 'integer_data'] == '1'NEWLINE assert data_fetched.loc[1000030, 'integer_data'] == 'NA'NEWLINE assert data_fetched.loc[1000020, 'integer_data'] == 'NA'NEWLINE assert data_fetched.loc[1000060, 'integer_data'] == 'NA'NEWLINE assert data_fetched.loc[1000070, 'integer_data'] == '2'NEWLINENEWLINE def test_phenotype_query_yaml_simple_query(self):NEWLINE # PrepareNEWLINE self.setUp('pheno2sql/example13/example13_diseases.csv',NEWLINE bgen_sample_file=get_repository_path('pheno2sql/example13/impv2.sample'),NEWLINE sql_chunksize=2, n_columns_per_table=2)NEWLINENEWLINE # this type of query, with 'simple_' at the begining of the data section, makes direct queries to theNEWLINE # databaseNEWLINE yaml_data = b"""NEWLINE samples_filters:NEWLINE - lower(c21_2_0) in ('yes', 'no', 'maybe', 'probably')NEWLINE - c34_0_0 is null or c34_0_0 > -10 or c34_0_0 > -11NEWLINENEWLINE simple_covariates:NEWLINE field_name_34: c34_0_0 NEWLINE field_name_47: c47_0_0NEWLINE """NEWLINENEWLINE # simple_covariatesNEWLINE data_fetched =\NEWLINE self._make_yaml_request(NEWLINE yaml_data, 'simple_covariates', 5,NEWLINE ['field_name_34', 'field_name_47']NEWLINE )NEWLINENEWLINE assert data_fetched.loc[1000020, 'field_name_34'] == '34'NEWLINE assert data_fetched.loc[1000030, 'field_name_34'] == '-6'NEWLINE assert data_fetched.loc[1000050, 'field_name_34'] == '-4'NEWLINE assert data_fetched.loc[1000060, 'field_name_34'] == 'NA'NEWLINE assert data_fetched.loc[1000070, 'field_name_34'] == '-5'NEWLINE |
from unittest import TestCaseNEWLINENEWLINEclass TestArmLexer(TestCase): |
from .get_script import get_script # noqaNEWLINEfrom scripts import custom # noqaNEWLINE |
from datetime import dateNEWLINEfrom datetime import datetimeNEWLINEfrom datetime import timedelta as deltaNEWLINENEWLINEimport sysNEWLINEimport numpy as npNEWLINEimport xarray as xrNEWLINENEWLINEfrom parcels.grid import GridCodeNEWLINEfrom parcels.grid import CurvilinearGridNEWLINEfrom parcels.kernel import KernelNEWLINEfrom parcels.particle import JITParticleNEWLINEfrom parcels.particlefile import ParticleFileNEWLINEfrom parcels.tools.statuscodes import StateCodeNEWLINEfrom .baseparticleset import BaseParticleSetNEWLINEfrom .collectionsoa import ParticleCollectionSOANEWLINEfrom .collectionsoa import ParticleCollectionIteratorSOANEWLINEfrom parcels.tools.converters import _get_cftime_calendarsNEWLINEfrom parcels.tools.loggers import loggerNEWLINEtry:NEWLINE from mpi4py import MPINEWLINEexcept:NEWLINE MPI = NoneNEWLINE# == comment CK: prevents us from adding KDTree as 'mandatory' dependency == #NEWLINEtry:NEWLINE from pykdtree.kdtree import KDTreeNEWLINEexcept:NEWLINE KDTree = NoneNEWLINENEWLINE__all__ = ['ParticleSet', 'ParticleSetSOA']NEWLINENEWLINENEWLINEdef _convert_to_array(var):NEWLINE """Convert lists and single integers/floats to one-dimensional numpyNEWLINE arraysNEWLINE """NEWLINE if isinstance(var, np.ndarray):NEWLINE return var.flatten()NEWLINE elif isinstance(var, (int, float, np.float32, np.int32)):NEWLINE return np.array([var])NEWLINE else:NEWLINE return np.array(var)NEWLINENEWLINENEWLINEdef _convert_to_reltime(time):NEWLINE """Check to determine if the value of the time parameter needs to beNEWLINE converted to a relative value (relative to the time_origin).NEWLINE """NEWLINE if isinstance(time, np.datetime64) or (hasattr(time, 'calendar') and time.calendar in _get_cftime_calendars()):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINEclass ParticleSetSOA(BaseParticleSet):NEWLINE """Container class for storing particle and executing kernel over them.NEWLINENEWLINE Please note that this currently only supports fixed size particle sets.NEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocity.NEWLINE While fieldset=None is supported, this will throw a warning as it breaks most Parcels functionalityNEWLINE :param pclass: Optional :mod:`parcels.particle.JITParticle` orNEWLINE :mod:`parcels.particle.ScipyParticle` object that defines custom particleNEWLINE :param lon: List of initial longitude values for particlesNEWLINE :param lat: List of initial latitude values for particlesNEWLINE :param depth: Optional list of initial depth values for particles. Default is 0mNEWLINE :param time: Optional list of initial time values for particles. Default is fieldset.U.grid.time[0]NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE :param pid_orig: Optional list of (offsets for) the particle IDsNEWLINE :param partitions: List of cores on which to distribute the particles for MPI runs. Default: None, in which case particlesNEWLINE are distributed automatically on the processorsNEWLINENEWLINE Other Variables can be initialised using further arguments (e.g. v=... for a Variable named 'v')NEWLINE """NEWLINENEWLINE def __init__(self, fieldset=None, pclass=JITParticle, lon=None, lat=None, depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None, pid_orig=None, **kwargs):NEWLINE super(ParticleSetSOA, self).__init__()NEWLINE self.fieldset = fieldsetNEWLINE if self.fieldset is None:NEWLINE logger.warning_once("No FieldSet provided in ParticleSet generation. "NEWLINE "This breaks most Parcels functionality")NEWLINE else:NEWLINE self.fieldset.check_complete()NEWLINE partitions = kwargs.pop('partitions', None)NEWLINENEWLINE lon = np.empty(shape=0) if lon is None else _convert_to_array(lon)NEWLINE lat = np.empty(shape=0) if lat is None else _convert_to_array(lat)NEWLINENEWLINE if isinstance(pid_orig, (type(None), type(False))):NEWLINE pid_orig = np.arange(lon.size)NEWLINENEWLINE if depth is None:NEWLINE mindepth = self.fieldset.gridset.dimrange('depth')[0] if self.fieldset is not None else 0NEWLINE depth = np.ones(lon.size) * mindepthNEWLINE else:NEWLINE depth = _convert_to_array(depth)NEWLINE assert lon.size == lat.size and lon.size == depth.size, (NEWLINE 'lon, lat, depth don''t all have the same lenghts')NEWLINENEWLINE time = _convert_to_array(time)NEWLINE time = np.repeat(time, lon.size) if time.size == 1 else timeNEWLINENEWLINE if time.size > 0 and type(time[0]) in [datetime, date]:NEWLINE time = np.array([np.datetime64(t) for t in time])NEWLINE self.time_origin = fieldset.time_origin if self.fieldset is not None else 0NEWLINE if time.size > 0 and isinstance(time[0], np.timedelta64) and not self.time_origin:NEWLINE raise NotImplementedError('If fieldset.time_origin is not a date, time of a particle must be a double')NEWLINE time = np.array([self.time_origin.reltime(t) if _convert_to_reltime(t) else t for t in time])NEWLINE assert lon.size == time.size, (NEWLINE 'time and positions (lon, lat, depth) don''t have the same lengths.')NEWLINENEWLINE if lonlatdepth_dtype is None:NEWLINE if fieldset is not None:NEWLINE lonlatdepth_dtype = self.lonlatdepth_dtype_from_field_interp_method(fieldset.U)NEWLINE else:NEWLINE lonlatdepth_dtype = np.float32NEWLINE assert lonlatdepth_dtype in [np.float32, np.float64], \NEWLINE 'lon lat depth precision should be set to either np.float32 or np.float64'NEWLINENEWLINE for kwvar in kwargs:NEWLINE kwargs[kwvar] = _convert_to_array(kwargs[kwvar])NEWLINE assert lon.size == kwargs[kwvar].size, (NEWLINE '%s and positions (lon, lat, depth) don''t have the same lengths.' % kwvar)NEWLINENEWLINE self.repeatdt = repeatdt.total_seconds() if isinstance(repeatdt, delta) else repeatdtNEWLINE if self.repeatdt:NEWLINE if self.repeatdt <= 0:NEWLINE raise('Repeatdt should be > 0')NEWLINE if time[0] and not np.allclose(time, time[0]):NEWLINE raise ('All Particle.time should be the same when repeatdt is not None')NEWLINE self.repeatpclass = pclassNEWLINE self.repeatkwargs = kwargsNEWLINENEWLINE ngrids = fieldset.gridset.size if fieldset is not None else 1NEWLINE self._collection = ParticleCollectionSOA(pclass, lon=lon, lat=lat, depth=depth, time=time, lonlatdepth_dtype=lonlatdepth_dtype, pid_orig=pid_orig, partitions=partitions, ngrid=ngrids, **kwargs)NEWLINENEWLINE if self.repeatdt:NEWLINE if len(time) > 0 and time[0] is None:NEWLINE self.repeat_starttime = time[0]NEWLINE else:NEWLINE if self._collection.data['time'][0] and not np.allclose(self._collection.data['time'], self._collection.data['time'][0]):NEWLINE raise ValueError('All Particle.time should be the same when repeatdt is not None')NEWLINE self.repeat_starttime = self._collection.data['time'][0]NEWLINE self.repeatlon = self._collection.data['lon']NEWLINE self.repeatlat = self._collection.data['lat']NEWLINE self.repeatdepth = self._collection.data['depth']NEWLINE for kwvar in kwargs:NEWLINE self.repeatkwargs[kwvar] = self._collection.data[kwvar]NEWLINENEWLINE if self.repeatdt:NEWLINE if MPI and self._collection.pu_indicators is not None:NEWLINE mpi_comm = MPI.COMM_WORLDNEWLINE mpi_rank = mpi_comm.Get_rank()NEWLINE self.repeatpid = pid_orig[self._collection.pu_indicators == mpi_rank]NEWLINENEWLINE self.kernel = NoneNEWLINENEWLINE def _set_particle_vector(self, name, value):NEWLINE """Set attributes of all particles to new values.NEWLINENEWLINE :param name: Name of the attribute (str).NEWLINE :param value: New value to set the attribute of the particles to.NEWLINE """NEWLINE self.collection._data[name][:] = valueNEWLINENEWLINE def _impute_release_times(self, default):NEWLINE """Set attribute 'time' to default if encountering NaN values.NEWLINENEWLINE :param default: Default release time.NEWLINE :return: Minimum and maximum release times.NEWLINE """NEWLINE if np.any(np.isnan(self._collection.data['time'])):NEWLINE self._collection.data['time'][np.isnan(self._collection.data['time'])] = defaultNEWLINE return np.min(self._collection.data['time']), np.max(self._collection.data['time'])NEWLINENEWLINE def data_indices(self, variable_name, compare_values, invert=False):NEWLINE """Get the indices of all particles where the value ofNEWLINE `variable_name` equals (one of) `compare_values`.NEWLINENEWLINE :param variable_name: Name of the variable to check.NEWLINE :param compare_values: Value or list of values to compare to.NEWLINE :param invert: Whether to invert the selection. I.e., when True,NEWLINE return all indices that do not equal (one of)NEWLINE `compare_values`.NEWLINE :return: Numpy array of indices that satisfy the test.NEWLINE """NEWLINE compare_values = np.array([compare_values, ]) if type(compare_values) not in [list, dict, np.ndarray] else compare_valuesNEWLINE return np.where(np.isin(self._collection.data[variable_name], compare_values, invert=invert))[0]NEWLINENEWLINE def indexed_subset(self, indices):NEWLINE return ParticleCollectionIteratorSOA(self._collection,NEWLINE subset=indices)NEWLINENEWLINE def populate_indices(self):NEWLINE """Pre-populate guesses of particle xi/yi indices using a kdtree.NEWLINENEWLINE This is only intended for curvilinear grids, where the initial index searchNEWLINE may be quite expensive.NEWLINE """NEWLINENEWLINE if self.fieldset is None:NEWLINE # we need to be attached to a fieldset to have a validNEWLINE # gridset to search for indicesNEWLINE returnNEWLINENEWLINE if KDTree is None:NEWLINE returnNEWLINE else:NEWLINE for i, grid in enumerate(self.fieldset.gridset.grids):NEWLINE if not isinstance(grid, CurvilinearGrid):NEWLINE continueNEWLINENEWLINE tree_data = np.stack((grid.lon.flat, grid.lat.flat), axis=-1)NEWLINE tree = KDTree(tree_data)NEWLINE # stack all the particle positions for a single queryNEWLINE pts = np.stack((self._collection.data['lon'], self._collection.data['lat']), axis=-1)NEWLINE # query datatype needs to match tree datatypeNEWLINE _, idx = tree.query(pts.astype(tree_data.dtype))NEWLINE yi, xi = np.unravel_index(idx, grid.lon.shape)NEWLINENEWLINE self._collection.data['xi'][:, i] = xiNEWLINE self._collection.data['yi'][:, i] = yiNEWLINENEWLINE @propertyNEWLINE def error_particles(self):NEWLINE """Get an iterator over all particles that are in an error state.NEWLINENEWLINE :return: Collection iterator over error particles.NEWLINE """NEWLINE error_indices = self.data_indices('state', [StateCode.Success, StateCode.Evaluate], invert=True)NEWLINE return ParticleCollectionIteratorSOA(self._collection, subset=error_indices)NEWLINENEWLINE @propertyNEWLINE def num_error_particles(self):NEWLINE """Get the number of particles that are in an error state.NEWLINENEWLINE :return: The number of error particles.NEWLINE """NEWLINE return np.sum(np.isin(NEWLINE self._collection.data['state'],NEWLINE [StateCode.Success, StateCode.Evaluate], invert=True))NEWLINENEWLINE def __getitem__(self, index):NEWLINE """Get a single particle by index"""NEWLINE return self._collection.get_single_by_index(index)NEWLINENEWLINE def cstruct(self):NEWLINE """NEWLINE 'cstruct' returns the ctypes mapping of the combined collections cstruct and the fieldset cstruct.NEWLINE This depends on the specific structure in question.NEWLINE """NEWLINE cstruct = self._collection.cstruct()NEWLINE return cstructNEWLINENEWLINE @propertyNEWLINE def ctypes_struct(self):NEWLINE return self.cstruct()NEWLINENEWLINE @classmethodNEWLINE def monte_carlo_sample(cls, start_field, size, mode='monte_carlo'):NEWLINE """NEWLINE Converts a starting field into a monte-carlo sample of lons and lats.NEWLINENEWLINE :param start_field: :mod:`parcels.fieldset.Field` object for initialising particles stochastically (horizontally) according to the presented density field.NEWLINENEWLINE returns list(lon), list(lat)NEWLINE """NEWLINE if mode == 'monte_carlo':NEWLINE data = start_field.data if isinstance(start_field.data, np.ndarray) else np.array(start_field.data)NEWLINE if start_field.interp_method == 'cgrid_tracer':NEWLINE p_interior = np.squeeze(data[0, 1:, 1:])NEWLINE else: # if A-gridNEWLINE d = dataNEWLINE p_interior = (d[0, :-1, :-1] + d[0, 1:, :-1] + d[0, :-1, 1:] + d[0, 1:, 1:])/4.NEWLINE p_interior = np.where(d[0, :-1, :-1] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, 1:, :-1] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, 1:, 1:] == 0, 0, p_interior)NEWLINE p_interior = np.where(d[0, :-1, 1:] == 0, 0, p_interior)NEWLINE p = np.reshape(p_interior, (1, p_interior.size))NEWLINE inds = np.random.choice(p_interior.size, size, replace=True, p=p[0] / np.sum(p))NEWLINE xsi = np.random.uniform(size=len(inds))NEWLINE eta = np.random.uniform(size=len(inds))NEWLINE j, i = np.unravel_index(inds, p_interior.shape)NEWLINE grid = start_field.gridNEWLINE lon, lat = ([], [])NEWLINE if grid.gtype in [GridCode.RectilinearZGrid, GridCode.RectilinearSGrid]:NEWLINE lon = grid.lon[i] + xsi * (grid.lon[i + 1] - grid.lon[i])NEWLINE lat = grid.lat[j] + eta * (grid.lat[j + 1] - grid.lat[j])NEWLINE else:NEWLINE lons = np.array([grid.lon[j, i], grid.lon[j, i+1], grid.lon[j+1, i+1], grid.lon[j+1, i]])NEWLINE if grid.mesh == 'spherical':NEWLINE lons[1:] = np.where(lons[1:] - lons[0] > 180, lons[1:]-360, lons[1:])NEWLINE lons[1:] = np.where(-lons[1:] + lons[0] > 180, lons[1:]+360, lons[1:])NEWLINE lon = (1-xsi)*(1-eta) * lons[0] +\NEWLINE xsi*(1-eta) * lons[1] +\NEWLINE xsi*eta * lons[2] +\NEWLINE (1-xsi)*eta * lons[3]NEWLINE lat = (1-xsi)*(1-eta) * grid.lat[j, i] +\NEWLINE xsi*(1-eta) * grid.lat[j, i+1] +\NEWLINE xsi*eta * grid.lat[j+1, i+1] +\NEWLINE (1-xsi)*eta * grid.lat[j+1, i]NEWLINE return list(lon), list(lat)NEWLINE else:NEWLINE raise NotImplementedError('Mode %s not implemented. Please use "monte carlo" algorithm instead.' % mode)NEWLINENEWLINE @classmethodNEWLINE def from_field(cls, fieldset, pclass, start_field, size, mode='monte_carlo', depth=None, time=None, repeatdt=None, lonlatdepth_dtype=None):NEWLINE """Initialise the ParticleSet randomly drawn according to distribution from a fieldNEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocityNEWLINE :param pclass: mod:`parcels.particle.JITParticle` or :mod:`parcels.particle.ScipyParticle`NEWLINE object that defines custom particleNEWLINE :param start_field: Field for initialising particles stochastically (horizontally) according to the presented density field.NEWLINE :param size: Initial size of particle setNEWLINE :param mode: Type of random sampling. Currently only 'monte_carlo' is implementedNEWLINE :param depth: Optional list of initial depth values for particles. Default is 0mNEWLINE :param time: Optional start time value for particles. Default is fieldset.U.time[0]NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE """NEWLINE lon, lat = cls.monte_carlo_sample(start_field, size, mode)NEWLINENEWLINE return cls(fieldset=fieldset, pclass=pclass, lon=lon, lat=lat, depth=depth, time=time,NEWLINE lonlatdepth_dtype=lonlatdepth_dtype, repeatdt=repeatdt)NEWLINENEWLINE @classmethodNEWLINE def from_particlefile(cls, fieldset, pclass, filename, restart=True, restarttime=None, repeatdt=None, lonlatdepth_dtype=None, **kwargs):NEWLINE """Initialise the ParticleSet from a netcdf ParticleFile.NEWLINE This creates a new ParticleSet based on locations of all particles writtenNEWLINE in a netcdf ParticleFile at a certain time. Particle IDs are preserved if restart=TrueNEWLINENEWLINE :param fieldset: :mod:`parcels.fieldset.FieldSet` object from which to sample velocityNEWLINE :param pclass: mod:`parcels.particle.JITParticle` or :mod:`parcels.particle.ScipyParticle`NEWLINE object that defines custom particleNEWLINE :param filename: Name of the particlefile from which to read initial conditionsNEWLINE :param restart: Boolean to signal if pset is used for a restart (default is True).NEWLINE In that case, Particle IDs are preserved.NEWLINE :param restarttime: time at which the Particles will be restarted. Default is the last time written.NEWLINE Alternatively, restarttime could be a time value (including np.datetime64) orNEWLINE a callable function such as np.nanmin. The last is useful when running with dt < 0.NEWLINE :param repeatdt: Optional interval (in seconds) on which to repeat the release of the ParticleSetNEWLINE :param lonlatdepth_dtype: Floating precision for lon, lat, depth particle coordinates.NEWLINE It is either np.float32 or np.float64. Default is np.float32 if fieldset.U.interp_method is 'linear'NEWLINE and np.float64 if the interpolation method is 'cgrid_velocity'NEWLINE """NEWLINENEWLINE if repeatdt is not None:NEWLINE logger.warning('Note that the `repeatdt` argument is not retained from %s, and that 'NEWLINE 'setting a new repeatdt will start particles from the _new_ particle 'NEWLINE 'locations.' % filename)NEWLINENEWLINE pfile = xr.open_dataset(str(filename), decode_cf=True)NEWLINE pfile_vars = [v for v in pfile.data_vars]NEWLINENEWLINE vars = {}NEWLINE to_write = {}NEWLINE for v in pclass.getPType().variables:NEWLINE if v.name in pfile_vars:NEWLINE vars[v.name] = np.ma.filled(pfile.variables[v.name], np.nan)NEWLINE elif v.name not in ['xi', 'yi', 'zi', 'ti', 'dt', '_next_dt', 'depth', 'id', 'fileid', 'state'] \NEWLINE and v.to_write:NEWLINE raise RuntimeError('Variable %s is in pclass but not in the particlefile' % v.name)NEWLINE to_write[v.name] = v.to_writeNEWLINE vars['depth'] = np.ma.filled(pfile.variables['z'], np.nan)NEWLINE vars['id'] = np.ma.filled(pfile.variables['trajectory'], np.nan)NEWLINENEWLINE if isinstance(vars['time'][0, 0], np.timedelta64):NEWLINE vars['time'] = np.array([t/np.timedelta64(1, 's') for t in vars['time']])NEWLINENEWLINE if restarttime is None:NEWLINE restarttime = np.nanmax(vars['time'])NEWLINE elif callable(restarttime):NEWLINE restarttime = restarttime(vars['time'])NEWLINE else:NEWLINE restarttime = restarttimeNEWLINENEWLINE inds = np.where(vars['time'] == restarttime)NEWLINE for v in vars:NEWLINE if to_write[v] is True:NEWLINE vars[v] = vars[v][inds]NEWLINE elif to_write[v] == 'once':NEWLINE vars[v] = vars[v][inds[0]]NEWLINE if v not in ['lon', 'lat', 'depth', 'time', 'id']:NEWLINE kwargs[v] = vars[v]NEWLINENEWLINE if restart:NEWLINE pclass.setLastID(0) # reset to zero offsetNEWLINE else:NEWLINE vars['id'] = NoneNEWLINENEWLINE return cls(fieldset=fieldset, pclass=pclass, lon=vars['lon'], lat=vars['lat'],NEWLINE depth=vars['depth'], time=vars['time'], pid_orig=vars['id'],NEWLINE lonlatdepth_dtype=lonlatdepth_dtype, repeatdt=repeatdt, **kwargs)NEWLINENEWLINE def to_dict(self, pfile, time, deleted_only=False):NEWLINE """NEWLINE Convert all Particle data from one time step to a python dictionary.NEWLINE :param pfile: ParticleFile object requesting the conversionNEWLINE :param time: Time at which to write ParticleSetNEWLINE :param deleted_only: Flag to write only the deleted ParticlesNEWLINE returns two dictionaries: one for all variables to be written each outputdt,NEWLINE and one for all variables to be written onceNEWLINE """NEWLINE return self._collection.toDictionary(pfile=pfile, time=time,NEWLINE deleted_only=deleted_only)NEWLINENEWLINE @propertyNEWLINE def size(self):NEWLINE # ==== to change at some point - len and size are different things ==== #NEWLINE return len(self._collection)NEWLINENEWLINE def __repr__(self):NEWLINE return "\n".join([str(p) for p in self])NEWLINENEWLINE def __len__(self):NEWLINE return len(self._collection)NEWLINENEWLINE def __sizeof__(self):NEWLINE return sys.getsizeof(self._collection)NEWLINENEWLINE def __iadd__(self, particles):NEWLINE """Add particles to the ParticleSet. Note that this is anNEWLINE incremental add, the particles will be added to the ParticleSetNEWLINE on which this function is called.NEWLINENEWLINE :param particles: Another ParticleSet containing particles to addNEWLINE to this one.NEWLINE :return: The current ParticleSetNEWLINE """NEWLINE self.add(particles)NEWLINE return selfNEWLINENEWLINE def add(self, particles):NEWLINE """Add particles to the ParticleSet. Note that this is anNEWLINE incremental add, the particles will be added to the ParticleSetNEWLINE on which this function is called.NEWLINENEWLINE :param particles: Another ParticleSet containing particles to addNEWLINE to this one.NEWLINE :return: The current ParticleSetNEWLINE """NEWLINE if isinstance(particles, BaseParticleSet):NEWLINE particles = particles.collectionNEWLINE self._collection += particlesNEWLINE return selfNEWLINENEWLINE def remove_indices(self, indices):NEWLINE """Method to remove particles from the ParticleSet, based on their `indices`"""NEWLINE if type(indices) in [int, np.int32, np.intp]:NEWLINE self._collection.remove_single_by_index(indices)NEWLINE else:NEWLINE self._collection.remove_multi_by_indices(indices)NEWLINENEWLINE def remove_booleanvector(self, indices):NEWLINE """Method to remove particles from the ParticleSet, based on an array of booleans"""NEWLINE self.remove_indices(np.where(indices)[0])NEWLINENEWLINE def show(self, with_particles=True, show_time=None, field=None, domain=None, projection=None,NEWLINE land=True, vmin=None, vmax=None, savefile=None, animation=False, **kwargs):NEWLINE """Method to 'show' a Parcels ParticleSetNEWLINENEWLINE :param with_particles: Boolean whether to show particlesNEWLINE :param show_time: Time at which to show the ParticleSetNEWLINE :param field: Field to plot under particles (either None, a Field object, or 'vector')NEWLINE :param domain: dictionary (with keys 'N', 'S', 'E', 'W') defining domain to showNEWLINE :param projection: type of cartopy projection to use (default PlateCarree)NEWLINE :param land: Boolean whether to show land. This is ignored for flat meshesNEWLINE :param vmin: minimum colour scale (only in single-plot mode)NEWLINE :param vmax: maximum colour scale (only in single-plot mode)NEWLINE :param savefile: Name of a file to save the plot toNEWLINE :param animation: Boolean whether result is a single plot, or an animationNEWLINE """NEWLINE from parcels.plotting import plotparticlesNEWLINE plotparticles(particles=self, with_particles=with_particles, show_time=show_time, field=field, domain=domain,NEWLINE projection=projection, land=land, vmin=vmin, vmax=vmax, savefile=savefile, animation=animation, **kwargs)NEWLINENEWLINE def density(self, field_name=None, particle_val=None, relative=False, area_scale=False):NEWLINE """Method to calculate the density of particles in a ParticleSet from their locations,NEWLINE through a 2D histogram.NEWLINENEWLINE :param field: Optional :mod:`parcels.field.Field` object to calculate the histogramNEWLINE on. Default is `fieldset.U`NEWLINE :param particle_val: Optional numpy-array of values to weigh each particle with,NEWLINE or string name of particle variable to use weigh particles with.NEWLINE Default is None, resulting in a value of 1 for each particleNEWLINE :param relative: Boolean to control whether the density is scaled by the totalNEWLINE weight of all particles. Default is FalseNEWLINE :param area_scale: Boolean to control whether the density is scaled by the areaNEWLINE (in m^2) of each grid cell. Default is FalseNEWLINE """NEWLINENEWLINE field_name = field_name if field_name else "U"NEWLINE field = getattr(self.fieldset, field_name)NEWLINENEWLINE f_str = """NEWLINEdef search_kernel(particle, fieldset, time):NEWLINE x = fieldset.{}[time, particle.depth, particle.lat, particle.lon]NEWLINE """.format(field_name)NEWLINENEWLINE k = Kernel(NEWLINE self.fieldset,NEWLINE self._collection.ptype,NEWLINE funcname="search_kernel",NEWLINE funcvars=["particle", "fieldset", "time", "x"],NEWLINE funccode=f_str,NEWLINE )NEWLINE self.execute(pyfunc=k, runtime=0)NEWLINENEWLINE if isinstance(particle_val, str):NEWLINE particle_val = self._collection._data[particle_val]NEWLINE else:NEWLINE particle_val = particle_val if particle_val else np.ones(self.size)NEWLINE density = np.zeros((field.grid.lat.size, field.grid.lon.size), dtype=np.float32)NEWLINENEWLINE for i, p in enumerate(self):NEWLINE try: # breaks if either p.xi, p.yi, p.zi, p.ti do not exist (in scipy) or field not in fieldsetNEWLINE if p.ti[field.igrid] < 0: # xi, yi, zi, ti, not initialisedNEWLINE raise('error')NEWLINE xi = p.xi[field.igrid]NEWLINE yi = p.yi[field.igrid]NEWLINE except:NEWLINE _, _, _, xi, yi, _ = field.search_indices(p.lon, p.lat, p.depth, 0, 0, search2D=True)NEWLINE density[yi, xi] += particle_val[i]NEWLINENEWLINE if relative:NEWLINE density /= np.sum(particle_val)NEWLINENEWLINE if area_scale:NEWLINE density /= field.cell_areas()NEWLINENEWLINE return densityNEWLINENEWLINE def Kernel(self, pyfunc, c_include="", delete_cfiles=True):NEWLINE """Wrapper method to convert a `pyfunc` into a :class:`parcels.kernel.Kernel` objectNEWLINE based on `fieldset` and `ptype` of the ParticleSetNEWLINENEWLINE :param delete_cfiles: Boolean whether to delete the C-files after compilation in JIT mode (default is True)NEWLINE """NEWLINE return Kernel(self.fieldset, self.collection.ptype, pyfunc=pyfunc, c_include=c_include,NEWLINE delete_cfiles=delete_cfiles)NEWLINENEWLINE def ParticleFile(self, *args, **kwargs):NEWLINE """Wrapper method to initialise a :class:`parcels.particlefile.ParticleFile`NEWLINE object from the ParticleSet"""NEWLINE return ParticleFile(*args, particleset=self, **kwargs)NEWLINENEWLINE def set_variable_write_status(self, var, write_status):NEWLINE """NEWLINE Method to set the write status of a VariableNEWLINE :param var: Name of the variable (string)NEWLINE :param write_status: Write status of the variable (True, False orNEWLINE 'once')NEWLINE """NEWLINE self._collection.set_variable_write_status(var, write_status)NEWLINENEWLINENEWLINE# ParticleSet is an alias for ParticleSetSOA, i.e. the defaultNEWLINE# implementation for storing particles is the Structure of ArraysNEWLINE# approach.NEWLINEParticleSet = ParticleSetSOANEWLINE |
import osNEWLINEimport sysNEWLINEimport pytestNEWLINEfrom fastapi.testclient import TestClientNEWLINEfrom typer.testing import CliRunnerNEWLINEfrom sqlalchemy.exc import IntegrityErrorNEWLINENEWLINE# This next line ensures tests uses its own database and settings environmentNEWLINEos.environ["FORCE_ENV_FOR_DYNACONF"] = "testing" # noqaNEWLINE# WARNING: Ensure imports from `fastapi_sqlmodel_demo` comes after this lineNEWLINEfrom fastapi_sqlmodel_demo import app, settings, db # noqaNEWLINEfrom fastapi_sqlmodel_demo.cli import create_user, cli # noqaNEWLINENEWLINENEWLINE# each test runs on cwd to its temp [email protected](autouse=True)NEWLINEdef go_to_tmpdir(request):NEWLINE # Get the fixture dynamically by its name.NEWLINE tmpdir = request.getfixturevalue("tmpdir")NEWLINE # ensure local test created packages can be importedNEWLINE sys.path.insert(0, str(tmpdir))NEWLINE # Chdir only for the duration of the test.NEWLINE with tmpdir.as_cwd():NEWLINE [email protected](scope="function", name="app")NEWLINEdef _app():NEWLINE return [email protected](scope="function", name="cli")NEWLINEdef _cli():NEWLINE return [email protected](scope="function", name="settings")NEWLINEdef _settings():NEWLINE return [email protected](scope="function")NEWLINEdef api_client():NEWLINE return TestClient(app)[email protected](scope="function")NEWLINEdef api_client_authenticated():NEWLINENEWLINE try:NEWLINE create_user("admin", "admin", superuser=True)NEWLINE except IntegrityError:NEWLINE passNEWLINENEWLINE client = TestClient(app)NEWLINE token = client.post(NEWLINE "/token",NEWLINE data={"username": "admin", "password": "admin"},NEWLINE headers={"Content-Type": "application/x-www-form-urlencoded"},NEWLINE ).json()["access_token"]NEWLINE client.headers["Authorization"] = f"Bearer {token}"NEWLINE return [email protected](scope="function")NEWLINEdef cli_client():NEWLINE return CliRunner()NEWLINENEWLINENEWLINEdef remove_db():NEWLINE # Remove the database fileNEWLINE try:NEWLINE os.remove("testing.db")NEWLINE except FileNotFoundError:NEWLINE [email protected](scope="session", autouse=True)NEWLINEdef initialize_db(request):NEWLINE db.create_db_and_tables(db.engine)NEWLINE request.addfinalizer(remove_db)NEWLINE |
# Copyright: 2019, NLnet Labs and the Internet.nl contributorsNEWLINE# SPDX-License-Identifier: Apache-2.0NEWLINEfrom datetime import timedeltaNEWLINEimport randomNEWLINEfrom timeit import default_timer as timerNEWLINENEWLINEfrom internetnl.celery import appNEWLINEfrom celery.utils.log import get_task_loggerNEWLINEfrom django.conf import settingsNEWLINEfrom django.core.cache import cacheNEWLINEfrom django.utils import timezoneNEWLINEfrom pyrabbit import ClientNEWLINEfrom pyrabbit.http import HTTPError, NetworkErrorNEWLINEfrom pyrabbit.api import APIError, PermissionErrorNEWLINENEWLINEfrom . import utilNEWLINEfrom .. import batch_shared_task, redis_idNEWLINEfrom ..probes import batch_webprobes, batch_mailprobesNEWLINEfrom ..tasks.dnssec import batch_web_registered as dnssec_web_tasksetNEWLINEfrom ..tasks.dnssec import batch_mail_registered as dnssec_mail_tasksetNEWLINEfrom ..tasks.ipv6 import batch_web_registered as ipv6_web_tasksetNEWLINEfrom ..tasks.ipv6 import batch_mail_registered as ipv6_mail_tasksetNEWLINEfrom ..tasks.mail import batch_mail_registered as auth_mail_tasksetNEWLINEfrom ..tasks.tls import batch_web_registered as tls_web_tasksetNEWLINEfrom ..tasks.tls import batch_mail_registered as tls_mail_tasksetNEWLINEfrom ..tasks.appsecpriv import batch_web_registered as appsecpriv_web_tasksetNEWLINEfrom ..tasks import dispatcherNEWLINEfrom ..models import BatchRequest, BatchRequestStatus, BatchDomainNEWLINEfrom ..models import BatchDomainStatus, BatchTestStatusNEWLINEfrom ..models import BatchWebTestNEWLINEfrom ..models import WebTestTls, WebTestAppsecprivNEWLINEfrom ..models import DomainTestReport, MailTestReport, MailTestTlsNEWLINEfrom ..models import MailTestDnssec, DomainTestDnssecNEWLINENEWLINElogger = get_task_logger(__name__)NEWLINENEWLINEBATCH_WEBTEST = {NEWLINE 'subtests': {NEWLINE 'ipv6': ipv6_web_taskset,NEWLINE 'dnssec': dnssec_web_taskset,NEWLINE 'tls': tls_web_taskset,NEWLINE 'appsecpriv': appsecpriv_web_taskset,NEWLINE },NEWLINE 'report': {NEWLINE 'name': 'domaintestreport'NEWLINE }NEWLINE}NEWLINEBATCH_MAILTEST = {NEWLINE 'subtests': {NEWLINE 'ipv6': ipv6_mail_taskset,NEWLINE 'dnssec': dnssec_mail_taskset,NEWLINE 'auth': auth_mail_taskset,NEWLINE 'tls': tls_mail_taskset,NEWLINE },NEWLINE 'report': {NEWLINE 'name': 'mailtestreport'NEWLINE }NEWLINE}NEWLINENEWLINENEWLINEclass Rabbit():NEWLINE """NEWLINE Wrapper class for the pyrabbit client.NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, rabbit, user, password):NEWLINE self._rabbit = rabbitNEWLINE self._user = userNEWLINE self._pass = passwordNEWLINENEWLINE def _get_client(self):NEWLINE """NEWLINE Get a client connection to rabbitmq.NEWLINENEWLINE """NEWLINE try:NEWLINE self._cl = Client(self._rabbit, self._user, self._pass)NEWLINE return TrueNEWLINE except (HTTPError, NetworkError, APIError, PermissionError):NEWLINE return NoneNEWLINENEWLINE def get_queue_depth(self, host, queue):NEWLINE """NEWLINE Get the size of a queue on a rabbitmq virtual host.NEWLINE In case of a random exception, retry before failing.NEWLINENEWLINE """NEWLINE tries = 5NEWLINE while tries > 0:NEWLINE try:NEWLINE return self._cl.get_queue_depth(host, queue)NEWLINE except (AttributeError, HTTPError, NetworkError, APIError,NEWLINE PermissionError) as e:NEWLINE self._get_client()NEWLINE tries -= 1NEWLINE if tries <= 0:NEWLINE raise eNEWLINENEWLINENEWLINEdef is_queue_loaded(client):NEWLINE """NEWLINE Check if we consider the monitor queue loaded.NEWLINENEWLINE """NEWLINE current_load = client.get_queue_depth(NEWLINE settings.RABBIT_VHOST, settings.RABBIT_MON_QUEUE)NEWLINE if current_load >= settings.RABBIT_MON_THRESHOLD:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINEdef get_live_requests():NEWLINE """NEWLINE Return a dictionary with active users as keys and their earliestNEWLINE live batch request as value.NEWLINENEWLINE """NEWLINE live_requests = dict()NEWLINE batch_requests = BatchRequest.objects.filter(NEWLINE status=BatchRequestStatus.live).order_by('submit_date')NEWLINE for request in batch_requests:NEWLINE if not live_requests.get(request.user):NEWLINE live_requests[request.user] = requestNEWLINE return live_requestsNEWLINENEWLINENEWLINEdef get_user_and_request(live_requests):NEWLINE """NEWLINE Pick a user and his request from the available live_requests.NEWLINE Users are fairly chosen regardless of the number of submitted tests.NEWLINENEWLINE """NEWLINE if not live_requests:NEWLINE return None, NoneNEWLINENEWLINE user = random.choice(list(live_requests.keys()))NEWLINE batch_request = live_requests[user]NEWLINE return user, batch_requestNEWLINENEWLINENEWLINEdef pick_domain(batch_request):NEWLINE """NEWLINE Pick a domain to test.NEWLINE Selects the first available domain.NEWLINENEWLINE """NEWLINE try:NEWLINE return BatchDomain.objects.filter(NEWLINE status=BatchDomainStatus.waiting, batch_request=batch_request)[:1].get() #.first()NEWLINE except BatchDomain.DoesNotExist:NEWLINE return NoneNEWLINENEWLINENEWLINEdef check_for_result_or_start_test(batch_domain, batch_test, subtest, taskset):NEWLINE """NEWLINE Link the result if already available or start a test.NEWLINENEWLINE """NEWLINE started_test = FalseNEWLINE subtest_model = batch_test._meta.get_field(subtest).remote_field.modelNEWLINE result = find_result(batch_domain, subtest_model)NEWLINE if result:NEWLINE save_result(batch_test, subtest, result)NEWLINE else:NEWLINE start_test(batch_domain, batch_test, subtest, taskset)NEWLINE started_test = TrueNEWLINE return started_testNEWLINENEWLINENEWLINEdef find_result(batch_domain, model):NEWLINE """NEWLINE Check if we already have results for the domain. Viable results areNEWLINE ones recorded after the batch submission.NEWLINENEWLINE """NEWLINE submit_date = batch_domain.batch_request.submit_dateNEWLINE try:NEWLINE if model is WebTestTls:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE webtestset__timestamp__gte=submit_date).latest('id')NEWLINE elif model is MailTestTls:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE testset__timestamp__gte=submit_date).latest('id')NEWLINE elif model is MailTestDnssec:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE testset__timestamp__gte=submit_date).latest('id')NEWLINE elif model is WebTestAppsecpriv:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE webtestset__timestamp__gte=submit_date).latest('id')NEWLINE elif model is DomainTestDnssec:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE maildomain_id=None,NEWLINE timestamp__gte=submit_date).latest('id')NEWLINE else:NEWLINE result = model.objects.filter(NEWLINE domain=batch_domain.domain,NEWLINE timestamp__gte=submit_date).latest('id')NEWLINE except model.DoesNotExist:NEWLINE result = NoneNEWLINE return resultNEWLINENEWLINENEWLINEdef save_result(batch_test, subtest, result):NEWLINE """NEWLINE Link results and save model.NEWLINENEWLINE """NEWLINE setattr(batch_test, subtest, result)NEWLINE setattr(batch_test, '{}_status'.format(subtest), BatchTestStatus.done)NEWLINE batch_test.save(update_fields=[NEWLINE '{}_id'.format(subtest),NEWLINE '{}_status'.format(subtest)])NEWLINENEWLINENEWLINEdef start_test(batch_domain, batch_test, subtest, taskset):NEWLINE """NEWLINE Submit test and change status to running.NEWLINENEWLINE """NEWLINE submit_test(batch_domain, subtest, taskset)NEWLINE setattr(batch_test, '{}_status'.format(subtest), BatchTestStatus.running)NEWLINE batch_test.save(update_fields=['{}_status'.format(subtest)])NEWLINENEWLINENEWLINEdef submit_test(batch_domain, test, checks_registry):NEWLINE """NEWLINE Submit the test in celery.NEWLINENEWLINE """NEWLINE url = batch_domain.domainNEWLINE task_set = dispatcher.submit_task_set(NEWLINE url, checks_registry, error_cb=error_callback)NEWLINE # Need to cache it in redis, then the callback can look it up basedNEWLINE # on the task id.NEWLINE cache_id = redis_id.running_batch_test.id.format(task_set.id)NEWLINE cache_ttl = redis_id.running_batch_test.ttlNEWLINE cache.set(cache_id, (batch_domain.id, test), cache_ttl)NEWLINENEWLINE return task_setNEWLINENEWLINENEWLINEdef check_any_subtest_for_status(batch_test, status):NEWLINE """NEWLINE Check if any of the subtests has a given status.NEWLINENEWLINE """NEWLINE if isinstance(batch_test, BatchWebTest):NEWLINE subtests = BATCH_WEBTEST['subtests']NEWLINE else:NEWLINE subtests = BATCH_MAILTEST['subtests']NEWLINENEWLINE for subtest in subtests:NEWLINE if getattr(batch_test, "{}_status".format(subtest)) == status:NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINEdef find_or_create_report(batch_domain):NEWLINE report = get_common_report(batch_domain)NEWLINE if report:NEWLINE batch_test = batch_domain.get_batch_test()NEWLINE batch_test.report = reportNEWLINE batch_test.save(update_fields=['report'])NEWLINE else:NEWLINE create_report(batch_domain)NEWLINENEWLINENEWLINEdef get_common_report(batch_domain):NEWLINE """NEWLINE Try to find the most recent common report for all subtests.NEWLINE If no such report exists or at least one of the subtests is not yetNEWLINE part of a report return nothing.NEWLINENEWLINE """NEWLINE batch_test = batch_domain.get_batch_test()NEWLINE if isinstance(batch_test, BatchWebTest):NEWLINE subtests = BATCH_WEBTEST['subtests']NEWLINE report_details = BATCH_WEBTEST['report']NEWLINE else:NEWLINE subtests = BATCH_MAILTEST['subtests']NEWLINE report_details = BATCH_MAILTEST['report']NEWLINENEWLINE report_ids = {}NEWLINE for subtest in subtests:NEWLINE report_ids[subtest] = set()NEWLINE # example: batch_test.ipv6.mailtestreport_set.all()NEWLINE for report in getattr(NEWLINE getattr(batch_test, subtest),NEWLINE '{}_set'.format(report_details['name'])).all():NEWLINE report_ids[subtest].add(report.id)NEWLINENEWLINE if not report_ids[subtest]:NEWLINE return NoneNEWLINENEWLINE for i, subtest in enumerate(report_ids):NEWLINE if i == 0:NEWLINE common_report_ids = report_ids[subtest]NEWLINE else:NEWLINE common_report_ids.intersection_update(report_ids[subtest])NEWLINENEWLINE if common_report_ids:NEWLINE common_report_id = max(common_report_ids)NEWLINE report_model = batch_test._meta.get_field('report').remote_field.modelNEWLINE try:NEWLINE return report_model.objects.get(id=common_report_id)NEWLINE except report_model.DoesNotExist:NEWLINE passNEWLINE return NoneNEWLINENEWLINENEWLINEdef create_report(batch_domain):NEWLINE """NEWLINE Create the report for this domain.NEWLINE Similar to when a user is redirected to the results page.NEWLINENEWLINE """NEWLINE domain = batch_domain.domainNEWLINE if batch_domain.webtest:NEWLINE batch_test = batch_domain.webtestNEWLINE report = DomainTestReport(NEWLINE domain=domain,NEWLINE ipv6=batch_test.ipv6,NEWLINE dnssec=batch_test.dnssec,NEWLINE tls=batch_test.tls,NEWLINE appsecpriv=batch_test.appsecpriv)NEWLINE probe_reports = batch_webprobes.get_probe_reports(report)NEWLINE score = batch_webprobes.count_probe_reports_score(probe_reports)NEWLINE else:NEWLINE batch_test = batch_domain.mailtestNEWLINE report = MailTestReport(NEWLINE domain=domain,NEWLINE ipv6=batch_test.ipv6,NEWLINE dnssec=batch_test.dnssec,NEWLINE auth=batch_test.auth,NEWLINE tls=batch_test.tls)NEWLINE probe_reports = batch_mailprobes.get_probe_reports(report)NEWLINE score = batch_mailprobes.count_probe_reports_score(probe_reports)NEWLINENEWLINE report.registrar = "-Not available in batch-"NEWLINE report.score = scoreNEWLINE report.save()NEWLINE batch_test.report = reportNEWLINE batch_test.save()NEWLINENEWLINENEWLINEdef update_domain_status(batch_domain):NEWLINE """NEWLINE Check the status of the individual tests and update the domain'sNEWLINE entry status.NEWLINENEWLINE """NEWLINE if batch_domain.status == BatchDomainStatus.cancelled:NEWLINE returnNEWLINENEWLINE batch_test = batch_domain.get_batch_test()NEWLINENEWLINE if check_any_subtest_for_status(batch_test, BatchTestStatus.error):NEWLINE batch_domain.status = BatchDomainStatus.errorNEWLINE elif check_any_subtest_for_status(batch_test, BatchTestStatus.waiting):NEWLINE batch_domain.status = BatchDomainStatus.waitingNEWLINE elif check_any_subtest_for_status(batch_test, BatchTestStatus.running):NEWLINE batch_domain.status = BatchDomainStatus.runningNEWLINE else:NEWLINE batch_domain.status = BatchDomainStatus.doneNEWLINE find_or_create_report(batch_domain)NEWLINE batch_domain.status_changed = timezone.now()NEWLINE batch_domain.save(update_fields=['status_changed', 'status'])NEWLINENEWLINENEWLINEdef update_batch_status(batch_request):NEWLINE """NEWLINE Check the status of the submitted domains and update the batchNEWLINE request's status if necessary.NEWLINENEWLINE """NEWLINE if batch_request.status in (BatchRequestStatus.cancelled,NEWLINE BatchRequestStatus.done,NEWLINE BatchRequestStatus.registering,NEWLINE BatchRequestStatus.error):NEWLINE returnNEWLINENEWLINE waiting = batch_request.domains.filter(NEWLINE status=BatchDomainStatus.waiting).exists()NEWLINE running = batch_request.domains.filter(NEWLINE status=BatchDomainStatus.running).exists()NEWLINE if not waiting:NEWLINE if running:NEWLINE batch_request.status = BatchRequestStatus.runningNEWLINE else:NEWLINE batch_request.status = BatchRequestStatus.doneNEWLINE batch_request.finished_date = timezone.now()NEWLINE else:NEWLINE batch_request.status = BatchRequestStatus.liveNEWLINE batch_request.save(update_fields=['status', 'finished_date'])NEWLINENEWLINENEWLINEdef batch_callback_hook(result, task_id):NEWLINE """NEWLINE Link the result and change the status of the running test.NEWLINENEWLINE """NEWLINE if not result:NEWLINE logger.error("Post callback, no result!")NEWLINE returnNEWLINENEWLINE cache_id = redis_id.running_batch_test.id.format(task_id)NEWLINE cached = cache.get(cache_id)NEWLINE if not cached:NEWLINE logger.error(NEWLINE "Post callback, could not find task id '{}'"NEWLINE "".format(task_id))NEWLINE returnNEWLINENEWLINE batch_domain_id, subtest = cachedNEWLINE batch_domain = BatchDomain.objects.get(id=batch_domain_id)NEWLINE if batch_domain.status == BatchDomainStatus.cancelled:NEWLINE returnNEWLINENEWLINE batch_test = batch_domain.get_batch_test()NEWLINENEWLINE save_result(batch_test, subtest, result)NEWLINE cache.delete(cache_id)NEWLINE update_domain_status(batch_domain)NEWLINENEWLINENEWLINE@batch_shared_task()NEWLINEdef error_callback(request, exc, traceback):NEWLINE """NEWLINE Increase error count and change status, if an error occurs.NEWLINENEWLINE .. note:: Celery only calls this when there is an exception in the chordNEWLINE callback. This is a bug in celery. To compensate we periodicallyNEWLINE check for tests stuck in the running state withNEWLINE find_stalled_tests_and_update_db().NEWLINENEWLINE """NEWLINE logger.error("Task {0!r} raised error: {1!r}".format(request.id, exc))NEWLINE cache_id = redis_id.running_batch_test.id.format(request.id)NEWLINE cached = cache.get(cache_id)NEWLINE if not cached:NEWLINE logger.error(NEWLINE "Error callback, could not find task id '{}'"NEWLINE "".format(request.id))NEWLINE returnNEWLINENEWLINE batch_domain_id, test = cachedNEWLINE batch_domain = BatchDomain.objects.get(id=batch_domain_id)NEWLINE if batch_domain.status == BatchDomainStatus.cancelled:NEWLINE returnNEWLINENEWLINE batch_test = batch_domain.get_batch_test()NEWLINE record_subtest_error(batch_test, test)NEWLINE update_domain_status(batch_domain)NEWLINE cache.delete(cache_id)NEWLINENEWLINENEWLINEdef record_subtest_error(batch_test, subtest):NEWLINE """NEWLINE Increase and return the error count for the given subtest. Also changeNEWLINE the status if appropriate.NEWLINENEWLINE """NEWLINE error_count = getattr(batch_test, '{}_errors'.format(subtest))NEWLINE status = getattr(batch_test, '{}_status'.format(subtest))NEWLINE error_count += 1NEWLINE if status != BatchTestStatus.cancelled:NEWLINE if error_count > 2:NEWLINE status = BatchTestStatus.errorNEWLINE else:NEWLINE status = BatchTestStatus.waitingNEWLINE setattr(batch_test, '{}_status'.format(subtest), status)NEWLINE setattr(batch_test, '{}_errors'.format(subtest), error_count)NEWLINE batch_test.save(update_fields=[NEWLINE '{}_status'.format(subtest),NEWLINE '{}_errors'.format(subtest)])NEWLINE return error_countNEWLINENEWLINENEWLINEdef find_stalled_tests_and_update_db():NEWLINE """NEWLINE Find tests that have been in the running state for more than a givenNEWLINE threshold and update their status.NEWLINENEWLINE """NEWLINE running_domains = BatchDomain.objects.filter(NEWLINE status=BatchDomainStatus.running)NEWLINE now = timezone.now()NEWLINE for batch_domain in running_domains:NEWLINE timediff = (now - batch_domain.status_changed).total_seconds()NEWLINE if timediff >= settings.BATCH_MAX_RUNNING_TIME:NEWLINE if batch_domain.webtest:NEWLINE batch_test = batch_domain.webtestNEWLINE subtests = BATCH_WEBTEST['subtests']NEWLINE else:NEWLINE batch_test = batch_domain.mailtestNEWLINE subtests = BATCH_MAILTEST['subtests']NEWLINENEWLINE for subtest in subtests:NEWLINE status = getattr(batch_test, '{}_status'.format(subtest))NEWLINE if status == BatchTestStatus.running:NEWLINE errors = record_subtest_error(batch_test, subtest)NEWLINE logger.info(NEWLINE "{} errors for {}({})"NEWLINE "".format(errors, batch_domain.domain, subtest))NEWLINE update_domain_status(batch_domain)NEWLINENEWLINENEWLINEdef update_batch_request_status():NEWLINE batch_requests = BatchRequest.objects.filter(NEWLINE status__in=(BatchRequestStatus.live, BatchRequestStatus.running))NEWLINE for batch_request in batch_requests:NEWLINE update_batch_status(batch_request)NEWLINENEWLINENEWLINEdef _run_scheduler():NEWLINE """NEWLINE Submit a fixed number of domains for testing if the queue is notNEWLINE considered loaded.NEWLINENEWLINE """NEWLINE client = Rabbit(NEWLINE settings.RABBIT, settings.RABBIT_USER, settings.RABBIT_PASS)NEWLINE domains_to_test = settings.BATCH_SCHEDULER_DOMAINSNEWLINENEWLINE start_time = timer()NEWLINE find_stalled_tests_and_update_db()NEWLINE logger.info("Find stalled duration: {}".format(timer() - start_time))NEWLINENEWLINE start_time = timer()NEWLINE update_batch_request_status()NEWLINE logger.info("Update status duration: {}".format(timer() - start_time))NEWLINENEWLINE submitted = 0NEWLINE found = 0NEWLINE if not is_queue_loaded(client):NEWLINE start_time = timer()NEWLINE live_requests = get_live_requests()NEWLINE while domains_to_test > 0:NEWLINE user, batch_request = get_user_and_request(live_requests)NEWLINE if not (user or batch_request):NEWLINE breakNEWLINENEWLINE batch_domain = pick_domain(batch_request)NEWLINE if not batch_domain:NEWLINE breakNEWLINENEWLINE subtests_started = 0NEWLINE batch_test = batch_domain.get_batch_test()NEWLINE if isinstance(batch_test, BatchWebTest):NEWLINE subtests = BATCH_WEBTEST['subtests']NEWLINE else:NEWLINE subtests = BATCH_MAILTEST['subtests']NEWLINENEWLINE for subtest in subtests:NEWLINE if (getattr(batch_test, '{}_status'.format(subtest))NEWLINE == BatchTestStatus.waiting):NEWLINE started_test = check_for_result_or_start_test(NEWLINE batch_domain, batch_test, subtest,NEWLINE subtests[subtest])NEWLINE if started_test:NEWLINE subtests_started += 1NEWLINENEWLINE if subtests_started > 0:NEWLINE submitted += 1NEWLINE domains_to_test -= 1NEWLINE else:NEWLINE found += 1NEWLINE update_domain_status(batch_domain)NEWLINE logger.info("Submission duration: {}".format(timer() - start_time))NEWLINENEWLINE submitted_domains = settings.BATCH_SCHEDULER_DOMAINS - domains_to_testNEWLINE submitted_domains = submittedNEWLINE found_domains = foundNEWLINE logger.info("Submitted {} domains".format(submitted_domains))NEWLINE logger.info("Found {} domains".format(found_domains))NEWLINENEWLINENEWLINE@batch_shared_taskNEWLINEdef run():NEWLINE """NEWLINE Run the scheduler every interval only if it is not running already.NEWLINENEWLINE """NEWLINE lock_id = redis_id.batch_scheduler_lock.idNEWLINE lock_ttl = redis_id.batch_scheduler_lock.ttlNEWLINE with util.memcache_lock(lock_id, lock_ttl) as acquired:NEWLINE if acquired:NEWLINE _run_scheduler()NEWLINE returnNEWLINE logger.info("Already running...")NEWLINE |
"""NEWLINEThe script is for creating a new graphml including nodes and edges NEWLINEbased on the subset geopackage created by "sv_createSubsetData.py".NEWLINEThis can reduce the volume of graphml, which can reduce the usage of memory in pc and NEWLINEimprove performace.NEWLINENEWLINE"""NEWLINEimport osmnx as oxNEWLINEimport networkx as nxNEWLINEimport osNEWLINEimport pandas as pdNEWLINEimport geopandas as gpdNEWLINEimport timeNEWLINENEWLINENEWLINEdef creatSubGraph(graphPath, gpkg_path, graphOutput):NEWLINE print('read original grapml, and save nodes and edges to geopackage.')NEWLINE G = ox.load_graphml(graphPath)NEWLINE nodes, edges = ox.graph_to_gdfs(G)NEWLINE # nodes = nodes.astype(str)NEWLINE columns = edges.columns.tolist()NEWLINE columns.remove('geometry')NEWLINE edges[columns] = edges[columns].astype(str)NEWLINE nodes.to_file(gpkg_path, layer='nodes_original', driver='GPKG')NEWLINE edges.to_file(gpkg_path, layer='edges_original', driver='GPKG')NEWLINE # sp = gpd.read_file(gpkg_path, layer='urban_sample_points')NEWLINE # nodesIds = pd.concat([sp.n1, sp.n2])NEWLINE # node_drop = nodesIds.drop_duplicates()NEWLINE # nodes = node_drop.tolist()NEWLINE # nodes_int = list(map(int, nodes))NEWLINE print('select nodes within study region buffer.')NEWLINE region_buffer = gpd.read_file(gpkg_path,NEWLINE layer='urban_study_region_buffered')NEWLINE nodes_withinbuffer = gpd.sjoin(nodes,NEWLINE region_buffer,NEWLINE how='inner',NEWLINE op='within')NEWLINE nodes_withinbuffer = nodes_withinbuffer.drop_duplicates(subset='osmid')NEWLINE nodesIds = nodes_withinbuffer.osmid.tolist()NEWLINE nodes_int = list(map(int, nodesIds))NEWLINE print('create sub grapml.')NEWLINE G_sub = G.subgraph(nodes_int).copy()NEWLINE # print(G_sub.nodes)NEWLINE print('save sub nodes and edges to geopackage.')NEWLINE nodes_sub, edges_sub = ox.graph_to_gdfs(G_sub)NEWLINE # nodes_sub = nodes_sub.astype(str)NEWLINE cols = edges_sub.columns.tolist()NEWLINE cols.remove('geometry')NEWLINE edges_sub[cols] = edges_sub[cols].astype(str)NEWLINE nodes_sub.to_file(gpkg_path, layer='nodes_subset', driver='GPKG')NEWLINE edges_sub.to_file(gpkg_path, layer='edges_subset', driver='GPKG')NEWLINE del nodes, edgesNEWLINE del edges_sub, nodes_subNEWLINE ox.save_graphml(G_sub,NEWLINE filename=graphOutput,NEWLINE folder=os.path.join(dirname, 'data'))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE startTime = time.time()NEWLINE print('begin to process')NEWLINE dirname = os.path.abspath('')NEWLINE graph_path = os.path.join(NEWLINE dirname,NEWLINE 'data/phoenix_us_2019_10000m_pedestrian_osm_20190902_proj.graphml')NEWLINE gpkg_path = os.path.join(dirname,NEWLINE 'data/phoenix_us_2019_subset.gpkg')NEWLINE graph_output = 'phoenix_us_2019_10000m_pedestrian_osm_20190902_proj_subset.graphml'NEWLINE creatSubGraph(graph_path, gpkg_path, graph_output)NEWLINE print("finished, time is {}".format(time.time() - startTime)) |
#!/usr/bin/env pythonNEWLINE#NEWLINE# ontoviz documentation build configuration file, created byNEWLINE# sphinx-quickstart on Fri Jun 9 13:47:02 2017.NEWLINE#NEWLINE# This file is execfile()d with the current directory set to itsNEWLINE# containing dir.NEWLINE#NEWLINE# Note that not all possible configuration values are present in thisNEWLINE# autogenerated file.NEWLINE#NEWLINE# All configuration values have a default; values that are commented outNEWLINE# serve to show the default.NEWLINENEWLINE# If extensions (or modules to document with autodoc) are in anotherNEWLINE# directory, add these directories to sys.path here. If the directory isNEWLINE# relative to the documentation root, use os.path.abspath to make itNEWLINE# absolute, like shown here.NEWLINE#NEWLINEimport sysNEWLINEfrom pathlib import PathNEWLINENEWLINEthis_dir = Path(__file__).resolve().parentNEWLINEroot_dir = (this_dir / '..').resolve()NEWLINEsys.path.insert(0, str(root_dir))NEWLINEsys.path.insert(0, str(this_dir))NEWLINENEWLINEimport ontovizNEWLINENEWLINE# -- General configuration ---------------------------------------------NEWLINENEWLINE# If your documentation needs a minimal Sphinx version, state it here.NEWLINE#NEWLINE# needs_sphinx = '1.0'NEWLINENEWLINE# Add any Sphinx extension module names here, as strings. They can beNEWLINE# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.NEWLINEextensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', "autoapi", "myst_nb"]NEWLINENEWLINE# Add any paths that contain templates here, relative to this directory.NEWLINEtemplates_path = ['_templates']NEWLINENEWLINE# The suffix(es) of source filenames.NEWLINE# You can specify multiple suffix as a list of string:NEWLINE#NEWLINE# source_suffix = ['.rst', '.md']NEWLINEsource_suffix = {NEWLINE '.rst': 'restructuredtext',NEWLINE '.ipynb': 'myst-nb',NEWLINE '.md': 'myst-nb',NEWLINE}NEWLINENEWLINE# The master toctree document.NEWLINEmaster_doc = 'index'NEWLINENEWLINE# General information about the project.NEWLINEproject = 'ontoviz'NEWLINEcopyright = "2021, René Fritze"NEWLINEauthor = "René Fritze"NEWLINENEWLINE# The version info for the project you're documenting, acts as replacementNEWLINE# for |version| and |release|, also used in various other places throughoutNEWLINE# the built documents.NEWLINE#NEWLINE# The short X.Y version.NEWLINEversion = ontoviz.__version__NEWLINE# The full version, including alpha/beta/rc tags.NEWLINErelease = ontoviz.__version__NEWLINENEWLINE# The language for content autogenerated by Sphinx. Refer to documentationNEWLINE# for a list of supported languages.NEWLINE#NEWLINE# This is also used if you do content translation via gettext catalogs.NEWLINE# Usually you set "language" from the command line for these cases.NEWLINElanguage = NoneNEWLINENEWLINE# List of patterns, relative to source directory, that match files andNEWLINE# directories to ignore when looking for source files.NEWLINE# This patterns also effect to html_static_path and html_extra_pathNEWLINEexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']NEWLINENEWLINE# The name of the Pygments (syntax highlighting) style to use.NEWLINEpygments_style = 'sphinx'NEWLINENEWLINE# If true, `todo` and `todoList` produce output, else they produce nothing.NEWLINEtodo_include_todos = TrueNEWLINENEWLINENEWLINE# -- Options for HTML output -------------------------------------------NEWLINENEWLINE# The theme to use for HTML and HTML Help pages. See the documentation forNEWLINE# a list of builtin themes.NEWLINE#NEWLINEhtml_theme = 'alabaster'NEWLINENEWLINE# Theme options are theme-specific and customize the look and feel of aNEWLINE# theme further. For a list of options available for each theme, see theNEWLINE# documentation.NEWLINE#NEWLINE# html_theme_options = {}NEWLINENEWLINE# Add any paths that contain custom static files (such as style sheets) here,NEWLINE# relative to this directory. They are copied after the builtin static files,NEWLINE# so a file named "default.css" will overwrite the builtin "default.css".NEWLINEhtml_static_path = ['_static']NEWLINENEWLINENEWLINE# -- Options for HTMLHelp output ---------------------------------------NEWLINENEWLINE# Output file base name for HTML help builder.NEWLINEhtmlhelp_basename = 'ontovizdoc'NEWLINENEWLINENEWLINE# -- Options for LaTeX output ------------------------------------------NEWLINENEWLINElatex_elements = {NEWLINE # The paper size ('letterpaper' or 'a4paper').NEWLINE #NEWLINE # 'papersize': 'letterpaper',NEWLINE # The font size ('10pt', '11pt' or '12pt').NEWLINE #NEWLINE # 'pointsize': '10pt',NEWLINE # Additional stuff for the LaTeX preamble.NEWLINE #NEWLINE # 'preamble': '',NEWLINE # Latex figure (float) alignmentNEWLINE #NEWLINE # 'figure_align': 'htbp',NEWLINE}NEWLINENEWLINE# Grouping the document tree into LaTeX files. List of tuplesNEWLINE# (source start file, target name, title, author, documentclassNEWLINE# [howto, manual, or own class]).NEWLINElatex_documents = [NEWLINE (master_doc, 'ontoviz.tex', 'ontoviz Documentation', 'René Fritze', 'manual'),NEWLINE]NEWLINENEWLINENEWLINE# -- Options for manual page output ------------------------------------NEWLINENEWLINE# One entry per manual page. List of tuplesNEWLINE# (source start file, name, description, authors, manual section).NEWLINEman_pages = [(master_doc, 'ontoviz', 'ontoviz Documentation', [author], 1)]NEWLINENEWLINENEWLINE# -- Options for Texinfo output ----------------------------------------NEWLINENEWLINE# Grouping the document tree into Texinfo files. List of tuplesNEWLINE# (source start file, target name, title, author,NEWLINE# dir menu entry, description, category)NEWLINEtexinfo_documents = [NEWLINE (NEWLINE master_doc,NEWLINE 'ontoviz',NEWLINE 'ontoviz Documentation',NEWLINE author,NEWLINE 'ontoviz',NEWLINE 'One line description of project.',NEWLINE 'Miscellaneous',NEWLINE ),NEWLINE]NEWLINENEWLINEautoapi_python_use_implicit_namespaces = TrueNEWLINEautoapi_dirs = [root_dir / 'ontoviz']NEWLINEautoapi_type = 'python'NEWLINE# allows incremental buildNEWLINEautoapi_keep_files = TrueNEWLINEautoapi_template_dir = this_dir / '_templates' / 'autoapi'NEWLINENEWLINEnb_execution_mode = "cache"NEWLINE |
import asyncioNEWLINENEWLINEfrom unittest.mock import patch, MagicMockNEWLINENEWLINEfrom icap import ICAPRequest, HeadersDict, handlerNEWLINEfrom icap.session import make_session_id, should_finalize_session, get_session, SessionStorageNEWLINEfrom icap.criteria import _HANDLERSNEWLINENEWLINENEWLINEdef test_make_session_id():NEWLINE req = ICAPRequest()NEWLINE with patch('icap.session.uuid.uuid4') as mock_uuid:NEWLINE mock_uuid.return_value.hex = 'cool hash'NEWLINE assert make_session_id(req) == 'cool hash'NEWLINENEWLINE req.headers['X-Session-ID'] = 'cool session id'NEWLINENEWLINE assert make_session_id(req) == 'cool session id'NEWLINENEWLINENEWLINEdef test_SessionStorage():NEWLINE t = SessionStorage.get('foo', MagicMock())NEWLINENEWLINE assert t['id'] == 'foo'NEWLINE assert 'foo' in SessionStorage.sessionsNEWLINE assert SessionStorage.get('foo', MagicMock()) is tNEWLINENEWLINE assert SessionStorage.finalize('foo')NEWLINE assert not SessionStorage.finalize('foo')NEWLINENEWLINE assert 'foo' not in SessionStorage.sessionsNEWLINE assert SessionStorage.get('foo', MagicMock()) is not tNEWLINENEWLINENEWLINEdef test_get_session():NEWLINE request = MagicMock(headers=HeadersDict())NEWLINE request.http.request_line.uri = 'foo'NEWLINE request.headers['X-Session-ID'] = 'bar'NEWLINENEWLINE session = asyncio.get_event_loop().run_until_complete(get_session(request))NEWLINENEWLINE assert session['url'] == 'foo'NEWLINE assert session['id'] == 'bar'NEWLINENEWLINENEWLINEdef test_should_finalize_session():NEWLINE _HANDLERS.clear()NEWLINENEWLINE assert not should_finalize_session(MagicMock(is_options=True))NEWLINE assert should_finalize_session(MagicMock(is_options=False, is_respmod=True))NEWLINE assert should_finalize_session(MagicMock(is_options=False, is_respmod=False, headers=HeadersDict()))NEWLINENEWLINE request = MagicMock(is_options=False, is_respmod=False, headers=HeadersDict())NEWLINE request.headers['X-Session-ID'] = 'foo'NEWLINENEWLINE @handler()NEWLINE def respmod(request):NEWLINE passNEWLINENEWLINE @handler(name='foo')NEWLINE def respmod(request):NEWLINE passNEWLINENEWLINE for p in ['/reqmod', '/reqmod/', '/foo/reqmod', '/foo/reqmod/']:NEWLINE request.request_line.uri.path = pNEWLINE assert not should_finalize_session(request)NEWLINENEWLINE for p in ['/bar/reqmod', '/bar/reqmod/']:NEWLINE request.request_line.uri.path = pNEWLINE assert should_finalize_session(request)NEWLINE |
# Licensed to the Apache Software Foundation (ASF) under oneNEWLINE# or more contributor license agreements. See the NOTICE fileNEWLINE# distributed with this work for additional informationNEWLINE# regarding copyright ownership. The ASF licenses this fileNEWLINE# to you under the Apache License, Version 2.0 (theNEWLINE# "License"); you may not use this file except in complianceNEWLINE# with the License. You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing,NEWLINE# software distributed under the License is distributed on anNEWLINE# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYNEWLINE# KIND, either express or implied. See the License for theNEWLINE# specific language governing permissions and limitationsNEWLINE# under the License.NEWLINE"""Test code for 3d convolution with winograd."""NEWLINENEWLINEimport numpy as npNEWLINEimport tvmNEWLINEfrom tvm import teNEWLINEfrom tvm import autotvmNEWLINEfrom tvm import topiNEWLINEimport tvm.testingNEWLINEimport tvm.topi.testingNEWLINEfrom tvm.contrib.pickle_memoize import memoizeNEWLINEfrom tvm.topi.nn.utils import get_pad_tuple3dNEWLINEfrom tvm.topi.utils import get_const_tupleNEWLINENEWLINENEWLINE_conv3d_ncdhw_implement = {NEWLINE "gpu": (topi.cuda.conv3d_ncdhw_winograd, topi.cuda.schedule_conv3d_ncdhw_winograd),NEWLINE}NEWLINENEWLINENEWLINEdef verify_conv3d_ncdhw(NEWLINE batch,NEWLINE in_channel,NEWLINE in_size,NEWLINE num_filter,NEWLINE depth_kernel,NEWLINE space_kernel,NEWLINE stride,NEWLINE padding,NEWLINE dilation=1,NEWLINE add_bias=False,NEWLINE add_relu=False,NEWLINE):NEWLINE pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right = get_pad_tuple3d(NEWLINE padding, (depth_kernel, space_kernel, space_kernel)NEWLINE )NEWLINE padding_sum = pad_front + pad_back + pad_top + pad_left + pad_bottom + pad_rightNEWLINE print(NEWLINE "Workload: (%d, %d, %d, %d, %d, %d, %d, %d)"NEWLINE % (batch, in_channel, in_size, num_filter, space_kernel, stride, padding_sum, dilation)NEWLINE )NEWLINENEWLINE in_depth = in_height = in_width = in_sizeNEWLINENEWLINE A = te.placeholder((batch, in_channel, in_depth, in_height, in_width), name="A")NEWLINE W = te.placeholder((num_filter, in_channel, depth_kernel, space_kernel, space_kernel), name="W")NEWLINE bias = te.placeholder((num_filter, 1, 1, 1), name="bias")NEWLINENEWLINE a_shape = get_const_tuple(A.shape)NEWLINE w_shape = get_const_tuple(W.shape)NEWLINE bias_shape = get_const_tuple(bias.shape)NEWLINE dtype = A.dtypeNEWLINENEWLINE @memoize("topi.tests.test_topi_conv3d_ncdhw.verify_conv3d_ncdhw")NEWLINE def get_ref_data():NEWLINE a_np = np.random.uniform(size=a_shape).astype(dtype)NEWLINE w_np = np.random.uniform(size=w_shape).astype(dtype)NEWLINE b_np = np.random.uniform(size=bias_shape).astype(dtype)NEWLINE dw_np = tvm.topi.testing.dilate_python(w_np, (1, 1, dilation, dilation, dilation))NEWLINE c_np = tvm.topi.testing.conv3d_ncdhw_python(a_np, dw_np, stride, padding)NEWLINE if add_bias:NEWLINE c_np += b_npNEWLINE if add_relu:NEWLINE c_np = np.maximum(c_np, 0)NEWLINE return a_np, w_np, b_np, c_npNEWLINENEWLINE a_np, w_np, b_np, c_np = get_ref_data()NEWLINENEWLINE def check_device(device):NEWLINE ctx = tvm.context(device, 0)NEWLINE if not tvm.testing.device_enabled(device):NEWLINE print("Skip because %s is not enabled" % device)NEWLINE returnNEWLINE print("Running on target: %s" % device)NEWLINE fcompute, fschedule = tvm.topi.testing.dispatch(device, _conv3d_ncdhw_implement)NEWLINE with tvm.target.Target(device):NEWLINE C = fcompute(NEWLINE A, W, (stride, stride, stride), padding, (dilation, dilation, dilation), dtypeNEWLINE )NEWLINE if add_bias:NEWLINE C = topi.add(C, bias)NEWLINE if add_relu:NEWLINE C = topi.nn.relu(C)NEWLINE s = fschedule([C])NEWLINENEWLINE a = tvm.nd.array(a_np, ctx)NEWLINE w = tvm.nd.array(w_np, ctx)NEWLINE b = tvm.nd.array(b_np, ctx)NEWLINE c = tvm.nd.array(np.zeros(get_const_tuple(C.shape), dtype=C.dtype), ctx)NEWLINE if add_bias:NEWLINE func = tvm.build(NEWLINE s,NEWLINE [A, W, bias, C],NEWLINE device,NEWLINE name="relu_%d_%d_%d_%d_%d_%d_%d_%d"NEWLINE % (NEWLINE batch,NEWLINE in_channel,NEWLINE in_size,NEWLINE num_filter,NEWLINE space_kernel,NEWLINE stride,NEWLINE padding_sum,NEWLINE dilation,NEWLINE ),NEWLINE )NEWLINE func(a, w, b, c)NEWLINE else:NEWLINE func = tvm.build(NEWLINE s,NEWLINE [A, W, C],NEWLINE device,NEWLINE name="relu_%d_%d_%d_%d_%d_%d_%d_%d"NEWLINE % (NEWLINE batch,NEWLINE in_channel,NEWLINE in_size,NEWLINE num_filter,NEWLINE space_kernel,NEWLINE stride,NEWLINE padding_sum,NEWLINE dilation,NEWLINE ),NEWLINE )NEWLINE func(a, w, c)NEWLINE tvm.testing.assert_allclose(c.asnumpy(), c_np, rtol=1e-4)NEWLINENEWLINE for device in ["cuda"]:NEWLINE with autotvm.tophub.context(device): # load tophub pre-tuned parametersNEWLINE check_device(device)[email protected]_gpuNEWLINEdef test_conv3d_ncdhw():NEWLINE # Try without depth transformationNEWLINE # 3DCNN workloadsNEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 3, 3, 1, 0)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 1, 3, 1, 0)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 5, 3, 1, 0)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 5, 5, 1, 2)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 1, 5, 1, 2)NEWLINE verify_conv3d_ncdhw(1, 61, 20, 120, 7, 7, 1, 3)NEWLINE verify_conv3d_ncdhw(1, 128, 12, 256, 3, 3, 1, 1)NEWLINE verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1)NEWLINENEWLINE # bias, reluNEWLINE verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1, add_relu=True)NEWLINE verify_conv3d_ncdhw(1, 64, 12, 128, 3, 3, 1, 1, add_relu=True, add_bias=True)NEWLINE verify_conv3d_ncdhw(1, 64, 12, 128, 1, 3, 1, 1, add_relu=True, add_bias=True)NEWLINENEWLINE # dilation = 2NEWLINE verify_conv3d_ncdhw(1, 16, 12, 16, 3, 3, 1, "VALID", dilation=2)NEWLINE verify_conv3d_ncdhw(1, 16, 12, 16, 1, 3, 1, "VALID", dilation=2)NEWLINENEWLINE # batch sizeNEWLINE verify_conv3d_ncdhw(4, 32, 12, 64, 3, 3, 1, 1)NEWLINE verify_conv3d_ncdhw(4, 32, 12, 64, 1, 3, 1, 1)NEWLINENEWLINE # weird workloadsNEWLINE verify_conv3d_ncdhw(2, 2, 2, 2, 3, 3, 1, 2)NEWLINE verify_conv3d_ncdhw(3, 3, 3, 3, 3, 3, 1, 3)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE test_conv3d_ncdhw()NEWLINE |
import osNEWLINEimport shutilNEWLINENEWLINEimport mathNEWLINEimport sysNEWLINENEWLINEANSI_ESCAPE_SEQUENCE_START = '\x1b'NEWLINEANSI_ESCAPE_SEQUENCE_END = 'm'NEWLINENEWLINENEWLINEdef get_terminal_width():NEWLINE # when piping stdout linux is executing commands in separate process (terminal-less), that's why shutil won't workNEWLINE # so instead of "echo x | program.py | cat" you should use "echo x | (export COLUMNS; program.py | cat"NEWLINENEWLINE # because PyCharm is using separate process for execution, shutil.get_terminal_size() is giving 80, 24NEWLINE if "PYCHARM_HOSTED" in os.environ:NEWLINE return 210NEWLINENEWLINE return shutil.get_terminal_size().columnsNEWLINENEWLINENEWLINEdef get_terminal_height():NEWLINE # when piping stdout linux is executing commands in separate process (terminal-less), that's why shutil won't workNEWLINE # so instead of "echo x | program.py | cat" you should use "echo x | (export COLUMNS; program.py | cat"NEWLINENEWLINE # because PyCharm is using separate process for execution, shutil.get_terminal_size() is giving 80, 24NEWLINE if "PYCHARM_HOSTED" in os.environ:NEWLINE return 40NEWLINENEWLINE return shutil.get_terminal_size().linesNEWLINENEWLINENEWLINEdef fit_text(text, width=None, already_used_characters=0, postfix='...'):NEWLINE width = width or get_terminal_width()NEWLINE if already_used_characters + len(text) > width - len(postfix):NEWLINE return text[:width - already_used_characters - len(postfix)] + postfixNEWLINE else:NEWLINE return textNEWLINENEWLINENEWLINE# TODO: instead of three letter "..." use one character elypsisis: "…" (few places here and maybe another elsewhere?)NEWLINEdef fit_text_printable_part_only(text, width=None, already_used_characters=0, postfix_if_cant_fit='...'):NEWLINE width = width or get_terminal_width()NEWLINE return get_printable_text_substring(text, 0, width - already_used_characters,NEWLINE postfix_if_cant_fit=postfix_if_cant_fit)NEWLINENEWLINENEWLINEdef get_printable_text_substring(text, _from, _len, postfix_if_cant_fit='...'):NEWLINE # print(f'get_printable_text_substring({repr(text)}, {_from}, {_len})')NEWLINE # TODO: https://unix.stackexchange.com/questions/111899/how-to-strip-color-codes-out-of-stdout-and-pipe-to-file-and-stdoutNEWLINE escape_sequence_in_progress = FalseNEWLINE printable_characters = 0NEWLINE output = []NEWLINE flags = []NEWLINE characters_to_skip = _fromNEWLINE characters_skipped = 0NEWLINE for character in text:NEWLINE if character == ANSI_ESCAPE_SEQUENCE_START:NEWLINE escape_sequence_in_progress = TrueNEWLINENEWLINE if printable_characters >= _len and not escape_sequence_in_progress: # text is longer than we can fitNEWLINE if len(postfix_if_cant_fit) > 0:NEWLINE removed_so_far = 0NEWLINE for i in range(len(output) - 1, 0, -1):NEWLINE if not flags[i]: # not non-printable = printableNEWLINE removed_so_far += 1NEWLINE del output[i]NEWLINE if removed_so_far == len(postfix_if_cant_fit):NEWLINE breakNEWLINENEWLINE output.extend(list(postfix_if_cant_fit))NEWLINE breakNEWLINENEWLINE if characters_skipped < characters_to_skip: # if we still skipping X printable charactersNEWLINE if not escape_sequence_in_progress:NEWLINE characters_skipped += 1NEWLINE else: # normal mode (after skipping)NEWLINE output.append(character)NEWLINE flags.append(escape_sequence_in_progress)NEWLINENEWLINE if not escape_sequence_in_progress:NEWLINE printable_characters += 1NEWLINENEWLINE if escape_sequence_in_progress and character == ANSI_ESCAPE_SEQUENCE_END:NEWLINE escape_sequence_in_progress = FalseNEWLINENEWLINE return ''.join(output)NEWLINENEWLINENEWLINEdef get_printable_text_length(text):NEWLINE escape_sequence_in_progress = FalseNEWLINE printable_characters = 0NEWLINE current_sequence_length = 0NEWLINE for character in text.rstrip():NEWLINE if character == ANSI_ESCAPE_SEQUENCE_START:NEWLINE escape_sequence_in_progress = TrueNEWLINE current_sequence_length = 0NEWLINENEWLINE if not escape_sequence_in_progress:NEWLINE printable_characters += 1NEWLINE else:NEWLINE current_sequence_length += 1NEWLINENEWLINE if escape_sequence_in_progress and character == ANSI_ESCAPE_SEQUENCE_END:NEWLINE escape_sequence_in_progress = FalseNEWLINE current_sequence_length = 0NEWLINENEWLINE printable_characters += current_sequence_lengthNEWLINENEWLINE return printable_charactersNEWLINENEWLINENEWLINEdef get_last_ansi_sequence(text):NEWLINE starting_pos = text.rfind(ANSI_ESCAPE_SEQUENCE_START)NEWLINE if starting_pos == -1:NEWLINE return ''NEWLINE ending_pos = text.find(ANSI_ESCAPE_SEQUENCE_END, starting_pos)NEWLINE if ending_pos == -1:NEWLINE return ''NEWLINENEWLINE return text[starting_pos:ending_pos + 1]NEWLINENEWLINENEWLINEdef colorized_center(text, width, fill_char, left_color, middle_color, right_color, rainbow=False):NEWLINE output = ''NEWLINE text_len = len(str(text))NEWLINE remaining_len = width - text_lenNEWLINE for i in range(int(math.floor(remaining_len / 2))):NEWLINE cur_color_index = left_color if not rainbow else i % 16NEWLINE output += colorize_text(fill_char, cur_color_index)NEWLINE output += colorize_text(text, middle_color)NEWLINE for i in range(int(math.ceil(remaining_len / 2))):NEWLINE cur_color_index = right_color if not rainbow else i % 16NEWLINE output += colorize_text(fill_char, cur_color_index)NEWLINE output += colorize_text('', 255)NEWLINE return outputNEWLINENEWLINENEWLINE# TODO: split into color_start, color_end then implement:NEWLINE# def colorize_text(text, color, normal_color):NEWLINE# return color_start(color) + text + color_end(normal_color)NEWLINENEWLINENEWLINEdef colorize_text(text, color):NEWLINE return f'\x1b[38;5;{color}m{text}'NEWLINENEWLINENEWLINEdef reset_color():NEWLINE return '\x1b[39m'NEWLINENEWLINENEWLINEdef clear_to_end_of_line():NEWLINE return '\x1b[K'NEWLINENEWLINENEWLINEdef clear_to_end_of_screen():NEWLINE return '\x1b[J'NEWLINENEWLINENEWLINEdef get_underscore_start():NEWLINE return '\x1b[4m'NEWLINENEWLINENEWLINEdef get_underscore_end():NEWLINE return '\x1b[24m'NEWLINENEWLINENEWLINEdef get_move_left(character_count):NEWLINE if character_count > 0:NEWLINE return f'\x1b[{character_count}D'NEWLINE else:NEWLINE return ''NEWLINENEWLINENEWLINEdef get_move_up(lines):NEWLINE return f'\x1b[{lines}A'NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE orig = '12345\x1b[38;5;m1'NEWLINE for i in range(4, 6 + 1):NEWLINE out_dots = get_printable_text_substring(orig, 0, i)NEWLINE out_empty = get_printable_text_substring(orig, 0, i, postfix_if_cant_fit="")NEWLINE print(f'{i}# {orig} + "..." -> {out_dots} ({len(out_dots)}:{get_printable_text_length(out_dots)})')NEWLINE print(f'{i}# {orig} + "" -> {out_empty} ({len(out_empty)}:{get_printable_text_length(out_empty)})')NEWLINENEWLINENEWLINEdef replace_whitespace_characters_by_their_representations(original_lines):NEWLINE # TODO: use string.translateNEWLINE replace_pairs = [['\n', '\\n'], ['\t', '\\t'], ['\r', '\\r'], ['\f', '\\f'], ['\b', '\\b'], ['\x0b', '\\x0b']]NEWLINE text = original_linesNEWLINE for replace_from, replace_to in replace_pairs:NEWLINE text = text.replace(replace_from, replace_to)NEWLINE return textNEWLINENEWLINENEWLINEdef is_piping_text():NEWLINE return not os.isatty(sys.stdin.fileno())NEWLINENEWLINENEWLINEdef read_text_from_pipe(encoding='utf8', errors='replace'):NEWLINE return sys.stdin.buffer.read().decode(encoding, errors)NEWLINE |
from django.core.cache import get_cacheNEWLINEfrom avocado.conf import settingsNEWLINEfrom .model import instance_cache_key, NEVER_EXPIRENEWLINENEWLINENEWLINEdef post_save_cache(sender, instance, **kwargs):NEWLINE """General post-save handler for caching model instances. NOTE: This mustNEWLINE be used in conjunction with the `pre_delete_uncache` since the cache is setNEWLINE to never expire.NEWLINE """NEWLINE cache = get_cache(settings.DATA_CACHE)NEWLINE cache.set(instance_cache_key(instance), instance, timeout=NEVER_EXPIRE)NEWLINENEWLINENEWLINEdef pre_delete_uncache(sender, instance, **kwargs):NEWLINE "General post-delete handler for removing cache for model instances."NEWLINE cache = get_cache(settings.DATA_CACHE)NEWLINE cache.delete(instance_cache_key(instance))NEWLINE |
NEWLINEimport sys, jsonNEWLINEimport cv2NEWLINEimport torchNEWLINENEWLINEPATH_EL = "../entity-linking/"NEWLINEsys.path.insert(0, PATH_EL)NEWLINENEWLINEimport clickNEWLINEimport tqdmNEWLINEfrom pycorenlp import StanfordCoreNLPNEWLINENEWLINEfrom entitylinking import core as ELNEWLINEfrom entitylinking.core.sentence import SentenceEncoderNEWLINENEWLINENEWLINEcorenlp = StanfordCoreNLP('http://semanticparsing:9000')NEWLINEcorenlp_properties = {NEWLINE 'annotators': 'tokenize, pos, ner',NEWLINE 'outputFormat': 'json'NEWLINE}NEWLINENEWLINEEL.candidate_retrieval.entity_linking_p['max.match.diff'] = 0NEWLINENEWLINEEL.mention_extraction.np_parser = EL.mention_extraction.NgramNpParser(NEWLINE exclude_pos={".", "ORDINAL", "TIME", "PERCENT", "NUMBER"},NEWLINE exclude_if_first={"WDT", "WP", "WP$", "WRB", "VBZ", "VB", "VBP"},NEWLINE exclude_prefix={"IN", "DT", "CC", "POS"},NEWLINE exclude_suffix={"IN", "DT", "CC", "JJ", "RB", "JJR", "JJS", "RBR", "RBS"},NEWLINE exclude_alone={"IN", "DT", "PDT", "POS", "PRP", "PRP$", "CC", "TO",NEWLINE "VBZ", "VBD", "VBP", "VB", "VBG", "VBN",NEWLINE "JJ", "RB", "JJR", "JJS", "RBR", "RBS",NEWLINE "MD", "WDT", "WP", "WP$", "WRB"NEWLINE })[email protected]()[email protected]('path_to_file')[email protected]('output_file')NEWLINEdef apply(path_to_file, output_file):NEWLINENEWLINE entitylinker = EL.MLLinker(path_to_model="../entity-linking/trainedmodels/VectorModel_137.torchweights",NEWLINE confidence=0.01,NEWLINE num_candidates=3,NEWLINE max_mention_len=2)NEWLINENEWLINE with open(path_to_file) as f:NEWLINE input_data = [l.strip().split(",") for l in f.readlines()][1:]NEWLINENEWLINE output_data = {}NEWLINE for parts in tqdm.tqdm(input_data):NEWLINE output_per_story = []NEWLINE for i in range(1, 7):NEWLINE s = parts[i]NEWLINE sent = entitylinker.link_entities_in_sentence_obj(EL.sentence.Sentence(input_text=s))NEWLINE sent.entities = [{k: e[k] for k in {'type', 'linkings', 'token_ids', 'poss', 'tokens', 'drop_score'}}NEWLINE for e in sent.entities if len(e['linkings']) > 0]NEWLINE for e in sent.entities:NEWLINE e['linkings'] = [(l.get('kbID'), l.get('label')) for l in e['linkings']]NEWLINE output_per_story.append(sent)NEWLINE output_data[parts[0]] = output_per_storyNEWLINE with open(output_file, "w") as out:NEWLINE json.dump(output_data, out, sort_keys=True, indent=4, cls=SentenceEncoder)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE apply()NEWLINE |
# Copyright 2021 Arbaaz LaskarNEWLINENEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINENEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINENEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEfrom typing import TupleNEWLINEimport reNEWLINEimport osNEWLINEimport sysNEWLINEimport hashlibNEWLINENEWLINEfrom colorama import Fore, StyleNEWLINEfrom tqdm import tqdmNEWLINEfrom loguru import loggerNEWLINEimport typerNEWLINENEWLINEfrom .fichub import FicHubNEWLINEfrom .logging import downloaded_logNEWLINENEWLINENEWLINEdef get_format_type(_format: str = "epub") -> int:NEWLINE if re.search(r"\bepub\b", _format, re.I):NEWLINE format_type = 0NEWLINENEWLINE elif re.search(r"\bmobi\b", _format, re.I):NEWLINE format_type = 1NEWLINENEWLINE elif re.search(r"\bpdf\b", _format, re.I):NEWLINE format_type = 2NEWLINENEWLINE elif re.search(r"\bhtml\b", _format, re.I):NEWLINE format_type = 3NEWLINENEWLINE else: # default epub formatNEWLINE format_type = 0NEWLINENEWLINE return format_typeNEWLINENEWLINENEWLINEdef check_url(url: str, debug: bool = False,NEWLINE exit_status: int = 0) -> Tuple[bool, int]:NEWLINENEWLINE if re.search(r"\barchiveofourown.org/series\b", url):NEWLINE unsupported_flag = TrueNEWLINENEWLINE elif re.search(r"\bfanfiction.net/u\b", url):NEWLINE unsupported_flag = TrueNEWLINENEWLINE else:NEWLINE unsupported_flag = FalseNEWLINENEWLINE if unsupported_flag:NEWLINE with open("err.log", "a") as file:NEWLINE file.write(url)NEWLINENEWLINE exit_status = 1NEWLINENEWLINE if debug:NEWLINE logger.error(NEWLINE f"Skipping unsupported URL: {url}")NEWLINE else:NEWLINE tqdm.write(NEWLINE Fore.RED + f"\nSkipping unsupported URL: {url}" +NEWLINE Style.RESET_ALL + Fore.CYAN +NEWLINE "\nTo see the supported site list, use " + Fore.YELLOW +NEWLINE "fichub_cli -ss" + Style.RESET_ALL + Fore.CYAN +NEWLINE "\nReport the error if the URL is supported!\n")NEWLINENEWLINE return False, exit_statusNEWLINENEWLINE else: # for supported urlsNEWLINE return True, exit_statusNEWLINENEWLINENEWLINEdef save_data(out_dir: str, file_name: str, download_url: str,NEWLINE debug: bool, force: bool, cache_hash: str,NEWLINE exit_status: int, automated: bool) -> int:NEWLINENEWLINE ebook_file = os.path.join(out_dir, file_name)NEWLINE try:NEWLINE hash_flag = check_hash(ebook_file, cache_hash)NEWLINENEWLINE except FileNotFoundError:NEWLINE hash_flag = FalseNEWLINENEWLINE if os.path.exists(ebook_file) and force is False and hash_flag is True:NEWLINENEWLINE exit_status = 1NEWLINE if debug:NEWLINE logger.warning(NEWLINE "The hash of the local file & the remote file is the same.")NEWLINENEWLINE logger.error(NEWLINE f"{ebook_file} is already the latest version. Skipping download. Use --force flag to overwrite.")NEWLINENEWLINE else:NEWLINE tqdm.write(NEWLINE Fore.RED +NEWLINE f"{ebook_file} is already the latest version. Skipping download." +NEWLINE Style.RESET_ALL + Fore.CYAN + " Use --force flag to overwrite.")NEWLINENEWLINE else:NEWLINE if force and debug:NEWLINE logger.warning(NEWLINE f"--force flag was passed. Overwriting {ebook_file}")NEWLINENEWLINE fic = FicHub(debug, automated, exit_status)NEWLINE fic.get_fic_data(download_url)NEWLINENEWLINE try:NEWLINE with open(ebook_file, "wb") as f:NEWLINE if debug:NEWLINE logger.info(NEWLINE f"Saving {ebook_file}")NEWLINE f.write(fic.response_data.content)NEWLINE downloaded_log(debug, file_name)NEWLINE except FileNotFoundError:NEWLINE tqdm.write(Fore.RED + "Output directory doesn't exist. Exiting!")NEWLINE sys.exit(1)NEWLINENEWLINE return exit_statusNEWLINENEWLINENEWLINEdef check_hash(ebook_file: str, cache_hash: str) -> bool:NEWLINENEWLINE with open(ebook_file, 'rb') as file:NEWLINE data = file.read()NEWLINENEWLINE ebook_hash = hashlib.md5(data).hexdigest()NEWLINENEWLINE if ebook_hash.strip() == cache_hash.strip():NEWLINE hash_flag = TrueNEWLINE else:NEWLINE hash_flag = FalseNEWLINENEWLINE return hash_flagNEWLINENEWLINENEWLINEdef out_dir_exists_check(out_dir):NEWLINE """Check if the output directory exists"""NEWLINE if not os.path.isdir(out_dir):NEWLINE mkdir_prompt = typer.prompt(NEWLINE Fore.RED+"Output directory doesn't exist!" + Style.RESET_ALL +NEWLINE Fore.BLUE + f"\nShould the CLI create {out_dir}?(y/n)")NEWLINE if mkdir_prompt == 'y':NEWLINE os.mkdir(out_dir)NEWLINE |
# Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.NEWLINE#NEWLINE# This work is made available under the Nvidia Source Code License-NC.NEWLINE# To view a copy of this license, check out LICENSE.mdNEWLINE# import torchNEWLINEimport mathNEWLINENEWLINEfrom torch.optim.optimizer import Optimizer, requiredNEWLINENEWLINENEWLINEclass Fromage(Optimizer):NEWLINE r"""Fromage optimizer implementation (https://arxiv.org/abs/2002.03432)"""NEWLINENEWLINE def __init__(self, params, lr=required, momentum=0):NEWLINE if lr is not required and lr < 0.0:NEWLINE raise ValueError("Invalid learning rate: {}".format(lr))NEWLINE defaults = dict(lr=lr, momentum=momentum)NEWLINE super(Fromage, self).__init__(params, defaults)NEWLINENEWLINE def step(self, closure=None):NEWLINE r"""Performs a single optimization step.NEWLINENEWLINE Args:NEWLINE closure (callable, optional): A closure that reevaluates the modelNEWLINE and returns the loss.NEWLINE """NEWLINE loss = NoneNEWLINE if closure is not None:NEWLINE loss = closure()NEWLINENEWLINE for group in self.param_groups:NEWLINE for p in group['params']:NEWLINE if p.grad is None:NEWLINE continueNEWLINE d_p = p.grad.dataNEWLINE d_p_norm = p.grad.norm()NEWLINE p_norm = p.norm()NEWLINE if p_norm > 0.0 and d_p_norm > 0.0:NEWLINE p.data.add_(-group['lr'], d_p * (p_norm / d_p_norm))NEWLINE else:NEWLINE p.data.add_(-group['lr'], d_p)NEWLINE p.data /= math.sqrt(1 + group['lr'] ** 2)NEWLINENEWLINE return lossNEWLINE |
# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""UI tests for /bundle page"""NEWLINENEWLINEimport osNEWLINEfrom typing import ListNEWLINENEWLINEimport allureNEWLINEimport pytestNEWLINEfrom adcm_client.objects import ADCMClient, BundleNEWLINEfrom adcm_pytest_plugin import utilsNEWLINEfrom adcm_pytest_plugin.utils import catch_failedNEWLINEfrom selenium.common.exceptions import ElementClickInterceptedExceptionNEWLINENEWLINEfrom tests.conftest import DUMMY_CLUSTER_BUNDLENEWLINEfrom tests.ui_tests.app.app import ADCMTestNEWLINEfrom tests.ui_tests.app.page.admin.page import AdminIntroPageNEWLINEfrom tests.ui_tests.app.page.bundle.page import BundlePageNEWLINEfrom tests.ui_tests.app.page.bundle_list.page import BundleListPage, BundleInfoNEWLINEfrom tests.ui_tests.app.page.cluster_list.page import ClusterListPageNEWLINEfrom tests.ui_tests.app.page.host_list.page import HostListPageNEWLINENEWLINELICENSE_FP = os.path.join(utils.get_data_dir(__file__), 'license.txt')NEWLINENEWLINECLUSTER_CE_CONFIG = DUMMY_CLUSTER_BUNDLENEWLINENEWLINECLUSTER_EE_CONFIG = [NEWLINE {NEWLINE **CLUSTER_CE_CONFIG[0],NEWLINE 'description': 'enterprise description',NEWLINE 'license': 'license.txt',NEWLINE 'edition': 'enterprise',NEWLINE }NEWLINE]NEWLINENEWLINEPROVIDER_CONFIG = [NEWLINE {NEWLINE 'type': 'provider',NEWLINE 'name': 'test_provider',NEWLINE 'version': '2.15-dev',NEWLINE },NEWLINE {NEWLINE 'type': 'host',NEWLINE 'name': 'Test Host',NEWLINE 'description': 'Test Host Description',NEWLINE 'version': '2.15-dev',NEWLINE },NEWLINE]NEWLINENEWLINENEWLINEdef _assert_bundle_info_value(attribute: str, actual_info: BundleInfo, expected_info: BundleInfo):NEWLINE actual_value = getattr(actual_info, attribute)NEWLINE expected_value = getattr(expected_info, attribute)NEWLINE assert actual_value == expected_value, f"Bundle's {attribute} should be {expected_value}, not {actual_value}"NEWLINENEWLINENEWLINE# pylint: [email protected]('Check bundle list is empty')NEWLINEdef _check_bundle_list_is_empty(page: BundleListPage):NEWLINE assert (row_count := page.table.row_count) == 0, f'Bundle list should be empty, but {row_count} records was found'[email protected]('Check bundle is listed in table')NEWLINEdef _open_bundle_list_and_check_info(page: BundleListPage, expected_info: BundleInfo):NEWLINE """NEWLINE Open bundle list page, check that exactly 1 row is presented and check it's infoNEWLINE """NEWLINE page.open()NEWLINE assert (NEWLINE row_count := page.table.row_countNEWLINE ) == 1, f'Bundle list should have exactly 1 record, but {row_count} was found'NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, expected_info)[email protected]('Check bundle info')NEWLINEdef check_bundle_info_is_equal(actual_info: BundleInfo, expected_info: BundleInfo):NEWLINE """Assert bundle attrs values"""NEWLINE for attr in ('name', 'description', 'version', 'edition'):NEWLINE _assert_bundle_info_value(attr, actual_info, expected_info)[email protected]()NEWLINE# pylint: disable-next=unused-argumentNEWLINEdef page(app_fs: ADCMTest, login_to_adcm_over_api) -> BundleListPage:NEWLINE """Get BundleListPage after authorization"""NEWLINE return BundleListPage(app_fs.driver, app_fs.adcm.url).open()[email protected]("Upload bundles")[email protected]()NEWLINEdef upload_bundles(create_bundle_archives: List[str], sdk_client_fs: ADCMClient) -> List[Bundle]:NEWLINE """Upload bundles to ADCM"""NEWLINE return [sdk_client_fs.upload_from_fs(path) for path in create_bundle_archives][email protected]()NEWLINEdef _create_cluster(upload_bundles: List[Bundle]):NEWLINE """Upload bundles and create cluster from first bundle"""NEWLINE upload_bundles[0].cluster_create('Best Cluster Ever')[email protected]()NEWLINEdef test_ce_bundle_upload(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload community bundle"""NEWLINE bundle_params = BundleInfo(NEWLINE name="test_cluster", version="1.5", edition="community", description="community description"NEWLINE )NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, bundle_params)[email protected]()[email protected]("create_bundle_archives", [([CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=True)NEWLINEdef test_ee_bundle_upload(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload enterprise bundle and accept licence"""NEWLINE bundle_params = BundleInfo(NEWLINE name='test_cluster',NEWLINE version='1.5',NEWLINE edition='enterprise',NEWLINE description='enterprise description',NEWLINE )NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE page.accept_licence()NEWLINE bundle_info = page.get_bundle_info()NEWLINE check_bundle_info_is_equal(bundle_info, bundle_params)[email protected]()NEWLINEdef test_delete_bundle(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload bundle and delete it"""NEWLINE with allure.step('Upload bundle'):NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE assert page.table.row_count == 1, 'One bundle should be uploaded'NEWLINE with allure.step('Delete bundle'):NEWLINE page.delete_bundle()NEWLINE assert page.table.row_count == 0, 'No bundle should be listed in the table'[email protected](NEWLINE "create_bundle_archives", [([CLUSTER_CE_CONFIG, CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=TrueNEWLINE)NEWLINEdef test_two_bundles(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload two bundles"""NEWLINE with allure.step('Upload 1st bundle'), page.table.wait_rows_change():NEWLINE page.upload_bundle(create_bundle_archives[0])NEWLINE with allure.step('Upload 2nd bundle'), page.table.wait_rows_change():NEWLINE page.upload_bundle(create_bundle_archives[1])NEWLINE with allure.step('Check there are exactly 2 rows'):NEWLINE rows = page.table.row_countNEWLINE assert rows == 2, f'Row amount should be 2, but only {rows} is presented'[email protected]("https://arenadata.atlassian.net/browse/ADCM-2010")[email protected](reason="Not worked using selenoid https://github.com/aerokube/selenoid/issues/844")[email protected](NEWLINE "create_bundle_archives", [([CLUSTER_CE_CONFIG, CLUSTER_EE_CONFIG], LICENSE_FP)], indirect=TrueNEWLINE)NEWLINEdef test_accept_license_with_two_bundles_upload_at_once(create_bundle_archives: List[str], page: BundleListPage):NEWLINE """Upload two bundles and accept license"""NEWLINE with page.table.wait_rows_change():NEWLINE page.upload_bundles(create_bundle_archives)NEWLINE with catch_failed(ElementClickInterceptedException, "License was not accepted by single button click"):NEWLINE page.accept_licence(row_num=1)[email protected]()NEWLINEdef test_open_bundle_from_table(page: BundleListPage, upload_bundles: List[Bundle]):NEWLINE """Test open bundle object page from list of bundles"""NEWLINE with allure.step('Open bundle object page from bundle list'):NEWLINE page.click_bundle_in_row(page.table.get_row())NEWLINE with allure.step('Check object page is opened'):NEWLINE object_page = BundlePage(page.driver, page.base_url, upload_bundles[0].id)NEWLINE object_page.wait_page_is_opened()[email protected]()NEWLINEdef test_open_main_menu_on_bundle_page(page: BundleListPage, upload_bundles: List[Bundle]):NEWLINE """Open main menu on bundle detailed page"""NEWLINE with allure.step('Open bundle object page'):NEWLINE object_page = BundlePage(page.driver, page.base_url, upload_bundles[0].id)NEWLINE object_page.open()NEWLINE object_page.open_main_menu()NEWLINE object_page.check_all_main_menu_fields_are_presented()[email protected]('upload_bundles')NEWLINEdef test_open_adcm_main_menu(page: BundleListPage):NEWLINE """Open main menu by clicking on the menu icon in toolbar"""NEWLINE page.click_on_home_button_on_tooltip()NEWLINE AdminIntroPage(page.driver, page.base_url).wait_page_is_opened()[email protected]("_create_cluster")NEWLINEdef test_delete_bundle_with_created_cluster(page: BundleListPage):NEWLINE """NEWLINE Bundle should not be deleted if an object defined in it is createdNEWLINE """NEWLINE page.delete_bundle()NEWLINE page.check_at_least_one_bundle_is_presented()[email protected]()[email protected](NEWLINE "create_bundle_archives",NEWLINE [[PROVIDER_CONFIG]],NEWLINE indirect=True,NEWLINE ids=['provider_bundle'],NEWLINE)NEWLINEdef test_upload_provider_bundle_from_another_page(NEWLINE page: BundleListPage, app_fs: ADCMTest, create_bundle_archives: List[str]NEWLINE):NEWLINE """NEWLINE Upload bundle from host list and check it is presented in tableNEWLINE """NEWLINE expected_info = BundleInfo(name='test_provider', version='2.15-dev', edition='community', description='')NEWLINE _check_bundle_list_is_empty(page)NEWLINE with allure.step('Create bundle from host creation popup'):NEWLINE host_list_page = HostListPage(app_fs.driver, app_fs.adcm.url).open()NEWLINE host_list_page.upload_bundle_from_host_create_popup(create_bundle_archives[0])NEWLINE _open_bundle_list_and_check_info(page, expected_info)[email protected]()[email protected](NEWLINE "create_bundle_archives",NEWLINE [[CLUSTER_CE_CONFIG]],NEWLINE indirect=True,NEWLINE ids=['cluster_bundle'],NEWLINE)NEWLINEdef test_upload_cluster_bundle_from_another_page(NEWLINE page: BundleListPage, app_fs: ADCMTest, create_bundle_archives: List[str]NEWLINE):NEWLINE """Upload bundle from cluster list and check it is presented in table"""NEWLINE expected_info = BundleInfo(NEWLINE name='test_cluster', version='1.5', edition='community', description='community description'NEWLINE )NEWLINE _check_bundle_list_is_empty(page)NEWLINE with allure.step('Create bundle from cluster creation popup'):NEWLINE cluster_page = ClusterListPage(app_fs.driver, app_fs.adcm.url).open()NEWLINE cluster_page.upload_bundle_from_cluster_create_popup(create_bundle_archives[0])NEWLINE _open_bundle_list_and_check_info(page, expected_info)[email protected](NEWLINE "create_bundle_archives",NEWLINE [[[{'type': 'cluster', 'name': f'ihavetodance-{i}', 'version': f'{i}-ver'}] for i in range(12)]],NEWLINE indirect=True,NEWLINE)[email protected]("upload_bundles")NEWLINEdef test_bundle_list_pagination(page: BundleListPage):NEWLINE """Upload 12 bundles and check pagination"""NEWLINE params = {'on_first_page': 10, 'on_second_page': 2}NEWLINE page.close_info_popup()NEWLINE page.table.check_pagination(params['on_second_page'])NEWLINE |
NEWLINEimport loggingNEWLINEfrom deep_lyric_visualizer.helpers import setup_logger, _extract_name_from_pathNEWLINEfrom deep_lyric_visualizer.generator.generation_environment import (GenerationEnvironment,NEWLINE WikipediaBigGANGenerationEnviornment)NEWLINEfrom deep_lyric_visualizer.generator.generatorio import PickleGeneratorIO, YAMLGeneratorIONEWLINENEWLINEfrom deep_lyric_visualizer.nlp.vectorizer import VectorizerNEWLINEimport numpy as npNEWLINEsetup_logger()NEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINENEWLINEclass ImageCategoryVectorizer(Vectorizer):NEWLINE def __init__(self, gen_env=None):NEWLINE """A vectorizer specific to image categories. Inherits from theNEWLINE Vectorizer class in the nlp section of this package.NEWLINENEWLINE Args:NEWLINE Vectorizer (nlp.Vectorizer): the Vectorizer class, from which thisNEWLINE class inherits.NEWLINE gen_env (generator.GenerationEnvironment, optional): aNEWLINE GenerationEnvironment instance. If None, uses the default .NEWLINE Defaults to None.NEWLINE """NEWLINE super().__init__(gen_env)NEWLINENEWLINE self.name = __name__ if __name__ != '__main__' else _extract_name_from_path(NEWLINE __file__)NEWLINE self.vectorized_dict = NoneNEWLINENEWLINE self.attrs = ['vectorized_dict']NEWLINENEWLINE def _mean_strategy(self, category_tokens):NEWLINE """Defines the so-called 'mean' strategy for vectorizing a list ofNEWLINE list of tokens for a category. Each sub-category or topic is treatedNEWLINE first, averaging the embeddings for the tokens in that category.NEWLINE Then, the results from each sub-category/topic are averaged together.NEWLINENEWLINE Args:NEWLINE category_tokens (list): This is a list of lists, one list of tokensNEWLINE for each topic in the category.NEWLINENEWLINE Returns:NEWLINE np.array: A so-called category vector, an embedding for theNEWLINE category.NEWLINE """NEWLINENEWLINE wordvec_sum = np.zeros(self.env.wordvec_dim)NEWLINE n_phrases = 0NEWLINENEWLINE for tokens in category_tokens:NEWLINE n = len(tokens)NEWLINE if n == 0:NEWLINE continueNEWLINENEWLINE vec = np.zeros(self.env.wordvec_dim)NEWLINE n_vectorizable_phrases = 0NEWLINE for token in tokens:NEWLINE try:NEWLINE vectorized = self.vectorize_word(token)NEWLINE except KeyError:NEWLINE passNEWLINE else:NEWLINE n_vectorizable_phrases += 1NEWLINE vec += vectorizedNEWLINE if n_vectorizable_phrases == 0:NEWLINE continueNEWLINE else:NEWLINE n_phrases += 1NEWLINE vec = vec / n_vectorizable_phrasesNEWLINE wordvec_sum += vecNEWLINE mean_wordvec = (NEWLINE wordvec_sum / n_phrases) if n_phrases != 0 else wordvec_sumNEWLINENEWLINE return mean_wordvecNEWLINENEWLINE def vectorize_category(self, category_tokens, strategy='mean'):NEWLINE """Handles the vectorization of a cateogry by a particular strategy.NEWLINE At the moment, the only considered strategy is the mean strategy.NEWLINENEWLINE Args:NEWLINE category_tokens (list [list [str]]): This is a list of lists,NEWLINE one list of tokens for each topic in the category.NEWLINE strategy (str, optional): One of {"mean"}. The strategy to useNEWLINE Currently only the mean strategy is supported.NEWLINE Defaults to 'mean'.NEWLINENEWLINE Returns:NEWLINE np.array: An array with the vector representing the categoryNEWLINE """NEWLINE if strategy == 'mean':NEWLINE return self._mean_strategy(category_tokens)NEWLINENEWLINE def vectorize_categories(self, categories_tokens, strategy='mean'):NEWLINE """Vectorize a set of categories given their lists of lists of tokens.NEWLINENEWLINE Args:NEWLINE categories_tokens (dict): A dictionary representing the id numberNEWLINE for a category to the list of lists of tokens for that category.NEWLINE strategy (str, optional): One of {"mean"}. The strategy to useNEWLINE Currently only the mean strategy is supported.NEWLINE Defaults to 'mean'.NEWLINENEWLINE Returns:NEWLINE dict: Dictionary with embeddings for each category_id.NEWLINE """NEWLINE self.vectorized_dict = {id_: self.vectorize_category(NEWLINE category) for id_, category in categories_tokens.items()}NEWLINE return self.vectorized_dictNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE im_vec = ImageCategoryVectorizer()NEWLINE im_vec.load()NEWLINE print(im_vec.vectorized_dict)NEWLINE |
from storages.backends.s3boto3 import S3Boto3StorageNEWLINENEWLINEStatRootS3BotoStorage = lambda: S3Boto3Storage(location='static')NEWLINENEWLINEMediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media')NEWLINE |
from django.conf import settingsNEWLINEfrom hashids import HashidsNEWLINENEWLINENEWLINEdef get_hashids():NEWLINE return Hashids(NEWLINE salt=settings.SECRET_KEY, min_length=4, alphabet="abcdefghijklmnopqrstuvwxyz"NEWLINE )NEWLINENEWLINENEWLINEdef decode_hashid(hashid):NEWLINE hashids = get_hashids()NEWLINENEWLINE return hashids.decode(hashid)[0]NEWLINENEWLINENEWLINEdef encode_hashid(value):NEWLINE hashids = get_hashids()NEWLINENEWLINE return hashids.encode(value)NEWLINE |
from dataclasses import dataclassNEWLINEfrom math import asin, cos, radians, sin, sqrtNEWLINENEWLINENEWLINE@dataclassNEWLINEclass Position:NEWLINE name: strNEWLINE lon: float = 0.0NEWLINE lat: float = 0.0NEWLINENEWLINE def distance_to(self, other):NEWLINE r = 6371 # Earth radius in kilometersNEWLINE lam_1, lam_2 = radians(self.lon), radians(self.lat)NEWLINE phi_1, phi_2 = radians(self.lat), radians(other.lat)NEWLINE h = (sin((phi_2 - phi_1) / 2)**2NEWLINE + cos(phi_1) * cos(phi_2) * sin((lam_2 - lam_1) / 2)**2)NEWLINE return 2 * r * asin(sqrt(h))NEWLINENEWLINENEWLINEoslo = Position('Oslo', 10.8, 59.9)NEWLINEvancouver = Position('Vancouver', -123.1, 49.3)NEWLINEoslo.distance_to(vancouver)NEWLINE |
import FWCore.ParameterSet.Config as cmsNEWLINENEWLINEpixelPluginsPhase1=cms.VPSet()NEWLINENEWLINENEWLINE#=====================================================================================NEWLINE#--- Phase 1 Pixel BarrelNEWLINE#NEWLINE# Layer Template Cluster file Resolution histogramsNEWLINE# -----------------------------------------------------------------------------NEWLINE# BPL1 2403 template_events_d63207.out.gz pixel_histos63207_2403.rootNEWLINE#NEWLINE#--- Layer 1NEWLINE#NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select = cms.string("subdetId==BPX && pxbLayer==1"),NEWLINE isBarrel = cms.bool(True),NEWLINE name = cms.string("pixelSmearerBarrelLayer1"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2403 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos63207_2403_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINE#NEWLINE#--- Layer 2NEWLINE# BPL2 2413 template_events_d63507.out.gz pixel_histos63507_2413.rootNEWLINE#NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select = cms.string("subdetId==BPX && pxbLayer==2"),NEWLINE isBarrel = cms.bool(True),NEWLINE name = cms.string("pixelSmearerBarrelLayer2"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2413 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos63507_2413_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINE#NEWLINE#--- Layer 3NEWLINE# BPL3 2423 template_events_d63807.out.gz pixel_histos63807_2423.rootNEWLINE#NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select = cms.string("subdetId==BPX && pxbLayer==3"),NEWLINE isBarrel = cms.bool(True),NEWLINE name = cms.string("pixelSmearerBarrelLayer3"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2413 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos63807_2423_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINENEWLINE#NEWLINE#--- Layer 4NEWLINE# BPL4 2433 template_events_d63807.out.gz pixel_histos64107_2433.rootNEWLINE#NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select = cms.string("subdetId==BPX && pxbLayer==4"),NEWLINE isBarrel = cms.bool(True),NEWLINE name = cms.string("pixelSmearerBarrelLayer4"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2413 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64107_2433_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/BarrelEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/bysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINENEWLINENEWLINENEWLINE#=====================================================================================NEWLINE#--- Phase 1 Pixel ForwardNEWLINE#NEWLINE# Panel Template Cluster file Resolution histogramsNEWLINE# -----------------------------------------------------------------------------NEWLINE# FPR2P1 2443 template_events_d64237.out.gz pixel_histos64237_2443.rootNEWLINE#NEWLINE#--- Ring 2, Panel 1NEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select=cms.string("subdetId==FPX && pxfBlade>22 && pxfPanel==1"), ## 1-56 (Ring 1 is 1-22, Ring 2 is 23-56)NEWLINE isBarrel = cms.bool(False),NEWLINE name = cms.string("pixelSmearerForwardRing2Panel1"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2443 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64237_2443_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINENEWLINENEWLINE#--- Ring 1, Panel 1NEWLINE# FPR1P1 2453 template_events_d64367.out.gz pixel_histos64367_2453.rootNEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select=cms.string("subdetId==FPX && pxfBlade<23 && pxfPanel==1"), ## 1-56 (Ring 1 is 1-22, Ring 2 is 23-56)NEWLINE isBarrel = cms.bool(False),NEWLINE name = cms.string("pixelSmearerForwardRing1Panel1"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2453 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64367_2453_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINENEWLINE#--- Ring 1, Panel 2NEWLINE# FPR1P2 2463 template_events_d64497.out.gz pixel_histos64497_2463.rootNEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select=cms.string("subdetId==FPX && pxfBlade<23 && pxfPanel==2"), ## 1-56 (Ring 1 is 1-22, Ring 2 is 23-56)NEWLINE isBarrel = cms.bool(False),NEWLINE name = cms.string("pixelSmearerForwardRing1Panel2"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2463 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64497_2463_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINE#--- Ring 2, Panel 2NEWLINE# FPR2P2 2473 template_events_d64627.out.gz pixel_histos64627_2473.rootNEWLINEpixelPluginsPhase1.append(NEWLINE cms.PSet(NEWLINE select=cms.string("subdetId==FPX && pxfBlade>22 && pxfPanel==2"), ## 1-56 (Ring 1 is 1-22, Ring 2 is 23-56)NEWLINE isBarrel = cms.bool(False),NEWLINE name = cms.string("pixelSmearerForwardRing2Panel2"),NEWLINE type = cms.string("PixelTemplateSmearerPlugin"),NEWLINE # templateId = cms.int32( 2473 ),NEWLINE RegularPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/pixel_histos64627_2473_6.root'),NEWLINE BigPixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardBig2017.root'),NEWLINE EdgePixelResolutionFile = cms.string('FastSimulation/TrackingRecHitProducer/data/ForwardEdge2017.root'),NEWLINE #NEWLINE MergeHitsOn = cms.bool(False),NEWLINE MergingProbabilityFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fmergeprob.root'),NEWLINE MergedPixelResolutionXFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fxsmear.root'),NEWLINE MergedPixelResolutionYFile = cms.string('FastSimulation/TrackingRecHitProducer/data/fysmear.root'),NEWLINE )NEWLINE)NEWLINENEWLINE |
# coding=utf-8NEWLINE# *** WARNING: this file was generated by crd2pulumi. ***NEWLINE# *** Do not edit by hand unless you're certain you know what you are doing! ***NEWLINENEWLINESNAKE_TO_CAMEL_CASE_TABLE = {NEWLINE "active_directory": "activeDirectory",NEWLINE "api_version": "apiVersion",NEWLINE "augmented_active_directory": "augmentedActiveDirectory",NEWLINE "base_dn": "baseDN",NEWLINE "ca_secret": "caSecret",NEWLINE "credentials_secret": "credentialsSecret",NEWLINE "deref_aliases": "derefAliases",NEWLINE "group_membership_attributes": "groupMembershipAttributes",NEWLINE "group_name_attributes": "groupNameAttributes",NEWLINE "group_uid_attribute": "groupUIDAttribute",NEWLINE "group_uid_name_mapping": "groupUIDNameMapping",NEWLINE "groups_query": "groupsQuery",NEWLINE "last_sync_success_time": "lastSyncSuccessTime",NEWLINE "last_transition_time": "lastTransitionTime",NEWLINE "login_realm": "loginRealm",NEWLINE "page_size": "pageSize",NEWLINE "tolerate_member_not_found_errors": "tolerateMemberNotFoundErrors",NEWLINE "tolerate_member_out_of_scope_errors": "tolerateMemberOutOfScopeErrors",NEWLINE "user_name_attributes": "userNameAttributes",NEWLINE "user_uid_attribute": "userUIDAttribute",NEWLINE "users_query": "usersQuery",NEWLINE}NEWLINENEWLINECAMEL_TO_SNAKE_CASE_TABLE = {NEWLINE "activeDirectory": "active_directory",NEWLINE "apiVersion": "api_version",NEWLINE "augmentedActiveDirectory": "augmented_active_directory",NEWLINE "baseDN": "base_dn",NEWLINE "caSecret": "ca_secret",NEWLINE "credentialsSecret": "credentials_secret",NEWLINE "derefAliases": "deref_aliases",NEWLINE "groupMembershipAttributes": "group_membership_attributes",NEWLINE "groupNameAttributes": "group_name_attributes",NEWLINE "groupUIDAttribute": "group_uid_attribute",NEWLINE "groupUIDNameMapping": "group_uid_name_mapping",NEWLINE "groupsQuery": "groups_query",NEWLINE "lastSyncSuccessTime": "last_sync_success_time",NEWLINE "lastTransitionTime": "last_transition_time",NEWLINE "loginRealm": "login_realm",NEWLINE "pageSize": "page_size",NEWLINE "tolerateMemberNotFoundErrors": "tolerate_member_not_found_errors",NEWLINE "tolerateMemberOutOfScopeErrors": "tolerate_member_out_of_scope_errors",NEWLINE "userNameAttributes": "user_name_attributes",NEWLINE "userUIDAttribute": "user_uid_attribute",NEWLINE "usersQuery": "users_query",NEWLINE}NEWLINE |
import mathNEWLINENEWLINEr= float(input("Radius:"))NEWLINEri=int(r)NEWLINEwhile r>ri:NEWLINE ri=ri+1NEWLINEx= float(input("x-coordinate:"))NEWLINEwhile x>r or x<-r:NEWLINE print ("x-coordinate cannot be larger than radius")NEWLINE x= float(input("x-coordinate:"))NEWLINEy= float(input("y-coordinate:"))NEWLINEwhile y>r or y<-r:NEWLINE print ("y-coordinate cannot be larger than radius")NEWLINE y= float(input("y-coordinate:"))NEWLINEz= float(input("z-coordinate:"))NEWLINEwhile z>r or z<-r:NEWLINE print ("z-coordinate cannot be larger than radius")NEWLINE z= float(input("z-coordinate:"))NEWLINErij=math.sqrt(((x)**2)+((y)**2)+((z)**2))NEWLINEwhile rij>((math.sqrt(3))*r):NEWLINE print ("point is outside the cube")NEWLINE x=float(input("x-coordinate:"))NEWLINE while x>r or x<-r:NEWLINE print ("x-coordinate cannot be larger than radius")NEWLINE x=float(input("x-coordinate:"))NEWLINE y=float(input("y-coordinate:"))NEWLINE while y>r or y<-r:NEWLINE print ("y-coordinate cannot be larger than radius")NEWLINE y=float(input("y-coordinate:"))NEWLINE z=float(input("z-coordinate:"))NEWLINE while z>r or z<-r:NEWLINE print ("z-coordinate cannot be larger than radius")NEWLINE z=float(input("z-coordinate:"))NEWLINE rij=math.sqrt(((x)**2)+((y)**2)+((z)**2))NEWLINEprint ('Point:(',x,',',y,',',z,')')NEWLINENEWLINEwhile x<0:NEWLINE x=x*(-1)NEWLINEwhile y<0:NEWLINE y=y*(-1)NEWLINEwhile z<0:NEWLINE z=z*(-1)NEWLINENEWLINExone=ri-xNEWLINEyone=ri-yNEWLINEzone=ri-zNEWLINExtwo=(-1)*(x+ri)NEWLINEytwo=(-1)*(y+ri)NEWLINEztwo=(-1)*(z+ri)NEWLINEtotalx=0NEWLINEtotaly=0NEWLINEtotalz=0NEWLINENEWLINEwhile xone>=xtwo:NEWLINE while yone>=ytwo:NEWLINE while zone>=ztwo:NEWLINE if xone==0 and yone==0 and zone==0:NEWLINE zone=zone-1NEWLINE else:NEWLINE rij=math.sqrt(((xone)**2)+((yone)**2)+((zone)**2))NEWLINE rijc=math.sqrt(((x+xone)**2)+((y+yone)**2)+((z+zone)**2))NEWLINE if rijc>((math.sqrt(3))*r):NEWLINE zone=zone-1NEWLINE else:NEWLINE Hx=((3*xone*zone)/((rij)**5))NEWLINE Hy=((3*yone*zone)/((rij)**5))NEWLINE Hz=(((2*((zone)**2))-((xone)**2)-((yone)**2))/((rij)**5))NEWLINE totalx=totalx+HxNEWLINE totaly=totaly+HyNEWLINE totalz=totalz+HzNEWLINE zone=zone-1NEWLINE yone=yone-1NEWLINE zone=ri+zNEWLINE xone=xone-1NEWLINE yone=ri+yNEWLINENEWLINEH=math.sqrt(((totalx)**2)+((totaly)**2)+((totalz)**2))NEWLINEif H<(10**(-10)):NEWLINE print ("total H: 0.0")NEWLINEelse:NEWLINE print ("total H:",H)NEWLINENEWLINE NEWLINENEWLINENEWLINE |
from .jkgat import JKGATNEWLINENEWLINE__all__ = ['JKGAT']NEWLINE |
# -*- coding: utf-8 -*-NEWLINE# Copyright 2020 Google LLCNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINEfrom collections import OrderedDictNEWLINEfrom typing import Dict, TypeNEWLINENEWLINEfrom .base import ProfileServiceTransportNEWLINEfrom .grpc import ProfileServiceGrpcTransportNEWLINEfrom .grpc_asyncio import ProfileServiceGrpcAsyncIOTransportNEWLINENEWLINENEWLINE# Compile a registry of transports.NEWLINE_transport_registry = OrderedDict() # type: Dict[str, Type[ProfileServiceTransport]]NEWLINE_transport_registry['grpc'] = ProfileServiceGrpcTransportNEWLINE_transport_registry['grpc_asyncio'] = ProfileServiceGrpcAsyncIOTransportNEWLINENEWLINE__all__ = (NEWLINE 'ProfileServiceTransport',NEWLINE 'ProfileServiceGrpcTransport',NEWLINE 'ProfileServiceGrpcAsyncIOTransport',NEWLINE)NEWLINE |
# -*- coding: utf-8 -*-NEWLINE#NEWLINE# dengueAI documentation build configuration file, created byNEWLINE# sphinx-quickstart.NEWLINE#NEWLINE# This file is execfile()d with the current directory set to its containing dir.NEWLINE#NEWLINE# Note that not all possible configuration values are present in thisNEWLINE# autogenerated file.NEWLINE#NEWLINE# All configuration values have a default; values that are commented outNEWLINE# serve to show the default.NEWLINENEWLINEimport osNEWLINEimport sysNEWLINENEWLINE# If extensions (or modules to document with autodoc) are in another directory,NEWLINE# add these directories to sys.path here. If the directory is relative to theNEWLINE# documentation root, use os.path.abspath to make it absolute, like shown here.NEWLINE# sys.path.insert(0, os.path.abspath('.'))NEWLINENEWLINE# -- General configuration -----------------------------------------------------NEWLINENEWLINE# If your documentation needs a minimal Sphinx version, state it here.NEWLINE# needs_sphinx = '1.0'NEWLINENEWLINE# Add any Sphinx extension module names here, as strings. They can be extensionsNEWLINE# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.NEWLINEextensions = []NEWLINENEWLINE# Add any paths that contain templates here, relative to this directory.NEWLINEtemplates_path = ['_templates']NEWLINENEWLINE# The suffix of source filenames.NEWLINEsource_suffix = '.rst'NEWLINENEWLINE# The encoding of source files.NEWLINE# source_encoding = 'utf-8-sig'NEWLINENEWLINE# The master toctree document.NEWLINEmaster_doc = 'index'NEWLINENEWLINE# General information about the project.NEWLINEproject = u'dengueAI'NEWLINENEWLINE# The version info for the project you're documenting, acts as replacement forNEWLINE# |version| and |release|, also used in various other places throughout theNEWLINE# built documents.NEWLINE#NEWLINE# The short X.Y version.NEWLINEversion = '0.1'NEWLINE# The full version, including alpha/beta/rc tags.NEWLINErelease = '0.1'NEWLINENEWLINE# The language for content autogenerated by Sphinx. Refer to documentationNEWLINE# for a list of supported languages.NEWLINE# language = NoneNEWLINENEWLINE# There are two options for replacing |today|: either, you set today to someNEWLINE# non-false value, then it is used:NEWLINE# today = ''NEWLINE# Else, today_fmt is used as the format for a strftime call.NEWLINE# today_fmt = '%B %d, %Y'NEWLINENEWLINE# List of patterns, relative to source directory, that match files andNEWLINE# directories to ignore when looking for source files.NEWLINEexclude_patterns = ['_build']NEWLINENEWLINE# The reST default role (used for this markup: `text`) to use for all documents.NEWLINE# default_role = NoneNEWLINENEWLINE# If true, '()' will be appended to :func: etc. cross-reference text.NEWLINE# add_function_parentheses = TrueNEWLINENEWLINE# If true, the current module name will be prepended to all descriptionNEWLINE# unit titles (such as .. function::).NEWLINE# add_module_names = TrueNEWLINENEWLINE# If true, sectionauthor and moduleauthor directives will be shown in theNEWLINE# output. They are ignored by default.NEWLINE# show_authors = FalseNEWLINENEWLINE# The name of the Pygments (syntax highlighting) style to use.NEWLINEpygments_style = 'sphinx'NEWLINENEWLINE# A list of ignored prefixes for module index sorting.NEWLINE# modindex_common_prefix = []NEWLINENEWLINENEWLINE# -- Options for HTML output ---------------------------------------------------NEWLINENEWLINE# The theme to use for HTML and HTML Help pages. See the documentation forNEWLINE# a list of builtin themes.NEWLINEhtml_theme = 'default'NEWLINENEWLINE# Theme options are theme-specific and customize the look and feel of a themeNEWLINE# further. For a list of options available for each theme, see theNEWLINE# documentation.NEWLINE# html_theme_options = {}NEWLINENEWLINE# Add any paths that contain custom themes here, relative to this directory.NEWLINE# html_theme_path = []NEWLINENEWLINE# The name for this set of Sphinx documents. If None, it defaults toNEWLINE# "<project> v<release> documentation".NEWLINE# html_title = NoneNEWLINENEWLINE# A shorter title for the navigation bar. Default is the same as html_title.NEWLINE# html_short_title = NoneNEWLINENEWLINE# The name of an image file (relative to this directory) to place at the topNEWLINE# of the sidebar.NEWLINE# html_logo = NoneNEWLINENEWLINE# The name of an image file (within the static path) to use as favicon of theNEWLINE# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32NEWLINE# pixels large.NEWLINE# html_favicon = NoneNEWLINENEWLINE# Add any paths that contain custom static files (such as style sheets) here,NEWLINE# relative to this directory. They are copied after the builtin static files,NEWLINE# so a file named "default.css" will overwrite the builtin "default.css".NEWLINEhtml_static_path = ['_static']NEWLINENEWLINE# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,NEWLINE# using the given strftime format.NEWLINE# html_last_updated_fmt = '%b %d, %Y'NEWLINENEWLINE# If true, SmartyPants will be used to convert quotes and dashes toNEWLINE# typographically correct entities.NEWLINE# html_use_smartypants = TrueNEWLINENEWLINE# Custom sidebar templates, maps document names to template names.NEWLINE# html_sidebars = {}NEWLINENEWLINE# Additional templates that should be rendered to pages, maps page names toNEWLINE# template names.NEWLINE# html_additional_pages = {}NEWLINENEWLINE# If false, no module index is generated.NEWLINE# html_domain_indices = TrueNEWLINENEWLINE# If false, no index is generated.NEWLINE# html_use_index = TrueNEWLINENEWLINE# If true, the index is split into individual pages for each letter.NEWLINE# html_split_index = FalseNEWLINENEWLINE# If true, links to the reST sources are added to the pages.NEWLINE# html_show_sourcelink = TrueNEWLINENEWLINE# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.NEWLINE# html_show_sphinx = TrueNEWLINENEWLINE# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.NEWLINE# html_show_copyright = TrueNEWLINENEWLINE# If true, an OpenSearch description file will be output, and all pages willNEWLINE# contain a <link> tag referring to it. The value of this option must be theNEWLINE# base URL from which the finished HTML is served.NEWLINE# html_use_opensearch = ''NEWLINENEWLINE# This is the file name suffix for HTML files (e.g. ".xhtml").NEWLINE# html_file_suffix = NoneNEWLINENEWLINE# Output file base name for HTML help builder.NEWLINEhtmlhelp_basename = 'dengueaidoc'NEWLINENEWLINENEWLINE# -- Options for LaTeX output --------------------------------------------------NEWLINENEWLINElatex_elements = {NEWLINE # The paper size ('letterpaper' or 'a4paper').NEWLINE # 'papersize': 'letterpaper',NEWLINENEWLINE # The font size ('10pt', '11pt' or '12pt').NEWLINE # 'pointsize': '10pt',NEWLINENEWLINE # Additional stuff for the LaTeX preamble.NEWLINE # 'preamble': '',NEWLINE}NEWLINENEWLINE# Grouping the document tree into LaTeX files. List of tuplesNEWLINE# (source start file, target name, title, author, documentclass [howto/manual]).NEWLINElatex_documents = [NEWLINE ('index',NEWLINE 'dengueai.tex',NEWLINE u'dengueAI Documentation',NEWLINE u"John Keating", 'manual'),NEWLINE]NEWLINENEWLINE# The name of an image file (relative to this directory) to place at the top ofNEWLINE# the title page.NEWLINE# latex_logo = NoneNEWLINENEWLINE# For "manual" documents, if this is true, then toplevel headings are parts,NEWLINE# not chapters.NEWLINE# latex_use_parts = FalseNEWLINENEWLINE# If true, show page references after internal links.NEWLINE# latex_show_pagerefs = FalseNEWLINENEWLINE# If true, show URL addresses after external links.NEWLINE# latex_show_urls = FalseNEWLINENEWLINE# Documents to append as an appendix to all manuals.NEWLINE# latex_appendices = []NEWLINENEWLINE# If false, no module index is generated.NEWLINE# latex_domain_indices = TrueNEWLINENEWLINENEWLINE# -- Options for manual page output --------------------------------------------NEWLINENEWLINE# One entry per manual page. List of tuplesNEWLINE# (source start file, name, description, authors, manual section).NEWLINEman_pages = [NEWLINE ('index', 'dengueai', u'dengueAI Documentation',NEWLINE [u"John Keating"], 1)NEWLINE]NEWLINENEWLINE# If true, show URL addresses after external links.NEWLINE# man_show_urls = FalseNEWLINENEWLINENEWLINE# -- Options for Texinfo output ------------------------------------------------NEWLINENEWLINE# Grouping the document tree into Texinfo files. List of tuplesNEWLINE# (source start file, target name, title, author,NEWLINE# dir menu entry, description, category)NEWLINEtexinfo_documents = [NEWLINE ('index', 'dengueai', u'dengueAI Documentation',NEWLINE u"John Keating", 'dengueAI',NEWLINE 'DengueAI is a DrivenData competition designed to find a means of predicting the spread of Dengue Fever/', 'Miscellaneous'),NEWLINE]NEWLINENEWLINE# Documents to append as an appendix to all manuals.NEWLINE# texinfo_appendices = []NEWLINENEWLINE# If false, no module index is generated.NEWLINE# texinfo_domain_indices = TrueNEWLINENEWLINE# How to display URL addresses: 'footnote', 'no', or 'inline'.NEWLINE# texinfo_show_urls = 'footnote'NEWLINE |
# Licensed to the Apache Software Foundation (ASF) under one or moreNEWLINE# contributor license agreements. See the NOTICE file distributed withNEWLINE# this work for additional information regarding copyright ownership.NEWLINE# The ASF licenses this file to You under the Apache License, Version 2.0NEWLINE# (the "License"); you may not use this file except in compliance withNEWLINE# the License. You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEimport reNEWLINEimport sysNEWLINEfrom setuptools import find_packages, setupNEWLINEfrom setuptools.command.test import test as TestCommandNEWLINENEWLINEversion = ''NEWLINEwith open('kafkatest/__init__.py', 'r') as fd:NEWLINE version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1)NEWLINENEWLINENEWLINEclass PyTest(TestCommand):NEWLINE user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]NEWLINENEWLINE def initialize_options(self):NEWLINE TestCommand.initialize_options(self)NEWLINE self.pytest_args = []NEWLINENEWLINE def finalize_options(self):NEWLINE TestCommand.finalize_options(self)NEWLINE self.test_args = []NEWLINE self.test_suite = TrueNEWLINENEWLINE def run_tests(self):NEWLINE # import here, cause outside the eggs aren't loadedNEWLINE import pytestNEWLINE print(self.pytest_args)NEWLINE errno = pytest.main(self.pytest_args)NEWLINE sys.exit(errno)NEWLINENEWLINE# Note: when changing the version of ducktape, also revise tests/docker/DockerfileNEWLINEsetup(name="kafkatest",NEWLINE version=version,NEWLINE description="Apache Kafka System Tests",NEWLINE author="Apache Kafka",NEWLINE platforms=["any"],NEWLINE license="apache2.0",NEWLINE packages=find_packages(),NEWLINE include_package_data=True,NEWLINE install_requires=["ducktape>0.8", "requests==2.24.0"],NEWLINE tests_require=["pytest", "mock"],NEWLINE cmdclass={'test': PyTest},NEWLINE zip_safe=FalseNEWLINE )NEWLINE |
# Time: O(n)NEWLINE# Space: O(k)NEWLINENEWLINEclass Solution:NEWLINE def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:NEWLINE """NEWLINE modified sliding window, using a mapNEWLINE """NEWLINENEWLINE if not s or not k:NEWLINE return 0NEWLINENEWLINE left = 0NEWLINE index = 0NEWLINE imap = collections.defaultdict(int)NEWLINE max_dist = float('-inf')NEWLINENEWLINE while index<len(s):NEWLINENEWLINE imap[s[index]]+=1NEWLINENEWLINE while len(imap)>k and left<len(s):NEWLINE imap[s[left]]-=1NEWLINENEWLINE if imap[s[left]]<=0:NEWLINE del imap[s[left]]NEWLINE left+=1NEWLINENEWLINE max_dist = max(max_dist, index-left+1)NEWLINE index+=1NEWLINENEWLINE return max_distNEWLINE |
import unittestNEWLINEimport osNEWLINEfrom ...BaseTestCase import BaseTestCaseNEWLINEfrom kombi.Task import TaskNEWLINEfrom kombi.Crawler.Fs import FsCrawlerNEWLINENEWLINEclass ResizeImageTaskTest(BaseTestCase):NEWLINE """Test ResizeImage task."""NEWLINENEWLINE __sourcePath = os.path.join(BaseTestCase.dataTestsDirectory(), "testSeq.0001.exr")NEWLINE __targetPath = os.path.join(BaseTestCase.tempDirectory(), "testToDelete.jpg")NEWLINENEWLINE def testResizeImage(self):NEWLINE """NEWLINE Test that the ResizeImage task works properly.NEWLINE """NEWLINE crawler = FsCrawler.createFromPath(self.__sourcePath)NEWLINE resizeTask = Task.create('resizeImage')NEWLINE resizeTask.add(crawler, self.__targetPath)NEWLINE resizeTask.setOption("width", "480")NEWLINE resizeTask.setOption("height", "270")NEWLINE for convertToRGBA in [False, True]:NEWLINE resizeTask.setOption("convertToRGBA", convertToRGBA)NEWLINE result = resizeTask.output()NEWLINE self.assertEqual(len(result), 1)NEWLINE crawler = result[0]NEWLINE self.assertEqual(crawler.var("width"), 480)NEWLINE self.assertEqual(crawler.var("height"), 270)NEWLINENEWLINE @classmethodNEWLINE def tearDownClass(cls):NEWLINE """NEWLINE Remove the file that was copied.NEWLINE """NEWLINE os.remove(cls.__targetPath)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE unittest.main()NEWLINE |
# Generated from SMTLIBv2.g4 by ANTLR 4.9.2NEWLINEfrom antlr4 import *NEWLINEfrom io import StringIONEWLINEimport sysNEWLINEif sys.version_info[1] > 5:NEWLINE from typing import TextIONEWLINEelse:NEWLINE from typing.io import TextIONEWLINENEWLINENEWLINENEWLINEdef serializedATN():NEWLINE with StringIO() as buf:NEWLINE buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\u008d")NEWLINE buf.write("\u072b\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")NEWLINE buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")NEWLINE buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23")NEWLINE buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30")NEWLINE buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36")NEWLINE buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%")NEWLINE buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.")NEWLINE buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64")NEWLINE buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:")NEWLINE buf.write("\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA\4B\tB\4C\t")NEWLINE buf.write("C\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\tJ\4K\tK\4L\t")NEWLINE buf.write("L\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S\tS\4T\tT\4U\t")NEWLINE buf.write("U\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\4\\\t\\\4]\t]\4")NEWLINE buf.write("^\t^\4_\t_\4`\t`\4a\ta\4b\tb\4c\tc\4d\td\4e\te\4f\tf\4")NEWLINE buf.write("g\tg\4h\th\4i\ti\4j\tj\4k\tk\4l\tl\4m\tm\4n\tn\4o\to\4")NEWLINE buf.write("p\tp\4q\tq\4r\tr\4s\ts\4t\tt\4u\tu\4v\tv\4w\tw\4x\tx\4")NEWLINE buf.write("y\ty\4z\tz\4{\t{\4|\t|\4}\t}\4~\t~\4\177\t\177\4\u0080")NEWLINE buf.write("\t\u0080\4\u0081\t\u0081\4\u0082\t\u0082\4\u0083\t\u0083")NEWLINE buf.write("\4\u0084\t\u0084\4\u0085\t\u0085\4\u0086\t\u0086\4\u0087")NEWLINE buf.write("\t\u0087\4\u0088\t\u0088\4\u0089\t\u0089\4\u008a\t\u008a")NEWLINE buf.write("\4\u008b\t\u008b\4\u008c\t\u008c\4\u008d\t\u008d\4\u008e")NEWLINE buf.write("\t\u008e\4\u008f\t\u008f\4\u0090\t\u0090\4\u0091\t\u0091")NEWLINE buf.write("\4\u0092\t\u0092\4\u0093\t\u0093\4\u0094\t\u0094\4\u0095")NEWLINE buf.write("\t\u0095\3\2\3\2\3\2\3\2\3\3\3\3\7\3\u0132\n\3\f\3\16")NEWLINE buf.write("\3\u0135\13\3\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7")NEWLINE buf.write("\3\7\7\7\u0142\n\7\f\7\16\7\u0145\13\7\3\7\3\7\3\b\3\b")NEWLINE buf.write("\3\b\7\b\u014c\n\b\f\b\16\b\u014f\13\b\3\b\3\b\3\t\3\t")NEWLINE buf.write("\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3")NEWLINE buf.write("\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\5\t\u016a\n\t\3\n\3\n\3")NEWLINE buf.write("\n\3\n\3\13\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\r\3")NEWLINE buf.write("\r\3\r\3\r\3\r\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16")NEWLINE buf.write("\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16")NEWLINE buf.write("\3\16\3\17\3\17\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20")NEWLINE buf.write("\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21")NEWLINE buf.write("\3\21\3\21\3\21\3\21\3\21\3\21\3\22\3\22\3\22\3\22\3\22")NEWLINE buf.write("\3\22\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23")NEWLINE buf.write("\3\23\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\25\3\25\3\25")NEWLINE buf.write("\3\25\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3\27\3\27")NEWLINE buf.write("\3\27\3\27\3\27\3\27\3\27\3\30\3\30\3\30\3\30\3\30\3\31")NEWLINE buf.write("\3\31\3\31\3\31\3\31\3\31\3\31\3\31\3\32\3\32\3\32\3\32")NEWLINE buf.write("\3\32\3\32\3\32\3\32\3\32\3\32\3\32\3\32\3\33\3\33\3\33")NEWLINE buf.write("\3\33\3\33\3\33\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\35")NEWLINE buf.write("\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35")NEWLINE buf.write("\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\37\3\37")NEWLINE buf.write("\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3 \3 \3 \3 \3")NEWLINE buf.write(" \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3 \3!\3!\3!\3")NEWLINE buf.write("!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3\"\3\"\3\"\3\"")NEWLINE buf.write("\3\"\3\"\3\"\3#\3#\3#\3#\3#\3#\3#\3#\3#\3$\3$\3$\3$\3")NEWLINE buf.write("$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3%\3")NEWLINE buf.write("%\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3&\3")NEWLINE buf.write("\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'\3\'")NEWLINE buf.write("\3\'\3\'\3\'\3\'\3\'\3(\3(\3(\3(\3(\3(\3(\3(\3(\3(\3(")NEWLINE buf.write("\3(\3(\3(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3)\3)\3)\3)\3)\3")NEWLINE buf.write(")\3)\3)\3)\3)\3)\3)\3)\3)\3)\3*\3*\3*\3*\3*\3*\3*\3*\3")NEWLINE buf.write("*\3*\3*\3*\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3+\3,\3")NEWLINE buf.write(",\3,\3,\3,\3,\3,\3-\3-\3-\3-\3-\3-\3-\3-\3-\3-\3-\3.\3")NEWLINE buf.write(".\3.\3.\3.\3.\3.\3.\3.\3.\3.\3.\3.\3/\3/\3/\3/\3/\3/\3")NEWLINE buf.write("/\3/\3/\3/\3/\3/\3/\3/\3/\3\60\3\60\3\60\3\60\3\60\3\60")NEWLINE buf.write("\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\61")NEWLINE buf.write("\3\61\3\61\3\61\3\61\3\61\3\61\3\61\3\61\3\61\3\61\3\61")NEWLINE buf.write("\3\62\3\62\3\62\3\62\3\62\3\62\3\62\3\62\3\63\3\63\3\63")NEWLINE buf.write("\3\63\3\63\3\64\3\64\3\64\3\64\3\64\3\65\3\65\3\65\3\65")NEWLINE buf.write("\3\65\3\66\3\66\3\66\3\66\3\66\3\66\3\66\3\66\3\66\3\66")NEWLINE buf.write("\3\66\3\66\3\66\3\66\3\66\3\67\3\67\3\67\3\67\3\67\3\67")NEWLINE buf.write("\3\67\3\67\3\67\3\67\3\67\3\67\3\67\3\67\3\67\38\38\3")NEWLINE buf.write("8\38\38\38\38\38\38\38\38\38\38\38\38\39\39\39\39\39\3")NEWLINE buf.write("9\39\39\39\3:\3:\3:\3:\3:\3:\3:\3:\3:\3:\3;\3;\3;\3;\3")NEWLINE buf.write(";\3;\3;\3;\3;\3;\3;\3;\3<\3<\3<\3<\3<\3<\3<\3<\3<\3<\3")NEWLINE buf.write("<\3=\3=\3=\3=\3=\3=\3=\3=\3=\3=\3=\3=\3>\3>\3>\3>\3>\3")NEWLINE buf.write(">\3>\3>\3>\3>\3?\3?\3?\3?\3?\3?\3?\3?\3?\3?\3?\3?\3?\3")NEWLINE buf.write("?\3?\3?\3?\3?\3?\3?\3?\3?\3@\3@\3@\3@\3@\3@\3@\3@\3@\3")NEWLINE buf.write("@\3@\3@\3@\3@\3@\3A\3A\3A\3A\3A\3A\3A\3A\3A\3A\3B\3B\3")NEWLINE buf.write("B\3B\3C\3C\3C\3C\3C\3D\3D\3D\3D\3D\3D\3E\3E\3E\3E\3E\3")NEWLINE buf.write("E\3E\3E\3E\3E\3E\3E\3E\3E\3E\3E\3E\3F\3F\3F\3F\3F\3F\3")NEWLINE buf.write("F\3F\3F\3G\3G\3G\3G\3G\3G\3G\3G\3G\3G\3H\3H\3H\3H\3H\3")NEWLINE buf.write("H\3H\3H\3H\3H\3H\3I\3I\3I\3I\3I\3J\3J\3J\3J\3J\3J\3J\3")NEWLINE buf.write("J\3J\3K\3K\3K\3K\3K\3K\3K\3K\3K\3L\3L\3L\3L\3L\3L\3L\3")NEWLINE buf.write("L\3M\3M\3M\3M\3M\3M\3M\3M\3M\3M\3M\3M\3N\3N\3N\3N\3N\3")NEWLINE buf.write("N\3N\3O\3O\3O\3O\3O\3O\3O\3O\3P\3P\3P\3P\3P\3P\3P\3P\3")NEWLINE buf.write("P\3P\3P\3P\3P\3Q\3Q\3R\3R\3S\3S\3S\3T\3T\3T\3T\3T\3T\3")NEWLINE buf.write("T\3U\3U\3U\3U\3U\3U\3U\3U\3V\3V\3V\3V\3V\3V\3V\3W\3W\3")NEWLINE buf.write("W\3W\3W\3W\3W\3W\3W\3W\3W\3W\3X\3X\3X\3X\3X\3X\3X\3Y\3")NEWLINE buf.write("Y\3Y\3Y\3Z\3Z\3Z\3Z\3Z\3Z\3[\3[\3[\3[\3[\3[\3[\3[\3\\")NEWLINE buf.write("\3\\\3\\\3\\\3]\3]\3]\7]\u0495\n]\f]\16]\u0498\13]\5]")NEWLINE buf.write("\u049a\n]\3^\3^\3^\3^\6^\u04a0\n^\r^\16^\u04a1\3_\3_\3")NEWLINE buf.write("_\3_\6_\u04a8\n_\r_\16_\u04a9\3`\3`\3`\7`\u04af\n`\f`")NEWLINE buf.write("\16`\u04b2\13`\3`\3`\3a\3a\3b\3b\3c\3c\3d\3d\3e\3e\3f")NEWLINE buf.write("\3f\5f\u04c2\nf\3g\3g\5g\u04c6\ng\3h\3h\5h\u04ca\nh\3")NEWLINE buf.write("i\3i\3i\3j\3j\3k\3k\3k\3k\3k\3k\3k\3k\3k\3k\3k\3k\3k\3")NEWLINE buf.write("k\3k\3k\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3l\3")NEWLINE buf.write("l\3l\3l\3l\3l\3l\3l\3l\3l\3m\3m\3m\3m\3m\3m\3m\3m\3m\3")NEWLINE buf.write("n\3n\3n\3n\3n\3n\3n\3n\3n\3n\3o\3o\3o\3o\3o\3o\3o\3o\3")NEWLINE buf.write("o\3o\3o\3p\3p\3p\3p\3p\3p\3p\3p\3p\3p\3p\3p\3q\3q\3q\3")NEWLINE buf.write("q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3q\3")NEWLINE buf.write("q\3q\3q\3q\3q\3q\3r\3r\3r\3r\3r\3r\3r\3r\3r\3r\3r\3r\3")NEWLINE buf.write("r\3r\3r\3r\3s\3s\3s\3s\3s\3s\3s\3s\3s\3s\3s\3s\3t\3t\3")NEWLINE buf.write("t\3t\3t\3t\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3u\3")NEWLINE buf.write("u\3u\3u\3u\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3v\3")NEWLINE buf.write("v\3v\3v\3v\3v\3v\3v\3w\3w\3w\3w\3w\3w\3w\3w\3w\3w\3w\3")NEWLINE buf.write("w\3w\3w\3w\3w\3w\3w\3x\3x\3x\3x\3x\3x\3x\3x\3x\3x\3y\3")NEWLINE buf.write("y\3y\3y\3y\3y\3y\3y\3y\3y\3y\3y\3z\3z\3z\3z\3z\3z\3z\3")NEWLINE buf.write("z\3z\3{\3{\3{\3{\3{\3{\3{\3|\3|\3|\3|\3|\3|\3}\3}\3}\3")NEWLINE buf.write("}\3}\3}\3}\3~\3~\3~\3~\3~\3~\3~\3~\3~\3\177\3\177\3\177")NEWLINE buf.write("\3\177\3\177\3\177\3\177\3\177\3\177\3\177\3\177\3\177")NEWLINE buf.write("\3\177\3\177\3\177\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080")NEWLINE buf.write("\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080")NEWLINE buf.write("\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080\3\u0080")NEWLINE buf.write("\3\u0080\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081")NEWLINE buf.write("\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081")NEWLINE buf.write("\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081\3\u0081")NEWLINE buf.write("\3\u0081\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082")NEWLINE buf.write("\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082\3\u0082")NEWLINE buf.write("\3\u0082\3\u0082\3\u0082\3\u0083\3\u0083\3\u0083\3\u0083")NEWLINE buf.write("\3\u0083\3\u0083\3\u0083\3\u0083\3\u0083\3\u0083\3\u0083")NEWLINE buf.write("\3\u0083\3\u0083\3\u0083\3\u0083\3\u0083\3\u0084\3\u0084")NEWLINE buf.write("\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084")NEWLINE buf.write("\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084")NEWLINE buf.write("\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084\3\u0084")NEWLINE buf.write("\3\u0084\3\u0084\3\u0084\3\u0084\3\u0085\3\u0085\3\u0085")NEWLINE buf.write("\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085")NEWLINE buf.write("\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085\3\u0085")NEWLINE buf.write("\3\u0085\3\u0085\3\u0085\3\u0085\3\u0086\3\u0086\3\u0086")NEWLINE buf.write("\3\u0086\3\u0086\3\u0086\3\u0086\3\u0086\3\u0086\3\u0086")NEWLINE buf.write("\3\u0086\3\u0086\3\u0086\3\u0087\3\u0087\3\u0087\3\u0087")NEWLINE buf.write("\3\u0087\3\u0087\3\u0087\3\u0087\3\u0087\3\u0087\3\u0087")NEWLINE buf.write("\3\u0087\3\u0087\3\u0087\3\u0087\3\u0087\3\u0088\3\u0088")NEWLINE buf.write("\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088")NEWLINE buf.write("\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088")NEWLINE buf.write("\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088\3\u0088")NEWLINE buf.write("\3\u0088\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089")NEWLINE buf.write("\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089")NEWLINE buf.write("\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089")NEWLINE buf.write("\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089\3\u0089")NEWLINE buf.write("\3\u0089\3\u0089\3\u008a\3\u008a\3\u008a\3\u008a\3\u008a")NEWLINE buf.write("\3\u008a\3\u008a\3\u008a\3\u008a\3\u008a\3\u008a\3\u008a")NEWLINE buf.write("\3\u008a\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b")NEWLINE buf.write("\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b\3\u008b")NEWLINE buf.write("\3\u008b\3\u008b\3\u008b\3\u008b\3\u008c\3\u008c\3\u008c")NEWLINE buf.write("\3\u008c\3\u008c\3\u008c\3\u008c\3\u008d\3\u008d\3\u008d")NEWLINE buf.write("\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d")NEWLINE buf.write("\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d\3\u008d")NEWLINE buf.write("\3\u008d\3\u008d\3\u008e\3\u008e\3\u008e\3\u008e\3\u008e")NEWLINE buf.write("\3\u008e\3\u008e\3\u008e\3\u008f\3\u008f\3\u008f\3\u008f")NEWLINE buf.write("\3\u008f\3\u008f\3\u008f\3\u008f\3\u0090\3\u0090\3\u0090")NEWLINE buf.write("\3\u0090\3\u0090\3\u0090\3\u0090\3\u0090\3\u0090\3\u0090")NEWLINE buf.write("\3\u0091\3\u0091\3\u0091\3\u0091\3\u0091\3\u0091\3\u0091")NEWLINE buf.write("\3\u0091\3\u0092\3\u0092\3\u0092\3\u0092\3\u0092\3\u0092")NEWLINE buf.write("\3\u0092\3\u0092\3\u0092\3\u0092\3\u0092\3\u0093\3\u0093")NEWLINE buf.write("\3\u0093\3\u0093\3\u0093\3\u0093\3\u0093\3\u0093\3\u0093")NEWLINE buf.write("\3\u0094\3\u0094\3\u0094\7\u0094\u0720\n\u0094\f\u0094")NEWLINE buf.write("\16\u0094\u0723\13\u0094\3\u0095\6\u0095\u0726\n\u0095")NEWLINE buf.write("\r\u0095\16\u0095\u0727\3\u0095\3\u0095\2\2\u0096\3\3")NEWLINE buf.write("\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16")NEWLINE buf.write("\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61")NEWLINE buf.write("\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%I&K\'M(O)Q*")NEWLINE buf.write("S+U,W-Y.[/]\60_\61a\62c\63e\64g\65i\66k\67m8o9q:s;u<w")NEWLINE buf.write("=y>{?}@\177A\u0081B\u0083C\u0085D\u0087E\u0089F\u008b")NEWLINE buf.write("G\u008dH\u008fI\u0091J\u0093K\u0095L\u0097M\u0099N\u009b")NEWLINE buf.write("O\u009dP\u009fQ\u00a1R\u00a3S\u00a5T\u00a7U\u00a9V\u00ab")NEWLINE buf.write("W\u00adX\u00afY\u00b1Z\u00b3[\u00b5\\\u00b7]\u00b9^\u00bb")NEWLINE buf.write("_\u00bd`\u00bfa\u00c1\2\u00c3b\u00c5\2\u00c7\2\u00c9\2")NEWLINE buf.write("\u00cb\2\u00cd\2\u00cf\2\u00d1\2\u00d3\2\u00d5c\u00d7")NEWLINE buf.write("d\u00d9e\u00dbf\u00ddg\u00dfh\u00e1i\u00e3j\u00e5k\u00e7")NEWLINE buf.write("l\u00e9m\u00ebn\u00edo\u00efp\u00f1q\u00f3r\u00f5s\u00f7")NEWLINE buf.write("t\u00f9u\u00fbv\u00fdw\u00ffx\u0101y\u0103z\u0105{\u0107")NEWLINE buf.write("|\u0109}\u010b~\u010d\177\u010f\u0080\u0111\u0081\u0113")NEWLINE buf.write("\u0082\u0115\u0083\u0117\u0084\u0119\u0085\u011b\u0086")NEWLINE buf.write("\u011d\u0087\u011f\u0088\u0121\u0089\u0123\u008a\u0125")NEWLINE buf.write("\u008b\u0127\u008c\u0129\u008d\3\2\f\4\2\f\f\17\17\3\2")NEWLINE buf.write("\63;\5\2\62;CHch\3\2\62;\20\2##&(,-/\61>\\`ac|\u0080\u0080")NEWLINE buf.write("\u00c6\u00c6\u00d8\u00d8\u00de\u00de\u00e6\u00e6\u00f8")NEWLINE buf.write("\u00f8\u00fe\u00fe\3\2\62\63\4\2\"\u0080\u0082\1\5\2\"")NEWLINE buf.write("#%\u0080\u0082\1\6\2\"]_}\177\u0080\u0082\1\5\2\13\f\17")NEWLINE buf.write("\17\"\"\2\u0733\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2")NEWLINE buf.write("\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21")NEWLINE buf.write("\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3")NEWLINE buf.write("\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2")NEWLINE buf.write("\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2")NEWLINE buf.write("\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2")NEWLINE buf.write("\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2")NEWLINE buf.write("\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3")NEWLINE buf.write("\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q")NEWLINE buf.write("\3\2\2\2\2S\3\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2")NEWLINE buf.write("[\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2")NEWLINE buf.write("\2e\3\2\2\2\2g\3\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2")NEWLINE buf.write("\2\2o\3\2\2\2\2q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3\2")NEWLINE buf.write("\2\2\2y\3\2\2\2\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2\2")NEWLINE buf.write("\u0081\3\2\2\2\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087")NEWLINE buf.write("\3\2\2\2\2\u0089\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2\2")NEWLINE buf.write("\2\2\u008f\3\2\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2\2\2\u0095")NEWLINE buf.write("\3\2\2\2\2\u0097\3\2\2\2\2\u0099\3\2\2\2\2\u009b\3\2\2")NEWLINE buf.write("\2\2\u009d\3\2\2\2\2\u009f\3\2\2\2\2\u00a1\3\2\2\2\2\u00a3")NEWLINE buf.write("\3\2\2\2\2\u00a5\3\2\2\2\2\u00a7\3\2\2\2\2\u00a9\3\2\2")NEWLINE buf.write("\2\2\u00ab\3\2\2\2\2\u00ad\3\2\2\2\2\u00af\3\2\2\2\2\u00b1")NEWLINE buf.write("\3\2\2\2\2\u00b3\3\2\2\2\2\u00b5\3\2\2\2\2\u00b7\3\2\2")NEWLINE buf.write("\2\2\u00b9\3\2\2\2\2\u00bb\3\2\2\2\2\u00bd\3\2\2\2\2\u00bf")NEWLINE buf.write("\3\2\2\2\2\u00c3\3\2\2\2\2\u00d5\3\2\2\2\2\u00d7\3\2\2")NEWLINE buf.write("\2\2\u00d9\3\2\2\2\2\u00db\3\2\2\2\2\u00dd\3\2\2\2\2\u00df")NEWLINE buf.write("\3\2\2\2\2\u00e1\3\2\2\2\2\u00e3\3\2\2\2\2\u00e5\3\2\2")NEWLINE buf.write("\2\2\u00e7\3\2\2\2\2\u00e9\3\2\2\2\2\u00eb\3\2\2\2\2\u00ed")NEWLINE buf.write("\3\2\2\2\2\u00ef\3\2\2\2\2\u00f1\3\2\2\2\2\u00f3\3\2\2")NEWLINE buf.write("\2\2\u00f5\3\2\2\2\2\u00f7\3\2\2\2\2\u00f9\3\2\2\2\2\u00fb")NEWLINE buf.write("\3\2\2\2\2\u00fd\3\2\2\2\2\u00ff\3\2\2\2\2\u0101\3\2\2")NEWLINE buf.write("\2\2\u0103\3\2\2\2\2\u0105\3\2\2\2\2\u0107\3\2\2\2\2\u0109")NEWLINE buf.write("\3\2\2\2\2\u010b\3\2\2\2\2\u010d\3\2\2\2\2\u010f\3\2\2")NEWLINE buf.write("\2\2\u0111\3\2\2\2\2\u0113\3\2\2\2\2\u0115\3\2\2\2\2\u0117")NEWLINE buf.write("\3\2\2\2\2\u0119\3\2\2\2\2\u011b\3\2\2\2\2\u011d\3\2\2")NEWLINE buf.write("\2\2\u011f\3\2\2\2\2\u0121\3\2\2\2\2\u0123\3\2\2\2\2\u0125")NEWLINE buf.write("\3\2\2\2\2\u0127\3\2\2\2\2\u0129\3\2\2\2\3\u012b\3\2\2")NEWLINE buf.write("\2\5\u012f\3\2\2\2\7\u0138\3\2\2\2\t\u013a\3\2\2\2\13")NEWLINE buf.write("\u013c\3\2\2\2\r\u013e\3\2\2\2\17\u0148\3\2\2\2\21\u0169")NEWLINE buf.write("\3\2\2\2\23\u016b\3\2\2\2\25\u016f\3\2\2\2\27\u0174\3")NEWLINE buf.write("\2\2\2\31\u0178\3\2\2\2\33\u017d\3\2\2\2\35\u0191\3\2")NEWLINE buf.write("\2\2\37\u0197\3\2\2\2!\u019d\3\2\2\2#\u01ac\3\2\2\2%\u01b7")NEWLINE buf.write("\3\2\2\2\'\u01bd\3\2\2\2)\u01c4\3\2\2\2+\u01c8\3\2\2\2")NEWLINE buf.write("-\u01d0\3\2\2\2/\u01d7\3\2\2\2\61\u01dc\3\2\2\2\63\u01e4")NEWLINE buf.write("\3\2\2\2\65\u01f0\3\2\2\2\67\u01f6\3\2\2\29\u01fd\3\2")NEWLINE buf.write("\2\2;\u0209\3\2\2\2=\u0212\3\2\2\2?\u021c\3\2\2\2A\u022f")NEWLINE buf.write("\3\2\2\2C\u023f\3\2\2\2E\u0246\3\2\2\2G\u024f\3\2\2\2")NEWLINE buf.write("I\u0258\3\2\2\2K\u0266\3\2\2\2M\u0277\3\2\2\2O\u028a\3")NEWLINE buf.write("\2\2\2Q\u029c\3\2\2\2S\u02b0\3\2\2\2U\u02bc\3\2\2\2W\u02c9")NEWLINE buf.write("\3\2\2\2Y\u02d0\3\2\2\2[\u02db\3\2\2\2]\u02e8\3\2\2\2")NEWLINE buf.write("_\u02f7\3\2\2\2a\u0307\3\2\2\2c\u0313\3\2\2\2e\u031b\3")NEWLINE buf.write("\2\2\2g\u0320\3\2\2\2i\u0325\3\2\2\2k\u032a\3\2\2\2m\u0339")NEWLINE buf.write("\3\2\2\2o\u0348\3\2\2\2q\u0357\3\2\2\2s\u0360\3\2\2\2")NEWLINE buf.write("u\u036a\3\2\2\2w\u0376\3\2\2\2y\u0381\3\2\2\2{\u038d\3")NEWLINE buf.write("\2\2\2}\u0397\3\2\2\2\177\u03ad\3\2\2\2\u0081\u03bc\3")NEWLINE buf.write("\2\2\2\u0083\u03c6\3\2\2\2\u0085\u03ca\3\2\2\2\u0087\u03cf")NEWLINE buf.write("\3\2\2\2\u0089\u03d5\3\2\2\2\u008b\u03e6\3\2\2\2\u008d")NEWLINE buf.write("\u03ef\3\2\2\2\u008f\u03f9\3\2\2\2\u0091\u0404\3\2\2\2")NEWLINE buf.write("\u0093\u0409\3\2\2\2\u0095\u0412\3\2\2\2\u0097\u041b\3")NEWLINE buf.write("\2\2\2\u0099\u0423\3\2\2\2\u009b\u042f\3\2\2\2\u009d\u0436")NEWLINE buf.write("\3\2\2\2\u009f\u043e\3\2\2\2\u00a1\u044b\3\2\2\2\u00a3")NEWLINE buf.write("\u044d\3\2\2\2\u00a5\u044f\3\2\2\2\u00a7\u0452\3\2\2\2")NEWLINE buf.write("\u00a9\u0459\3\2\2\2\u00ab\u0461\3\2\2\2\u00ad\u0468\3")NEWLINE buf.write("\2\2\2\u00af\u0474\3\2\2\2\u00b1\u047b\3\2\2\2\u00b3\u047f")NEWLINE buf.write("\3\2\2\2\u00b5\u0485\3\2\2\2\u00b7\u048d\3\2\2\2\u00b9")NEWLINE buf.write("\u0499\3\2\2\2\u00bb\u049b\3\2\2\2\u00bd\u04a3\3\2\2\2")NEWLINE buf.write("\u00bf\u04ab\3\2\2\2\u00c1\u04b5\3\2\2\2\u00c3\u04b7\3")NEWLINE buf.write("\2\2\2\u00c5\u04b9\3\2\2\2\u00c7\u04bb\3\2\2\2\u00c9\u04bd")NEWLINE buf.write("\3\2\2\2\u00cb\u04c1\3\2\2\2\u00cd\u04c5\3\2\2\2\u00cf")NEWLINE buf.write("\u04c9\3\2\2\2\u00d1\u04cb\3\2\2\2\u00d3\u04ce\3\2\2\2")NEWLINE buf.write("\u00d5\u04d0\3\2\2\2\u00d7\u04e0\3\2\2\2\u00d9\u04f8\3")NEWLINE buf.write("\2\2\2\u00db\u0501\3\2\2\2\u00dd\u050b\3\2\2\2\u00df\u0516")NEWLINE buf.write("\3\2\2\2\u00e1\u0522\3\2\2\2\u00e3\u053d\3\2\2\2\u00e5")NEWLINE buf.write("\u054d\3\2\2\2\u00e7\u0559\3\2\2\2\u00e9\u055f\3\2\2\2")NEWLINE buf.write("\u00eb\u0571\3\2\2\2\u00ed\u0586\3\2\2\2\u00ef\u0598\3")NEWLINE buf.write("\2\2\2\u00f1\u05a2\3\2\2\2\u00f3\u05ae\3\2\2\2\u00f5\u05b7")NEWLINE buf.write("\3\2\2\2\u00f7\u05be\3\2\2\2\u00f9\u05c4\3\2\2\2\u00fb")NEWLINE buf.write("\u05cb\3\2\2\2\u00fd\u05d4\3\2\2\2\u00ff\u05e3\3\2\2\2")NEWLINE buf.write("\u0101\u05f7\3\2\2\2\u0103\u060c\3\2\2\2\u0105\u061c\3")NEWLINE buf.write("\2\2\2\u0107\u062c\3\2\2\2\u0109\u0647\3\2\2\2\u010b\u065c")NEWLINE buf.write("\3\2\2\2\u010d\u0669\3\2\2\2\u010f\u0679\3\2\2\2\u0111")NEWLINE buf.write("\u0691\3\2\2\2\u0113\u06ae\3\2\2\2\u0115\u06bb\3\2\2\2")NEWLINE buf.write("\u0117\u06cc\3\2\2\2\u0119\u06d3\3\2\2\2\u011b\u06e6\3")NEWLINE buf.write("\2\2\2\u011d\u06ee\3\2\2\2\u011f\u06f6\3\2\2\2\u0121\u0700")NEWLINE buf.write("\3\2\2\2\u0123\u0708\3\2\2\2\u0125\u0713\3\2\2\2\u0127")NEWLINE buf.write("\u071c\3\2\2\2\u0129\u0725\3\2\2\2\u012b\u012c\7\"\2\2")NEWLINE buf.write("\u012c\u012d\7d\2\2\u012d\u012e\7x\2\2\u012e\4\3\2\2\2")NEWLINE buf.write("\u012f\u0133\5\13\6\2\u0130\u0132\n\2\2\2\u0131\u0130")NEWLINE buf.write("\3\2\2\2\u0132\u0135\3\2\2\2\u0133\u0131\3\2\2\2\u0133")NEWLINE buf.write("\u0134\3\2\2\2\u0134\u0136\3\2\2\2\u0135\u0133\3\2\2\2")NEWLINE buf.write("\u0136\u0137\b\3\2\2\u0137\6\3\2\2\2\u0138\u0139\7*\2")NEWLINE buf.write("\2\u0139\b\3\2\2\2\u013a\u013b\7+\2\2\u013b\n\3\2\2\2")NEWLINE buf.write("\u013c\u013d\7=\2\2\u013d\f\3\2\2\2\u013e\u0143\7$\2\2")NEWLINE buf.write("\u013f\u0142\5\u00cdg\2\u0140\u0142\5\u00d3j\2\u0141\u013f")NEWLINE buf.write("\3\2\2\2\u0141\u0140\3\2\2\2\u0142\u0145\3\2\2\2\u0143")NEWLINE buf.write("\u0141\3\2\2\2\u0143\u0144\3\2\2\2\u0144\u0146\3\2\2\2")NEWLINE buf.write("\u0145\u0143\3\2\2\2\u0146\u0147\7$\2\2\u0147\16\3\2\2")NEWLINE buf.write("\2\u0148\u014d\7~\2\2\u0149\u014c\5\u00cfh\2\u014a\u014c")NEWLINE buf.write("\5\u00d3j\2\u014b\u0149\3\2\2\2\u014b\u014a\3\2\2\2\u014c")NEWLINE buf.write("\u014f\3\2\2\2\u014d\u014b\3\2\2\2\u014d\u014e\3\2\2\2")NEWLINE buf.write("\u014e\u0150\3\2\2\2\u014f\u014d\3\2\2\2\u0150\u0151\7")NEWLINE buf.write("~\2\2\u0151\20\3\2\2\2\u0152\u0153\7t\2\2\u0153\u0154")NEWLINE buf.write("\7g\2\2\u0154\u0155\7\60\2\2\u0155\u0156\7p\2\2\u0156")NEWLINE buf.write("\u0157\7q\2\2\u0157\u0158\7p\2\2\u0158\u016a\7g\2\2\u0159")NEWLINE buf.write("\u015a\7t\2\2\u015a\u015b\7g\2\2\u015b\u015c\7\60\2\2")NEWLINE buf.write("\u015c\u015d\7c\2\2\u015d\u015e\7n\2\2\u015e\u016a\7n")NEWLINE buf.write("\2\2\u015f\u0160\7t\2\2\u0160\u0161\7g\2\2\u0161\u0162")NEWLINE buf.write("\7\60\2\2\u0162\u0163\7c\2\2\u0163\u0164\7n\2\2\u0164")NEWLINE buf.write("\u0165\7n\2\2\u0165\u0166\7e\2\2\u0166\u0167\7j\2\2\u0167")NEWLINE buf.write("\u0168\7c\2\2\u0168\u016a\7t\2\2\u0169\u0152\3\2\2\2\u0169")NEWLINE buf.write("\u0159\3\2\2\2\u0169\u015f\3\2\2\2\u016a\22\3\2\2\2\u016b")NEWLINE buf.write("\u016c\7p\2\2\u016c\u016d\7q\2\2\u016d\u016e\7v\2\2\u016e")NEWLINE buf.write("\24\3\2\2\2\u016f\u0170\7D\2\2\u0170\u0171\7q\2\2\u0171")NEWLINE buf.write("\u0172\7q\2\2\u0172\u0173\7n\2\2\u0173\26\3\2\2\2\u0174")NEWLINE buf.write("\u0175\7K\2\2\u0175\u0176\7p\2\2\u0176\u0177\7v\2\2\u0177")NEWLINE buf.write("\30\3\2\2\2\u0178\u0179\7T\2\2\u0179\u017a\7g\2\2\u017a")NEWLINE buf.write("\u017b\7c\2\2\u017b\u017c\7n\2\2\u017c\32\3\2\2\2\u017d")NEWLINE buf.write("\u017e\7e\2\2\u017e\u017f\7q\2\2\u017f\u0180\7p\2\2\u0180")NEWLINE buf.write("\u0181\7v\2\2\u0181\u0182\7k\2\2\u0182\u0183\7p\2\2\u0183")NEWLINE buf.write("\u0184\7w\2\2\u0184\u0185\7g\2\2\u0185\u0186\7f\2\2\u0186")NEWLINE buf.write("\u0187\7/\2\2\u0187\u0188\7g\2\2\u0188\u0189\7z\2\2\u0189")NEWLINE buf.write("\u018a\7g\2\2\u018a\u018b\7e\2\2\u018b\u018c\7w\2\2\u018c")NEWLINE buf.write("\u018d\7v\2\2\u018d\u018e\7k\2\2\u018e\u018f\7q\2\2\u018f")NEWLINE buf.write("\u0190\7p\2\2\u0190\34\3\2\2\2\u0191\u0192\7g\2\2\u0192")NEWLINE buf.write("\u0193\7t\2\2\u0193\u0194\7t\2\2\u0194\u0195\7q\2\2\u0195")NEWLINE buf.write("\u0196\7t\2\2\u0196\36\3\2\2\2\u0197\u0198\7h\2\2\u0198")NEWLINE buf.write("\u0199\7c\2\2\u0199\u019a\7n\2\2\u019a\u019b\7u\2\2\u019b")NEWLINE buf.write("\u019c\7g\2\2\u019c \3\2\2\2\u019d\u019e\7k\2\2\u019e")NEWLINE buf.write("\u019f\7o\2\2\u019f\u01a0\7o\2\2\u01a0\u01a1\7g\2\2\u01a1")NEWLINE buf.write("\u01a2\7f\2\2\u01a2\u01a3\7k\2\2\u01a3\u01a4\7c\2\2\u01a4")NEWLINE buf.write("\u01a5\7v\2\2\u01a5\u01a6\7g\2\2\u01a6\u01a7\7/\2\2\u01a7")NEWLINE buf.write("\u01a8\7g\2\2\u01a8\u01a9\7z\2\2\u01a9\u01aa\7k\2\2\u01aa")NEWLINE buf.write("\u01ab\7v\2\2\u01ab\"\3\2\2\2\u01ac\u01ad\7k\2\2\u01ad")NEWLINE buf.write("\u01ae\7p\2\2\u01ae\u01af\7e\2\2\u01af\u01b0\7q\2\2\u01b0")NEWLINE buf.write("\u01b1\7o\2\2\u01b1\u01b2\7r\2\2\u01b2\u01b3\7n\2\2\u01b3")NEWLINE buf.write("\u01b4\7g\2\2\u01b4\u01b5\7v\2\2\u01b5\u01b6\7g\2\2\u01b6")NEWLINE buf.write("$\3\2\2\2\u01b7\u01b8\7n\2\2\u01b8\u01b9\7q\2\2\u01b9")NEWLINE buf.write("\u01ba\7i\2\2\u01ba\u01bb\7k\2\2\u01bb\u01bc\7e\2\2\u01bc")NEWLINE buf.write("&\3\2\2\2\u01bd\u01be\7o\2\2\u01be\u01bf\7g\2\2\u01bf")NEWLINE buf.write("\u01c0\7o\2\2\u01c0\u01c1\7q\2\2\u01c1\u01c2\7w\2\2\u01c2")NEWLINE buf.write("\u01c3\7v\2\2\u01c3(\3\2\2\2\u01c4\u01c5\7u\2\2\u01c5")NEWLINE buf.write("\u01c6\7c\2\2\u01c6\u01c7\7v\2\2\u01c7*\3\2\2\2\u01c8")NEWLINE buf.write("\u01c9\7u\2\2\u01c9\u01ca\7w\2\2\u01ca\u01cb\7e\2\2\u01cb")NEWLINE buf.write("\u01cc\7e\2\2\u01cc\u01cd\7g\2\2\u01cd\u01ce\7u\2\2\u01ce")NEWLINE buf.write("\u01cf\7u\2\2\u01cf,\3\2\2\2\u01d0\u01d1\7v\2\2\u01d1")NEWLINE buf.write("\u01d2\7j\2\2\u01d2\u01d3\7g\2\2\u01d3\u01d4\7q\2\2\u01d4")NEWLINE buf.write("\u01d5\7t\2\2\u01d5\u01d6\7{\2\2\u01d6.\3\2\2\2\u01d7")NEWLINE buf.write("\u01d8\7v\2\2\u01d8\u01d9\7t\2\2\u01d9\u01da\7w\2\2\u01da")NEWLINE buf.write("\u01db\7g\2\2\u01db\60\3\2\2\2\u01dc\u01dd\7w\2\2\u01dd")NEWLINE buf.write("\u01de\7p\2\2\u01de\u01df\7m\2\2\u01df\u01e0\7p\2\2\u01e0")NEWLINE buf.write("\u01e1\7q\2\2\u01e1\u01e2\7y\2\2\u01e2\u01e3\7p\2\2\u01e3")NEWLINE buf.write("\62\3\2\2\2\u01e4\u01e5\7w\2\2\u01e5\u01e6\7p\2\2\u01e6")NEWLINE buf.write("\u01e7\7u\2\2\u01e7\u01e8\7w\2\2\u01e8\u01e9\7r\2\2\u01e9")NEWLINE buf.write("\u01ea\7r\2\2\u01ea\u01eb\7q\2\2\u01eb\u01ec\7t\2\2\u01ec")NEWLINE buf.write("\u01ed\7v\2\2\u01ed\u01ee\7g\2\2\u01ee\u01ef\7f\2\2\u01ef")NEWLINE buf.write("\64\3\2\2\2\u01f0\u01f1\7w\2\2\u01f1\u01f2\7p\2\2\u01f2")NEWLINE buf.write("\u01f3\7u\2\2\u01f3\u01f4\7c\2\2\u01f4\u01f5\7v\2\2\u01f5")NEWLINE buf.write("\66\3\2\2\2\u01f6\u01f7\7c\2\2\u01f7\u01f8\7u\2\2\u01f8")NEWLINE buf.write("\u01f9\7u\2\2\u01f9\u01fa\7g\2\2\u01fa\u01fb\7t\2\2\u01fb")NEWLINE buf.write("\u01fc\7v\2\2\u01fc8\3\2\2\2\u01fd\u01fe\7c\2\2\u01fe")NEWLINE buf.write("\u01ff\7u\2\2\u01ff\u0200\7u\2\2\u0200\u0201\7g\2\2\u0201")NEWLINE buf.write("\u0202\7t\2\2\u0202\u0203\7v\2\2\u0203\u0204\7/\2\2\u0204")NEWLINE buf.write("\u0205\7u\2\2\u0205\u0206\7q\2\2\u0206\u0207\7h\2\2\u0207")NEWLINE buf.write("\u0208\7v\2\2\u0208:\3\2\2\2\u0209\u020a\7u\2\2\u020a")NEWLINE buf.write("\u020b\7k\2\2\u020b\u020c\7o\2\2\u020c\u020d\7r\2\2\u020d")NEWLINE buf.write("\u020e\7n\2\2\u020e\u020f\7k\2\2\u020f\u0210\7h\2\2\u0210")NEWLINE buf.write("\u0211\7{\2\2\u0211<\3\2\2\2\u0212\u0213\7e\2\2\u0213")NEWLINE buf.write("\u0214\7j\2\2\u0214\u0215\7g\2\2\u0215\u0216\7e\2\2\u0216")NEWLINE buf.write("\u0217\7m\2\2\u0217\u0218\7/\2\2\u0218\u0219\7u\2\2\u0219")NEWLINE buf.write("\u021a\7c\2\2\u021a\u021b\7v\2\2\u021b>\3\2\2\2\u021c")NEWLINE buf.write("\u021d\7e\2\2\u021d\u021e\7j\2\2\u021e\u021f\7g\2\2\u021f")NEWLINE buf.write("\u0220\7e\2\2\u0220\u0221\7m\2\2\u0221\u0222\7/\2\2\u0222")NEWLINE buf.write("\u0223\7u\2\2\u0223\u0224\7c\2\2\u0224\u0225\7v\2\2\u0225")NEWLINE buf.write("\u0226\7/\2\2\u0226\u0227\7c\2\2\u0227\u0228\7u\2\2\u0228")NEWLINE buf.write("\u0229\7u\2\2\u0229\u022a\7w\2\2\u022a\u022b\7o\2\2\u022b")NEWLINE buf.write("\u022c\7k\2\2\u022c\u022d\7p\2\2\u022d\u022e\7i\2\2\u022e")NEWLINE buf.write("@\3\2\2\2\u022f\u0230\7e\2\2\u0230\u0231\7j\2\2\u0231")NEWLINE buf.write("\u0232\7g\2\2\u0232\u0233\7e\2\2\u0233\u0234\7m\2\2\u0234")NEWLINE buf.write("\u0235\7/\2\2\u0235\u0236\7u\2\2\u0236\u0237\7c\2\2\u0237")NEWLINE buf.write("\u0238\7v\2\2\u0238\u0239\7/\2\2\u0239\u023a\7w\2\2\u023a")NEWLINE buf.write("\u023b\7u\2\2\u023b\u023c\7k\2\2\u023c\u023d\7p\2\2\u023d")NEWLINE buf.write("\u023e\7i\2\2\u023eB\3\2\2\2\u023f\u0240\7n\2\2\u0240")NEWLINE buf.write("\u0241\7c\2\2\u0241\u0242\7d\2\2\u0242\u0243\7g\2\2\u0243")NEWLINE buf.write("\u0244\7n\2\2\u0244\u0245\7u\2\2\u0245D\3\2\2\2\u0246")NEWLINE buf.write("\u0247\7o\2\2\u0247\u0248\7k\2\2\u0248\u0249\7p\2\2\u0249")NEWLINE buf.write("\u024a\7k\2\2\u024a\u024b\7o\2\2\u024b\u024c\7k\2\2\u024c")NEWLINE buf.write("\u024d\7|\2\2\u024d\u024e\7g\2\2\u024eF\3\2\2\2\u024f")NEWLINE buf.write("\u0250\7o\2\2\u0250\u0251\7c\2\2\u0251\u0252\7z\2\2\u0252")NEWLINE buf.write("\u0253\7k\2\2\u0253\u0254\7o\2\2\u0254\u0255\7k\2\2\u0255")NEWLINE buf.write("\u0256\7|\2\2\u0256\u0257\7g\2\2\u0257H\3\2\2\2\u0258")NEWLINE buf.write("\u0259\7f\2\2\u0259\u025a\7g\2\2\u025a\u025b\7e\2\2\u025b")NEWLINE buf.write("\u025c\7n\2\2\u025c\u025d\7c\2\2\u025d\u025e\7t\2\2\u025e")NEWLINE buf.write("\u025f\7g\2\2\u025f\u0260\7/\2\2\u0260\u0261\7e\2\2\u0261")NEWLINE buf.write("\u0262\7q\2\2\u0262\u0263\7p\2\2\u0263\u0264\7u\2\2\u0264")NEWLINE buf.write("\u0265\7v\2\2\u0265J\3\2\2\2\u0266\u0267\7f\2\2\u0267")NEWLINE buf.write("\u0268\7g\2\2\u0268\u0269\7e\2\2\u0269\u026a\7n\2\2\u026a")NEWLINE buf.write("\u026b\7c\2\2\u026b\u026c\7t\2\2\u026c\u026d\7g\2\2\u026d")NEWLINE buf.write("\u026e\7/\2\2\u026e\u026f\7f\2\2\u026f\u0270\7c\2\2\u0270")NEWLINE buf.write("\u0271\7v\2\2\u0271\u0272\7c\2\2\u0272\u0273\7v\2\2\u0273")NEWLINE buf.write("\u0274\7{\2\2\u0274\u0275\7r\2\2\u0275\u0276\7g\2\2\u0276")NEWLINE buf.write("L\3\2\2\2\u0277\u0278\7f\2\2\u0278\u0279\7g\2\2\u0279")NEWLINE buf.write("\u027a\7e\2\2\u027a\u027b\7n\2\2\u027b\u027c\7c\2\2\u027c")NEWLINE buf.write("\u027d\7t\2\2\u027d\u027e\7g\2\2\u027e\u027f\7/\2\2\u027f")NEWLINE buf.write("\u0280\7e\2\2\u0280\u0281\7q\2\2\u0281\u0282\7f\2\2\u0282")NEWLINE buf.write("\u0283\7c\2\2\u0283\u0284\7v\2\2\u0284\u0285\7c\2\2\u0285")NEWLINE buf.write("\u0286\7v\2\2\u0286\u0287\7{\2\2\u0287\u0288\7r\2\2\u0288")NEWLINE buf.write("\u0289\7g\2\2\u0289N\3\2\2\2\u028a\u028b\7f\2\2\u028b")NEWLINE buf.write("\u028c\7g\2\2\u028c\u028d\7e\2\2\u028d\u028e\7n\2\2\u028e")NEWLINE buf.write("\u028f\7c\2\2\u028f\u0290\7t\2\2\u0290\u0291\7g\2\2\u0291")NEWLINE buf.write("\u0292\7/\2\2\u0292\u0293\7f\2\2\u0293\u0294\7c\2\2\u0294")NEWLINE buf.write("\u0295\7v\2\2\u0295\u0296\7c\2\2\u0296\u0297\7v\2\2\u0297")NEWLINE buf.write("\u0298\7{\2\2\u0298\u0299\7r\2\2\u0299\u029a\7g\2\2\u029a")NEWLINE buf.write("\u029b\7u\2\2\u029bP\3\2\2\2\u029c\u029d\7f\2\2\u029d")NEWLINE buf.write("\u029e\7g\2\2\u029e\u029f\7e\2\2\u029f\u02a0\7n\2\2\u02a0")NEWLINE buf.write("\u02a1\7c\2\2\u02a1\u02a2\7t\2\2\u02a2\u02a3\7g\2\2\u02a3")NEWLINE buf.write("\u02a4\7/\2\2\u02a4\u02a5\7e\2\2\u02a5\u02a6\7q\2\2\u02a6")NEWLINE buf.write("\u02a7\7f\2\2\u02a7\u02a8\7c\2\2\u02a8\u02a9\7v\2\2\u02a9")NEWLINE buf.write("\u02aa\7c\2\2\u02aa\u02ab\7v\2\2\u02ab\u02ac\7{\2\2\u02ac")NEWLINE buf.write("\u02ad\7r\2\2\u02ad\u02ae\7g\2\2\u02ae\u02af\7u\2\2\u02af")NEWLINE buf.write("R\3\2\2\2\u02b0\u02b1\7f\2\2\u02b1\u02b2\7g\2\2\u02b2")NEWLINE buf.write("\u02b3\7e\2\2\u02b3\u02b4\7n\2\2\u02b4\u02b5\7c\2\2\u02b5")NEWLINE buf.write("\u02b6\7t\2\2\u02b6\u02b7\7g\2\2\u02b7\u02b8\7/\2\2\u02b8")NEWLINE buf.write("\u02b9\7h\2\2\u02b9\u02ba\7w\2\2\u02ba\u02bb\7p\2\2\u02bb")NEWLINE buf.write("T\3\2\2\2\u02bc\u02bd\7f\2\2\u02bd\u02be\7g\2\2\u02be")NEWLINE buf.write("\u02bf\7e\2\2\u02bf\u02c0\7n\2\2\u02c0\u02c1\7c\2\2\u02c1")NEWLINE buf.write("\u02c2\7t\2\2\u02c2\u02c3\7g\2\2\u02c3\u02c4\7/\2\2\u02c4")NEWLINE buf.write("\u02c5\7u\2\2\u02c5\u02c6\7q\2\2\u02c6\u02c7\7t\2\2\u02c7")NEWLINE buf.write("\u02c8\7v\2\2\u02c8V\3\2\2\2\u02c9\u02ca\7f\2\2\u02ca")NEWLINE buf.write("\u02cb\7g\2\2\u02cb\u02cc\7h\2\2\u02cc\u02cd\7k\2\2\u02cd")NEWLINE buf.write("\u02ce\7p\2\2\u02ce\u02cf\7g\2\2\u02cfX\3\2\2\2\u02d0")NEWLINE buf.write("\u02d1\7f\2\2\u02d1\u02d2\7g\2\2\u02d2\u02d3\7h\2\2\u02d3")NEWLINE buf.write("\u02d4\7k\2\2\u02d4\u02d5\7p\2\2\u02d5\u02d6\7g\2\2\u02d6")NEWLINE buf.write("\u02d7\7/\2\2\u02d7\u02d8\7h\2\2\u02d8\u02d9\7w\2\2\u02d9")NEWLINE buf.write("\u02da\7p\2\2\u02daZ\3\2\2\2\u02db\u02dc\7f\2\2\u02dc")NEWLINE buf.write("\u02dd\7g\2\2\u02dd\u02de\7h\2\2\u02de\u02df\7k\2\2\u02df")NEWLINE buf.write("\u02e0\7p\2\2\u02e0\u02e1\7g\2\2\u02e1\u02e2\7/\2\2\u02e2")NEWLINE buf.write("\u02e3\7e\2\2\u02e3\u02e4\7q\2\2\u02e4\u02e5\7p\2\2\u02e5")NEWLINE buf.write("\u02e6\7u\2\2\u02e6\u02e7\7v\2\2\u02e7\\\3\2\2\2\u02e8")NEWLINE buf.write("\u02e9\7f\2\2\u02e9\u02ea\7g\2\2\u02ea\u02eb\7h\2\2\u02eb")NEWLINE buf.write("\u02ec\7k\2\2\u02ec\u02ed\7p\2\2\u02ed\u02ee\7g\2\2\u02ee")NEWLINE buf.write("\u02ef\7/\2\2\u02ef\u02f0\7h\2\2\u02f0\u02f1\7w\2\2\u02f1")NEWLINE buf.write("\u02f2\7p\2\2\u02f2\u02f3\7/\2\2\u02f3\u02f4\7t\2\2\u02f4")NEWLINE buf.write("\u02f5\7g\2\2\u02f5\u02f6\7e\2\2\u02f6^\3\2\2\2\u02f7")NEWLINE buf.write("\u02f8\7f\2\2\u02f8\u02f9\7g\2\2\u02f9\u02fa\7h\2\2\u02fa")NEWLINE buf.write("\u02fb\7k\2\2\u02fb\u02fc\7p\2\2\u02fc\u02fd\7g\2\2\u02fd")NEWLINE buf.write("\u02fe\7/\2\2\u02fe\u02ff\7h\2\2\u02ff\u0300\7w\2\2\u0300")NEWLINE buf.write("\u0301\7p\2\2\u0301\u0302\7u\2\2\u0302\u0303\7/\2\2\u0303")NEWLINE buf.write("\u0304\7t\2\2\u0304\u0305\7g\2\2\u0305\u0306\7e\2\2\u0306")NEWLINE buf.write("`\3\2\2\2\u0307\u0308\7f\2\2\u0308\u0309\7g\2\2\u0309")NEWLINE buf.write("\u030a\7h\2\2\u030a\u030b\7k\2\2\u030b\u030c\7p\2\2\u030c")NEWLINE buf.write("\u030d\7g\2\2\u030d\u030e\7/\2\2\u030e\u030f\7u\2\2\u030f")NEWLINE buf.write("\u0310\7q\2\2\u0310\u0311\7t\2\2\u0311\u0312\7v\2\2\u0312")NEWLINE buf.write("b\3\2\2\2\u0313\u0314\7f\2\2\u0314\u0315\7k\2\2\u0315")NEWLINE buf.write("\u0316\7u\2\2\u0316\u0317\7r\2\2\u0317\u0318\7n\2\2\u0318")NEWLINE buf.write("\u0319\7c\2\2\u0319\u031a\7{\2\2\u031ad\3\2\2\2\u031b")NEWLINE buf.write("\u031c\7g\2\2\u031c\u031d\7e\2\2\u031d\u031e\7j\2\2\u031e")NEWLINE buf.write("\u031f\7q\2\2\u031ff\3\2\2\2\u0320\u0321\7g\2\2\u0321")NEWLINE buf.write("\u0322\7x\2\2\u0322\u0323\7c\2\2\u0323\u0324\7n\2\2\u0324")NEWLINE buf.write("h\3\2\2\2\u0325\u0326\7g\2\2\u0326\u0327\7z\2\2\u0327")NEWLINE buf.write("\u0328\7k\2\2\u0328\u0329\7v\2\2\u0329j\3\2\2\2\u032a")NEWLINE buf.write("\u032b\7i\2\2\u032b\u032c\7g\2\2\u032c\u032d\7v\2\2\u032d")NEWLINE buf.write("\u032e\7/\2\2\u032e\u032f\7q\2\2\u032f\u0330\7d\2\2\u0330")NEWLINE buf.write("\u0331\7l\2\2\u0331\u0332\7g\2\2\u0332\u0333\7e\2\2\u0333")NEWLINE buf.write("\u0334\7v\2\2\u0334\u0335\7k\2\2\u0335\u0336\7x\2\2\u0336")NEWLINE buf.write("\u0337\7g\2\2\u0337\u0338\7u\2\2\u0338l\3\2\2\2\u0339")NEWLINE buf.write("\u033a\7i\2\2\u033a\u033b\7g\2\2\u033b\u033c\7v\2\2\u033c")NEWLINE buf.write("\u033d\7/\2\2\u033d\u033e\7c\2\2\u033e\u033f\7u\2\2\u033f")NEWLINE buf.write("\u0340\7u\2\2\u0340\u0341\7g\2\2\u0341\u0342\7t\2\2\u0342")NEWLINE buf.write("\u0343\7v\2\2\u0343\u0344\7k\2\2\u0344\u0345\7q\2\2\u0345")NEWLINE buf.write("\u0346\7p\2\2\u0346\u0347\7u\2\2\u0347n\3\2\2\2\u0348")NEWLINE buf.write("\u0349\7i\2\2\u0349\u034a\7g\2\2\u034a\u034b\7v\2\2\u034b")NEWLINE buf.write("\u034c\7/\2\2\u034c\u034d\7c\2\2\u034d\u034e\7u\2\2\u034e")NEWLINE buf.write("\u034f\7u\2\2\u034f\u0350\7k\2\2\u0350\u0351\7i\2\2\u0351")NEWLINE buf.write("\u0352\7p\2\2\u0352\u0353\7o\2\2\u0353\u0354\7g\2\2\u0354")NEWLINE buf.write("\u0355\7p\2\2\u0355\u0356\7v\2\2\u0356p\3\2\2\2\u0357")NEWLINE buf.write("\u0358\7i\2\2\u0358\u0359\7g\2\2\u0359\u035a\7v\2\2\u035a")NEWLINE buf.write("\u035b\7/\2\2\u035b\u035c\7k\2\2\u035c\u035d\7p\2\2\u035d")NEWLINE buf.write("\u035e\7h\2\2\u035e\u035f\7q\2\2\u035fr\3\2\2\2\u0360")NEWLINE buf.write("\u0361\7i\2\2\u0361\u0362\7g\2\2\u0362\u0363\7v\2\2\u0363")NEWLINE buf.write("\u0364\7/\2\2\u0364\u0365\7o\2\2\u0365\u0366\7q\2\2\u0366")NEWLINE buf.write("\u0367\7f\2\2\u0367\u0368\7g\2\2\u0368\u0369\7n\2\2\u0369")NEWLINE buf.write("t\3\2\2\2\u036a\u036b\7d\2\2\u036b\u036c\7n\2\2\u036c")NEWLINE buf.write("\u036d\7q\2\2\u036d\u036e\7e\2\2\u036e\u036f\7m\2\2\u036f")NEWLINE buf.write("\u0370\7/\2\2\u0370\u0371\7o\2\2\u0371\u0372\7q\2\2\u0372")NEWLINE buf.write("\u0373\7f\2\2\u0373\u0374\7g\2\2\u0374\u0375\7n\2\2\u0375")NEWLINE buf.write("v\3\2\2\2\u0376\u0377\7i\2\2\u0377\u0378\7g\2\2\u0378")NEWLINE buf.write("\u0379\7v\2\2\u0379\u037a\7/\2\2\u037a\u037b\7q\2\2\u037b")NEWLINE buf.write("\u037c\7r\2\2\u037c\u037d\7v\2\2\u037d\u037e\7k\2\2\u037e")NEWLINE buf.write("\u037f\7q\2\2\u037f\u0380\7p\2\2\u0380x\3\2\2\2\u0381")NEWLINE buf.write("\u0382\7r\2\2\u0382\u0383\7q\2\2\u0383\u0384\7n\2\2\u0384")NEWLINE buf.write("\u0385\7{\2\2\u0385\u0386\7\61\2\2\u0386\u0387\7h\2\2")NEWLINE buf.write("\u0387\u0388\7c\2\2\u0388\u0389\7e\2\2\u0389\u038a\7v")NEWLINE buf.write("\2\2\u038a\u038b\7q\2\2\u038b\u038c\7t\2\2\u038cz\3\2")NEWLINE buf.write("\2\2\u038d\u038e\7i\2\2\u038e\u038f\7g\2\2\u038f\u0390")NEWLINE buf.write("\7v\2\2\u0390\u0391\7/\2\2\u0391\u0392\7r\2\2\u0392\u0393")NEWLINE buf.write("\7t\2\2\u0393\u0394\7q\2\2\u0394\u0395\7q\2\2\u0395\u0396")NEWLINE buf.write("\7h\2\2\u0396|\3\2\2\2\u0397\u0398\7i\2\2\u0398\u0399")NEWLINE buf.write("\7g\2\2\u0399\u039a\7v\2\2\u039a\u039b\7/\2\2\u039b\u039c")NEWLINE buf.write("\7w\2\2\u039c\u039d\7p\2\2\u039d\u039e\7u\2\2\u039e\u039f")NEWLINE buf.write("\7c\2\2\u039f\u03a0\7v\2\2\u03a0\u03a1\7/\2\2\u03a1\u03a2")NEWLINE buf.write("\7c\2\2\u03a2\u03a3\7u\2\2\u03a3\u03a4\7u\2\2\u03a4\u03a5")NEWLINE buf.write("\7w\2\2\u03a5\u03a6\7o\2\2\u03a6\u03a7\7r\2\2\u03a7\u03a8")NEWLINE buf.write("\7v\2\2\u03a8\u03a9\7k\2\2\u03a9\u03aa\7q\2\2\u03aa\u03ab")NEWLINE buf.write("\7p\2\2\u03ab\u03ac\7u\2\2\u03ac~\3\2\2\2\u03ad\u03ae")NEWLINE buf.write("\7i\2\2\u03ae\u03af\7g\2\2\u03af\u03b0\7v\2\2\u03b0\u03b1")NEWLINE buf.write("\7/\2\2\u03b1\u03b2\7w\2\2\u03b2\u03b3\7p\2\2\u03b3\u03b4")NEWLINE buf.write("\7u\2\2\u03b4\u03b5\7c\2\2\u03b5\u03b6\7v\2\2\u03b6\u03b7")NEWLINE buf.write("\7/\2\2\u03b7\u03b8\7e\2\2\u03b8\u03b9\7q\2\2\u03b9\u03ba")NEWLINE buf.write("\7t\2\2\u03ba\u03bb\7g\2\2\u03bb\u0080\3\2\2\2\u03bc\u03bd")NEWLINE buf.write("\7i\2\2\u03bd\u03be\7g\2\2\u03be\u03bf\7v\2\2\u03bf\u03c0")NEWLINE buf.write("\7/\2\2\u03c0\u03c1\7x\2\2\u03c1\u03c2\7c\2\2\u03c2\u03c3")NEWLINE buf.write("\7n\2\2\u03c3\u03c4\7w\2\2\u03c4\u03c5\7g\2\2\u03c5\u0082")NEWLINE buf.write("\3\2\2\2\u03c6\u03c7\7r\2\2\u03c7\u03c8\7q\2\2\u03c8\u03c9")NEWLINE buf.write("\7r\2\2\u03c9\u0084\3\2\2\2\u03ca\u03cb\7r\2\2\u03cb\u03cc")NEWLINE buf.write("\7w\2\2\u03cc\u03cd\7u\2\2\u03cd\u03ce\7j\2\2\u03ce\u0086")NEWLINE buf.write("\3\2\2\2\u03cf\u03d0\7t\2\2\u03d0\u03d1\7g\2\2\u03d1\u03d2")NEWLINE buf.write("\7u\2\2\u03d2\u03d3\7g\2\2\u03d3\u03d4\7v\2\2\u03d4\u0088")NEWLINE buf.write("\3\2\2\2\u03d5\u03d6\7t\2\2\u03d6\u03d7\7g\2\2\u03d7\u03d8")NEWLINE buf.write("\7u\2\2\u03d8\u03d9\7g\2\2\u03d9\u03da\7v\2\2\u03da\u03db")NEWLINE buf.write("\7/\2\2\u03db\u03dc\7c\2\2\u03dc\u03dd\7u\2\2\u03dd\u03de")NEWLINE buf.write("\7u\2\2\u03de\u03df\7g\2\2\u03df\u03e0\7t\2\2\u03e0\u03e1")NEWLINE buf.write("\7v\2\2\u03e1\u03e2\7k\2\2\u03e2\u03e3\7q\2\2\u03e3\u03e4")NEWLINE buf.write("\7p\2\2\u03e4\u03e5\7u\2\2\u03e5\u008a\3\2\2\2\u03e6\u03e7")NEWLINE buf.write("\7u\2\2\u03e7\u03e8\7g\2\2\u03e8\u03e9\7v\2\2\u03e9\u03ea")NEWLINE buf.write("\7/\2\2\u03ea\u03eb\7k\2\2\u03eb\u03ec\7p\2\2\u03ec\u03ed")NEWLINE buf.write("\7h\2\2\u03ed\u03ee\7q\2\2\u03ee\u008c\3\2\2\2\u03ef\u03f0")NEWLINE buf.write("\7u\2\2\u03f0\u03f1\7g\2\2\u03f1\u03f2\7v\2\2\u03f2\u03f3")NEWLINE buf.write("\7/\2\2\u03f3\u03f4\7n\2\2\u03f4\u03f5\7q\2\2\u03f5\u03f6")NEWLINE buf.write("\7i\2\2\u03f6\u03f7\7k\2\2\u03f7\u03f8\7e\2\2\u03f8\u008e")NEWLINE buf.write("\3\2\2\2\u03f9\u03fa\7u\2\2\u03fa\u03fb\7g\2\2\u03fb\u03fc")NEWLINE buf.write("\7v\2\2\u03fc\u03fd\7/\2\2\u03fd\u03fe\7q\2\2\u03fe\u03ff")NEWLINE buf.write("\7r\2\2\u03ff\u0400\7v\2\2\u0400\u0401\7k\2\2\u0401\u0402")NEWLINE buf.write("\7q\2\2\u0402\u0403\7p\2\2\u0403\u0090\3\2\2\2\u0404\u0405")NEWLINE buf.write("\7v\2\2\u0405\u0406\7j\2\2\u0406\u0407\7g\2\2\u0407\u0408")NEWLINE buf.write("\7p\2\2\u0408\u0092\3\2\2\2\u0409\u040a\7c\2\2\u040a\u040b")NEWLINE buf.write("\7p\2\2\u040b\u040c\7f\2\2\u040c\u040d\7/\2\2\u040d\u040e")NEWLINE buf.write("\7v\2\2\u040e\u040f\7j\2\2\u040f\u0410\7g\2\2\u0410\u0411")NEWLINE buf.write("\7p\2\2\u0411\u0094\3\2\2\2\u0412\u0413\7r\2\2\u0413\u0414")NEWLINE buf.write("\7c\2\2\u0414\u0415\7t\2\2\u0415\u0416\7/\2\2\u0416\u0417")NEWLINE buf.write("\7v\2\2\u0417\u0418\7j\2\2\u0418\u0419\7g\2\2\u0419\u041a")NEWLINE buf.write("\7p\2\2\u041a\u0096\3\2\2\2\u041b\u041c\7q\2\2\u041c\u041d")NEWLINE buf.write("\7t\2\2\u041d\u041e\7/\2\2\u041e\u041f\7g\2\2\u041f\u0420")NEWLINE buf.write("\7n\2\2\u0420\u0421\7u\2\2\u0421\u0422\7g\2\2\u0422\u0098")NEWLINE buf.write("\3\2\2\2\u0423\u0424\7r\2\2\u0424\u0425\7c\2\2\u0425\u0426")NEWLINE buf.write("\7t\2\2\u0426\u0427\7/\2\2\u0427\u0428\7q\2\2\u0428\u0429")NEWLINE buf.write("\7t\2\2\u0429\u042a\7/\2\2\u042a\u042b\7g\2\2\u042b\u042c")NEWLINE buf.write("\7n\2\2\u042c\u042d\7u\2\2\u042d\u042e\7g\2\2\u042e\u009a")NEWLINE buf.write("\3\2\2\2\u042f\u0430\7r\2\2\u0430\u0431\7c\2\2\u0431\u0432")NEWLINE buf.write("\7t\2\2\u0432\u0433\7/\2\2\u0433\u0434\7q\2\2\u0434\u0435")NEWLINE buf.write("\7t\2\2\u0435\u009c\3\2\2\2\u0436\u0437\7v\2\2\u0437\u0438")NEWLINE buf.write("\7t\2\2\u0438\u0439\7{\2\2\u0439\u043a\7/\2\2\u043a\u043b")NEWLINE buf.write("\7h\2\2\u043b\u043c\7q\2\2\u043c\u043d\7t\2\2\u043d\u009e")NEWLINE buf.write("\3\2\2\2\u043e\u043f\7w\2\2\u043f\u0440\7u\2\2\u0440\u0441")NEWLINE buf.write("\7k\2\2\u0441\u0442\7p\2\2\u0442\u0443\7i\2\2\u0443\u0444")NEWLINE buf.write("\7/\2\2\u0444\u0445\7r\2\2\u0445\u0446\7c\2\2\u0446\u0447")NEWLINE buf.write("\7t\2\2\u0447\u0448\7c\2\2\u0448\u0449\7o\2\2\u0449\u044a")NEWLINE buf.write("\7u\2\2\u044a\u00a0\3\2\2\2\u044b\u044c\7#\2\2\u044c\u00a2")NEWLINE buf.write("\3\2\2\2\u044d\u044e\7a\2\2\u044e\u00a4\3\2\2\2\u044f")NEWLINE buf.write("\u0450\7c\2\2\u0450\u0451\7u\2\2\u0451\u00a6\3\2\2\2\u0452")NEWLINE buf.write("\u0453\7D\2\2\u0453\u0454\7K\2\2\u0454\u0455\7P\2\2\u0455")NEWLINE buf.write("\u0456\7C\2\2\u0456\u0457\7T\2\2\u0457\u0458\7[\2\2\u0458")NEWLINE buf.write("\u00a8\3\2\2\2\u0459\u045a\7F\2\2\u045a\u045b\7G\2\2\u045b")NEWLINE buf.write("\u045c\7E\2\2\u045c\u045d\7K\2\2\u045d\u045e\7O\2\2\u045e")NEWLINE buf.write("\u045f\7C\2\2\u045f\u0460\7N\2\2\u0460\u00aa\3\2\2\2\u0461")NEWLINE buf.write("\u0462\7g\2\2\u0462\u0463\7z\2\2\u0463\u0464\7k\2\2\u0464")NEWLINE buf.write("\u0465\7u\2\2\u0465\u0466\7v\2\2\u0466\u0467\7u\2\2\u0467")NEWLINE buf.write("\u00ac\3\2\2\2\u0468\u0469\7J\2\2\u0469\u046a\7G\2\2\u046a")NEWLINE buf.write("\u046b\7Z\2\2\u046b\u046c\7C\2\2\u046c\u046d\7F\2\2\u046d")NEWLINE buf.write("\u046e\7G\2\2\u046e\u046f\7E\2\2\u046f\u0470\7K\2\2\u0470")NEWLINE buf.write("\u0471\7O\2\2\u0471\u0472\7C\2\2\u0472\u0473\7N\2\2\u0473")NEWLINE buf.write("\u00ae\3\2\2\2\u0474\u0475\7h\2\2\u0475\u0476\7q\2\2\u0476")NEWLINE buf.write("\u0477\7t\2\2\u0477\u0478\7c\2\2\u0478\u0479\7n\2\2\u0479")NEWLINE buf.write("\u047a\7n\2\2\u047a\u00b0\3\2\2\2\u047b\u047c\7n\2\2\u047c")NEWLINE buf.write("\u047d\7g\2\2\u047d\u047e\7v\2\2\u047e\u00b2\3\2\2\2\u047f")NEWLINE buf.write("\u0480\7o\2\2\u0480\u0481\7c\2\2\u0481\u0482\7v\2\2\u0482")NEWLINE buf.write("\u0483\7e\2\2\u0483\u0484\7j\2\2\u0484\u00b4\3\2\2\2\u0485")NEWLINE buf.write("\u0486\7P\2\2\u0486\u0487\7W\2\2\u0487\u0488\7O\2\2\u0488")NEWLINE buf.write("\u0489\7G\2\2\u0489\u048a\7T\2\2\u048a\u048b\7C\2\2\u048b")NEWLINE buf.write("\u048c\7N\2\2\u048c\u00b6\3\2\2\2\u048d\u048e\7r\2\2\u048e")NEWLINE buf.write("\u048f\7c\2\2\u048f\u0490\7t\2\2\u0490\u00b8\3\2\2\2\u0491")NEWLINE buf.write("\u049a\7\62\2\2\u0492\u0496\t\3\2\2\u0493\u0495\5\u00c5")NEWLINE buf.write("c\2\u0494\u0493\3\2\2\2\u0495\u0498\3\2\2\2\u0496\u0494")NEWLINE buf.write("\3\2\2\2\u0496\u0497\3\2\2\2\u0497\u049a\3\2\2\2\u0498")NEWLINE buf.write("\u0496\3\2\2\2\u0499\u0491\3\2\2\2\u0499\u0492\3\2\2\2")NEWLINE buf.write("\u049a\u00ba\3\2\2\2\u049b\u049c\7%\2\2\u049c\u049d\7")NEWLINE buf.write("d\2\2\u049d\u049f\3\2\2\2\u049e\u04a0\5\u00c9e\2\u049f")NEWLINE buf.write("\u049e\3\2\2\2\u04a0\u04a1\3\2\2\2\u04a1\u049f\3\2\2\2")NEWLINE buf.write("\u04a1\u04a2\3\2\2\2\u04a2\u00bc\3\2\2\2\u04a3\u04a4\7")NEWLINE buf.write("%\2\2\u04a4\u04a5\7z\2\2\u04a5\u04a7\3\2\2\2\u04a6\u04a8")NEWLINE buf.write("\5\u00c1a\2\u04a7\u04a6\3\2\2\2\u04a8\u04a9\3\2\2\2\u04a9")NEWLINE buf.write("\u04a7\3\2\2\2\u04a9\u04aa\3\2\2\2\u04aa\u00be\3\2\2\2")NEWLINE buf.write("\u04ab\u04ac\5\u00b9]\2\u04ac\u04b0\7\60\2\2\u04ad\u04af")NEWLINE buf.write("\7\62\2\2\u04ae\u04ad\3\2\2\2\u04af\u04b2\3\2\2\2\u04b0")NEWLINE buf.write("\u04ae\3\2\2\2\u04b0\u04b1\3\2\2\2\u04b1\u04b3\3\2\2\2")NEWLINE buf.write("\u04b2\u04b0\3\2\2\2\u04b3\u04b4\5\u00b9]\2\u04b4\u00c0")NEWLINE buf.write("\3\2\2\2\u04b5\u04b6\t\4\2\2\u04b6\u00c2\3\2\2\2\u04b7")NEWLINE buf.write("\u04b8\7<\2\2\u04b8\u00c4\3\2\2\2\u04b9\u04ba\t\5\2\2")NEWLINE buf.write("\u04ba\u00c6\3\2\2\2\u04bb\u04bc\t\6\2\2\u04bc\u00c8\3")NEWLINE buf.write("\2\2\2\u04bd\u04be\t\7\2\2\u04be\u00ca\3\2\2\2\u04bf\u04c2")NEWLINE buf.write("\t\b\2\2\u04c0\u04c2\5\u00d1i\2\u04c1\u04bf\3\2\2\2\u04c1")NEWLINE buf.write("\u04c0\3\2\2\2\u04c2\u00cc\3\2\2\2\u04c3\u04c6\t\t\2\2")NEWLINE buf.write("\u04c4\u04c6\5\u00d1i\2\u04c5\u04c3\3\2\2\2\u04c5\u04c4")NEWLINE buf.write("\3\2\2\2\u04c6\u00ce\3\2\2\2\u04c7\u04ca\t\n\2\2\u04c8")NEWLINE buf.write("\u04ca\5\u00d1i\2\u04c9\u04c7\3\2\2\2\u04c9\u04c8\3\2")NEWLINE buf.write("\2\2\u04ca\u00d0\3\2\2\2\u04cb\u04cc\7$\2\2\u04cc\u04cd")NEWLINE buf.write("\7$\2\2\u04cd\u00d2\3\2\2\2\u04ce\u04cf\t\13\2\2\u04cf")NEWLINE buf.write("\u00d4\3\2\2\2\u04d0\u04d1\7<\2\2\u04d1\u04d2\7c\2\2\u04d2")NEWLINE buf.write("\u04d3\7n\2\2\u04d3\u04d4\7n\2\2\u04d4\u04d5\7/\2\2\u04d5")NEWLINE buf.write("\u04d6\7u\2\2\u04d6\u04d7\7v\2\2\u04d7\u04d8\7c\2\2\u04d8")NEWLINE buf.write("\u04d9\7v\2\2\u04d9\u04da\7k\2\2\u04da\u04db\7u\2\2\u04db")NEWLINE buf.write("\u04dc\7v\2\2\u04dc\u04dd\7k\2\2\u04dd\u04de\7e\2\2\u04de")NEWLINE buf.write("\u04df\7u\2\2\u04df\u00d6\3\2\2\2\u04e0\u04e1\7<\2\2\u04e1")NEWLINE buf.write("\u04e2\7c\2\2\u04e2\u04e3\7u\2\2\u04e3\u04e4\7u\2\2\u04e4")NEWLINE buf.write("\u04e5\7g\2\2\u04e5\u04e6\7t\2\2\u04e6\u04e7\7v\2\2\u04e7")NEWLINE buf.write("\u04e8\7k\2\2\u04e8\u04e9\7q\2\2\u04e9\u04ea\7p\2\2\u04ea")NEWLINE buf.write("\u04eb\7/\2\2\u04eb\u04ec\7u\2\2\u04ec\u04ed\7v\2\2\u04ed")NEWLINE buf.write("\u04ee\7c\2\2\u04ee\u04ef\7e\2\2\u04ef\u04f0\7m\2\2\u04f0")NEWLINE buf.write("\u04f1\7/\2\2\u04f1\u04f2\7n\2\2\u04f2\u04f3\7g\2\2\u04f3")NEWLINE buf.write("\u04f4\7x\2\2\u04f4\u04f5\7g\2\2\u04f5\u04f6\7n\2\2\u04f6")NEWLINE buf.write("\u04f7\7u\2\2\u04f7\u00d8\3\2\2\2\u04f8\u04f9\7<\2\2\u04f9")NEWLINE buf.write("\u04fa\7c\2\2\u04fa\u04fb\7w\2\2\u04fb\u04fc\7v\2\2\u04fc")NEWLINE buf.write("\u04fd\7j\2\2\u04fd\u04fe\7q\2\2\u04fe\u04ff\7t\2\2\u04ff")NEWLINE buf.write("\u0500\7u\2\2\u0500\u00da\3\2\2\2\u0501\u0502\7<\2\2\u0502")NEWLINE buf.write("\u0503\7e\2\2\u0503\u0504\7c\2\2\u0504\u0505\7v\2\2\u0505")NEWLINE buf.write("\u0506\7g\2\2\u0506\u0507\7i\2\2\u0507\u0508\7q\2\2\u0508")NEWLINE buf.write("\u0509\7t\2\2\u0509\u050a\7{\2\2\u050a\u00dc\3\2\2\2\u050b")NEWLINE buf.write("\u050c\7<\2\2\u050c\u050d\7e\2\2\u050d\u050e\7j\2\2\u050e")NEWLINE buf.write("\u050f\7c\2\2\u050f\u0510\7k\2\2\u0510\u0511\7p\2\2\u0511")NEWLINE buf.write("\u0512\7c\2\2\u0512\u0513\7d\2\2\u0513\u0514\7n\2\2\u0514")NEWLINE buf.write("\u0515\7g\2\2\u0515\u00de\3\2\2\2\u0516\u0517\7<\2\2\u0517")NEWLINE buf.write("\u0518\7f\2\2\u0518\u0519\7g\2\2\u0519\u051a\7h\2\2\u051a")NEWLINE buf.write("\u051b\7k\2\2\u051b\u051c\7p\2\2\u051c\u051d\7k\2\2\u051d")NEWLINE buf.write("\u051e\7v\2\2\u051e\u051f\7k\2\2\u051f\u0520\7q\2\2\u0520")NEWLINE buf.write("\u0521\7p\2\2\u0521\u00e0\3\2\2\2\u0522\u0523\7<\2\2\u0523")NEWLINE buf.write("\u0524\7f\2\2\u0524\u0525\7k\2\2\u0525\u0526\7c\2\2\u0526")NEWLINE buf.write("\u0527\7i\2\2\u0527\u0528\7p\2\2\u0528\u0529\7q\2\2\u0529")NEWLINE buf.write("\u052a\7u\2\2\u052a\u052b\7v\2\2\u052b\u052c\7k\2\2\u052c")NEWLINE buf.write("\u052d\7e\2\2\u052d\u052e\7/\2\2\u052e\u052f\7q\2\2\u052f")NEWLINE buf.write("\u0530\7w\2\2\u0530\u0531\7v\2\2\u0531\u0532\7r\2\2\u0532")NEWLINE buf.write("\u0533\7w\2\2\u0533\u0534\7v\2\2\u0534\u0535\7/\2\2\u0535")NEWLINE buf.write("\u0536\7e\2\2\u0536\u0537\7j\2\2\u0537\u0538\7c\2\2\u0538")NEWLINE buf.write("\u0539\7p\2\2\u0539\u053a\7p\2\2\u053a\u053b\7g\2\2\u053b")NEWLINE buf.write("\u053c\7n\2\2\u053c\u00e2\3\2\2\2\u053d\u053e\7<\2\2\u053e")NEWLINE buf.write("\u053f\7g\2\2\u053f\u0540\7t\2\2\u0540\u0541\7t\2\2\u0541")NEWLINE buf.write("\u0542\7q\2\2\u0542\u0543\7t\2\2\u0543\u0544\7/\2\2\u0544")NEWLINE buf.write("\u0545\7d\2\2\u0545\u0546\7g\2\2\u0546\u0547\7j\2\2\u0547")NEWLINE buf.write("\u0548\7c\2\2\u0548\u0549\7x\2\2\u0549\u054a\7k\2\2\u054a")NEWLINE buf.write("\u054b\7q\2\2\u054b\u054c\7t\2\2\u054c\u00e4\3\2\2\2\u054d")NEWLINE buf.write("\u054e\7<\2\2\u054e\u054f\7g\2\2\u054f\u0550\7z\2\2\u0550")NEWLINE buf.write("\u0551\7v\2\2\u0551\u0552\7g\2\2\u0552\u0553\7p\2\2\u0553")NEWLINE buf.write("\u0554\7u\2\2\u0554\u0555\7k\2\2\u0555\u0556\7q\2\2\u0556")NEWLINE buf.write("\u0557\7p\2\2\u0557\u0558\7u\2\2\u0558\u00e6\3\2\2\2\u0559")NEWLINE buf.write("\u055a\7<\2\2\u055a\u055b\7h\2\2\u055b\u055c\7w\2\2\u055c")NEWLINE buf.write("\u055d\7p\2\2\u055d\u055e\7u\2\2\u055e\u00e8\3\2\2\2\u055f")NEWLINE buf.write("\u0560\7<\2\2\u0560\u0561\7h\2\2\u0561\u0562\7w\2\2\u0562")NEWLINE buf.write("\u0563\7p\2\2\u0563\u0564\7u\2\2\u0564\u0565\7/\2\2\u0565")NEWLINE buf.write("\u0566\7f\2\2\u0566\u0567\7g\2\2\u0567\u0568\7u\2\2\u0568")NEWLINE buf.write("\u0569\7e\2\2\u0569\u056a\7t\2\2\u056a\u056b\7k\2\2\u056b")NEWLINE buf.write("\u056c\7r\2\2\u056c\u056d\7v\2\2\u056d\u056e\7k\2\2\u056e")NEWLINE buf.write("\u056f\7q\2\2\u056f\u0570\7p\2\2\u0570\u00ea\3\2\2\2\u0571")NEWLINE buf.write("\u0572\7<\2\2\u0572\u0573\7i\2\2\u0573\u0574\7n\2\2\u0574")NEWLINE buf.write("\u0575\7q\2\2\u0575\u0576\7d\2\2\u0576\u0577\7c\2\2\u0577")NEWLINE buf.write("\u0578\7n\2\2\u0578\u0579\7/\2\2\u0579\u057a\7f\2\2\u057a")NEWLINE buf.write("\u057b\7g\2\2\u057b\u057c\7e\2\2\u057c\u057d\7n\2\2\u057d")NEWLINE buf.write("\u057e\7c\2\2\u057e\u057f\7t\2\2\u057f\u0580\7c\2\2\u0580")NEWLINE buf.write("\u0581\7v\2\2\u0581\u0582\7k\2\2\u0582\u0583\7q\2\2\u0583")NEWLINE buf.write("\u0584\7p\2\2\u0584\u0585\7u\2\2\u0585\u00ec\3\2\2\2\u0586")NEWLINE buf.write("\u0587\7<\2\2\u0587\u0588\7k\2\2\u0588\u0589\7p\2\2\u0589")NEWLINE buf.write("\u058a\7v\2\2\u058a\u058b\7g\2\2\u058b\u058c\7t\2\2\u058c")NEWLINE buf.write("\u058d\7c\2\2\u058d\u058e\7e\2\2\u058e\u058f\7v\2\2\u058f")NEWLINE buf.write("\u0590\7k\2\2\u0590\u0591\7x\2\2\u0591\u0592\7g\2\2\u0592")NEWLINE buf.write("\u0593\7/\2\2\u0593\u0594\7o\2\2\u0594\u0595\7q\2\2\u0595")NEWLINE buf.write("\u0596\7f\2\2\u0596\u0597\7g\2\2\u0597\u00ee\3\2\2\2\u0598")NEWLINE buf.write("\u0599\7<\2\2\u0599\u059a\7n\2\2\u059a\u059b\7c\2\2\u059b")NEWLINE buf.write("\u059c\7p\2\2\u059c\u059d\7i\2\2\u059d\u059e\7w\2\2\u059e")NEWLINE buf.write("\u059f\7c\2\2\u059f\u05a0\7i\2\2\u05a0\u05a1\7g\2\2\u05a1")NEWLINE buf.write("\u00f0\3\2\2\2\u05a2\u05a3\7<\2\2\u05a3\u05a4\7n\2\2\u05a4")NEWLINE buf.write("\u05a5\7g\2\2\u05a5\u05a6\7h\2\2\u05a6\u05a7\7v\2\2\u05a7")NEWLINE buf.write("\u05a8\7/\2\2\u05a8\u05a9\7c\2\2\u05a9\u05aa\7u\2\2\u05aa")NEWLINE buf.write("\u05ab\7u\2\2\u05ab\u05ac\7q\2\2\u05ac\u05ad\7e\2\2\u05ad")NEWLINE buf.write("\u00f2\3\2\2\2\u05ae\u05af\7<\2\2\u05af\u05b0\7n\2\2\u05b0")NEWLINE buf.write("\u05b1\7k\2\2\u05b1\u05b2\7e\2\2\u05b2\u05b3\7g\2\2\u05b3")NEWLINE buf.write("\u05b4\7p\2\2\u05b4\u05b5\7u\2\2\u05b5\u05b6\7g\2\2\u05b6")NEWLINE buf.write("\u00f4\3\2\2\2\u05b7\u05b8\7<\2\2\u05b8\u05b9\7p\2\2\u05b9")NEWLINE buf.write("\u05ba\7c\2\2\u05ba\u05bb\7o\2\2\u05bb\u05bc\7g\2\2\u05bc")NEWLINE buf.write("\u05bd\7f\2\2\u05bd\u00f6\3\2\2\2\u05be\u05bf\7<\2\2\u05bf")NEWLINE buf.write("\u05c0\7p\2\2\u05c0\u05c1\7c\2\2\u05c1\u05c2\7o\2\2\u05c2")NEWLINE buf.write("\u05c3\7g\2\2\u05c3\u00f8\3\2\2\2\u05c4\u05c5\7<\2\2\u05c5")NEWLINE buf.write("\u05c6\7p\2\2\u05c6\u05c7\7q\2\2\u05c7\u05c8\7v\2\2\u05c8")NEWLINE buf.write("\u05c9\7g\2\2\u05c9\u05ca\7u\2\2\u05ca\u00fa\3\2\2\2\u05cb")NEWLINE buf.write("\u05cc\7<\2\2\u05cc\u05cd\7r\2\2\u05cd\u05ce\7c\2\2\u05ce")NEWLINE buf.write("\u05cf\7v\2\2\u05cf\u05d0\7v\2\2\u05d0\u05d1\7g\2\2\u05d1")NEWLINE buf.write("\u05d2\7t\2\2\u05d2\u05d3\7p\2\2\u05d3\u00fc\3\2\2\2\u05d4")NEWLINE buf.write("\u05d5\7<\2\2\u05d5\u05d6\7r\2\2\u05d6\u05d7\7t\2\2\u05d7")NEWLINE buf.write("\u05d8\7k\2\2\u05d8\u05d9\7p\2\2\u05d9\u05da\7v\2\2\u05da")NEWLINE buf.write("\u05db\7/\2\2\u05db\u05dc\7u\2\2\u05dc\u05dd\7w\2\2\u05dd")NEWLINE buf.write("\u05de\7e\2\2\u05de\u05df\7e\2\2\u05df\u05e0\7g\2\2\u05e0")NEWLINE buf.write("\u05e1\7u\2\2\u05e1\u05e2\7u\2\2\u05e2\u00fe\3\2\2\2\u05e3")NEWLINE buf.write("\u05e4\7<\2\2\u05e4\u05e5\7r\2\2\u05e5\u05e6\7t\2\2\u05e6")NEWLINE buf.write("\u05e7\7q\2\2\u05e7\u05e8\7f\2\2\u05e8\u05e9\7w\2\2\u05e9")NEWLINE buf.write("\u05ea\7e\2\2\u05ea\u05eb\7g\2\2\u05eb\u05ec\7/\2\2\u05ec")NEWLINE buf.write("\u05ed\7c\2\2\u05ed\u05ee\7u\2\2\u05ee\u05ef\7u\2\2\u05ef")NEWLINE buf.write("\u05f0\7g\2\2\u05f0\u05f1\7t\2\2\u05f1\u05f2\7v\2\2\u05f2")NEWLINE buf.write("\u05f3\7k\2\2\u05f3\u05f4\7q\2\2\u05f4\u05f5\7p\2\2\u05f5")NEWLINE buf.write("\u05f6\7u\2\2\u05f6\u0100\3\2\2\2\u05f7\u05f8\7<\2\2\u05f8")NEWLINE buf.write("\u05f9\7r\2\2\u05f9\u05fa\7t\2\2\u05fa\u05fb\7q\2\2\u05fb")NEWLINE buf.write("\u05fc\7f\2\2\u05fc\u05fd\7w\2\2\u05fd\u05fe\7e\2\2\u05fe")NEWLINE buf.write("\u05ff\7g\2\2\u05ff\u0600\7/\2\2\u0600\u0601\7c\2\2\u0601")NEWLINE buf.write("\u0602\7u\2\2\u0602\u0603\7u\2\2\u0603\u0604\7k\2\2\u0604")NEWLINE buf.write("\u0605\7i\2\2\u0605\u0606\7p\2\2\u0606\u0607\7o\2\2\u0607")NEWLINE buf.write("\u0608\7g\2\2\u0608\u0609\7p\2\2\u0609\u060a\7v\2\2\u060a")NEWLINE buf.write("\u060b\7u\2\2\u060b\u0102\3\2\2\2\u060c\u060d\7<\2\2\u060d")NEWLINE buf.write("\u060e\7r\2\2\u060e\u060f\7t\2\2\u060f\u0610\7q\2\2\u0610")NEWLINE buf.write("\u0611\7f\2\2\u0611\u0612\7w\2\2\u0612\u0613\7e\2\2\u0613")NEWLINE buf.write("\u0614\7g\2\2\u0614\u0615\7/\2\2\u0615\u0616\7o\2\2\u0616")NEWLINE buf.write("\u0617\7q\2\2\u0617\u0618\7f\2\2\u0618\u0619\7g\2\2\u0619")NEWLINE buf.write("\u061a\7n\2\2\u061a\u061b\7u\2\2\u061b\u0104\3\2\2\2\u061c")NEWLINE buf.write("\u061d\7<\2\2\u061d\u061e\7r\2\2\u061e\u061f\7t\2\2\u061f")NEWLINE buf.write("\u0620\7q\2\2\u0620\u0621\7f\2\2\u0621\u0622\7w\2\2\u0622")NEWLINE buf.write("\u0623\7e\2\2\u0623\u0624\7g\2\2\u0624\u0625\7/\2\2\u0625")NEWLINE buf.write("\u0626\7r\2\2\u0626\u0627\7t\2\2\u0627\u0628\7q\2\2\u0628")NEWLINE buf.write("\u0629\7q\2\2\u0629\u062a\7h\2\2\u062a\u062b\7u\2\2\u062b")NEWLINE buf.write("\u0106\3\2\2\2\u062c\u062d\7<\2\2\u062d\u062e\7r\2\2\u062e")NEWLINE buf.write("\u062f\7t\2\2\u062f\u0630\7q\2\2\u0630\u0631\7f\2\2\u0631")NEWLINE buf.write("\u0632\7w\2\2\u0632\u0633\7e\2\2\u0633\u0634\7g\2\2\u0634")NEWLINE buf.write("\u0635\7/\2\2\u0635\u0636\7w\2\2\u0636\u0637\7p\2\2\u0637")NEWLINE buf.write("\u0638\7u\2\2\u0638\u0639\7c\2\2\u0639\u063a\7v\2\2\u063a")NEWLINE buf.write("\u063b\7/\2\2\u063b\u063c\7c\2\2\u063c\u063d\7u\2\2\u063d")NEWLINE buf.write("\u063e\7u\2\2\u063e\u063f\7w\2\2\u063f\u0640\7o\2\2\u0640")NEWLINE buf.write("\u0641\7r\2\2\u0641\u0642\7v\2\2\u0642\u0643\7k\2\2\u0643")NEWLINE buf.write("\u0644\7q\2\2\u0644\u0645\7p\2\2\u0645\u0646\7u\2\2\u0646")NEWLINE buf.write("\u0108\3\2\2\2\u0647\u0648\7<\2\2\u0648\u0649\7r\2\2\u0649")NEWLINE buf.write("\u064a\7t\2\2\u064a\u064b\7q\2\2\u064b\u064c\7f\2\2\u064c")NEWLINE buf.write("\u064d\7w\2\2\u064d\u064e\7e\2\2\u064e\u064f\7g\2\2\u064f")NEWLINE buf.write("\u0650\7/\2\2\u0650\u0651\7w\2\2\u0651\u0652\7p\2\2\u0652")NEWLINE buf.write("\u0653\7u\2\2\u0653\u0654\7c\2\2\u0654\u0655\7v\2\2\u0655")NEWLINE buf.write("\u0656\7/\2\2\u0656\u0657\7e\2\2\u0657\u0658\7q\2\2\u0658")NEWLINE buf.write("\u0659\7t\2\2\u0659\u065a\7g\2\2\u065a\u065b\7u\2\2\u065b")NEWLINE buf.write("\u010a\3\2\2\2\u065c\u065d\7<\2\2\u065d\u065e\7t\2\2\u065e")NEWLINE buf.write("\u065f\7c\2\2\u065f\u0660\7p\2\2\u0660\u0661\7f\2\2\u0661")NEWLINE buf.write("\u0662\7q\2\2\u0662\u0663\7o\2\2\u0663\u0664\7/\2\2\u0664")NEWLINE buf.write("\u0665\7u\2\2\u0665\u0666\7g\2\2\u0666\u0667\7g\2\2\u0667")NEWLINE buf.write("\u0668\7f\2\2\u0668\u010c\3\2\2\2\u0669\u066a\7<\2\2\u066a")NEWLINE buf.write("\u066b\7t\2\2\u066b\u066c\7g\2\2\u066c\u066d\7c\2\2\u066d")NEWLINE buf.write("\u066e\7u\2\2\u066e\u066f\7q\2\2\u066f\u0670\7p\2\2\u0670")NEWLINE buf.write("\u0671\7/\2\2\u0671\u0672\7w\2\2\u0672\u0673\7p\2\2\u0673")NEWLINE buf.write("\u0674\7m\2\2\u0674\u0675\7p\2\2\u0675\u0676\7q\2\2\u0676")NEWLINE buf.write("\u0677\7y\2\2\u0677\u0678\7p\2\2\u0678\u010e\3\2\2\2\u0679")NEWLINE buf.write("\u067a\7<\2\2\u067a\u067b\7t\2\2\u067b\u067c\7g\2\2\u067c")NEWLINE buf.write("\u067d\7i\2\2\u067d\u067e\7w\2\2\u067e\u067f\7n\2\2\u067f")NEWLINE buf.write("\u0680\7c\2\2\u0680\u0681\7t\2\2\u0681\u0682\7/\2\2\u0682")NEWLINE buf.write("\u0683\7q\2\2\u0683\u0684\7w\2\2\u0684\u0685\7v\2\2\u0685")NEWLINE buf.write("\u0686\7r\2\2\u0686\u0687\7w\2\2\u0687\u0688\7v\2\2\u0688")NEWLINE buf.write("\u0689\7/\2\2\u0689\u068a\7e\2\2\u068a\u068b\7j\2\2\u068b")NEWLINE buf.write("\u068c\7c\2\2\u068c\u068d\7p\2\2\u068d\u068e\7p\2\2\u068e")NEWLINE buf.write("\u068f\7g\2\2\u068f\u0690\7n\2\2\u0690\u0110\3\2\2\2\u0691")NEWLINE buf.write("\u0692\7<\2\2\u0692\u0693\7t\2\2\u0693\u0694\7g\2\2\u0694")NEWLINE buf.write("\u0695\7r\2\2\u0695\u0696\7t\2\2\u0696\u0697\7q\2\2\u0697")NEWLINE buf.write("\u0698\7f\2\2\u0698\u0699\7w\2\2\u0699\u069a\7e\2\2\u069a")NEWLINE buf.write("\u069b\7k\2\2\u069b\u069c\7d\2\2\u069c\u069d\7n\2\2\u069d")NEWLINE buf.write("\u069e\7g\2\2\u069e\u069f\7/\2\2\u069f\u06a0\7t\2\2\u06a0")NEWLINE buf.write("\u06a1\7g\2\2\u06a1\u06a2\7u\2\2\u06a2\u06a3\7q\2\2\u06a3")NEWLINE buf.write("\u06a4\7w\2\2\u06a4\u06a5\7t\2\2\u06a5\u06a6\7e\2\2\u06a6")NEWLINE buf.write("\u06a7\7g\2\2\u06a7\u06a8\7/\2\2\u06a8\u06a9\7n\2\2\u06a9")NEWLINE buf.write("\u06aa\7k\2\2\u06aa\u06ab\7o\2\2\u06ab\u06ac\7k\2\2\u06ac")NEWLINE buf.write("\u06ad\7v\2\2\u06ad\u0112\3\2\2\2\u06ae\u06af\7<\2\2\u06af")NEWLINE buf.write("\u06b0\7t\2\2\u06b0\u06b1\7k\2\2\u06b1\u06b2\7i\2\2\u06b2")NEWLINE buf.write("\u06b3\7j\2\2\u06b3\u06b4\7v\2\2\u06b4\u06b5\7/\2\2\u06b5")NEWLINE buf.write("\u06b6\7c\2\2\u06b6\u06b7\7u\2\2\u06b7\u06b8\7u\2\2\u06b8")NEWLINE buf.write("\u06b9\7q\2\2\u06b9\u06ba\7e\2\2\u06ba\u0114\3\2\2\2\u06bb")NEWLINE buf.write("\u06bc\7<\2\2\u06bc\u06bd\7u\2\2\u06bd\u06be\7o\2\2\u06be")NEWLINE buf.write("\u06bf\7v\2\2\u06bf\u06c0\7/\2\2\u06c0\u06c1\7n\2\2\u06c1")NEWLINE buf.write("\u06c2\7k\2\2\u06c2\u06c3\7d\2\2\u06c3\u06c4\7/\2\2\u06c4")NEWLINE buf.write("\u06c5\7x\2\2\u06c5\u06c6\7g\2\2\u06c6\u06c7\7t\2\2\u06c7")NEWLINE buf.write("\u06c8\7u\2\2\u06c8\u06c9\7k\2\2\u06c9\u06ca\7q\2\2\u06ca")NEWLINE buf.write("\u06cb\7p\2\2\u06cb\u0116\3\2\2\2\u06cc\u06cd\7<\2\2\u06cd")NEWLINE buf.write("\u06ce\7u\2\2\u06ce\u06cf\7q\2\2\u06cf\u06d0\7t\2\2\u06d0")NEWLINE buf.write("\u06d1\7v\2\2\u06d1\u06d2\7u\2\2\u06d2\u0118\3\2\2\2\u06d3")NEWLINE buf.write("\u06d4\7<\2\2\u06d4\u06d5\7u\2\2\u06d5\u06d6\7q\2\2\u06d6")NEWLINE buf.write("\u06d7\7t\2\2\u06d7\u06d8\7v\2\2\u06d8\u06d9\7u\2\2\u06d9")NEWLINE buf.write("\u06da\7/\2\2\u06da\u06db\7f\2\2\u06db\u06dc\7g\2\2\u06dc")NEWLINE buf.write("\u06dd\7u\2\2\u06dd\u06de\7e\2\2\u06de\u06df\7t\2\2\u06df")NEWLINE buf.write("\u06e0\7k\2\2\u06e0\u06e1\7r\2\2\u06e1\u06e2\7v\2\2\u06e2")NEWLINE buf.write("\u06e3\7k\2\2\u06e3\u06e4\7q\2\2\u06e4\u06e5\7p\2\2\u06e5")NEWLINE buf.write("\u011a\3\2\2\2\u06e6\u06e7\7<\2\2\u06e7\u06e8\7u\2\2\u06e8")NEWLINE buf.write("\u06e9\7q\2\2\u06e9\u06ea\7w\2\2\u06ea\u06eb\7t\2\2\u06eb")NEWLINE buf.write("\u06ec\7e\2\2\u06ec\u06ed\7g\2\2\u06ed\u011c\3\2\2\2\u06ee")NEWLINE buf.write("\u06ef\7<\2\2\u06ef\u06f0\7u\2\2\u06f0\u06f1\7v\2\2\u06f1")NEWLINE buf.write("\u06f2\7c\2\2\u06f2\u06f3\7v\2\2\u06f3\u06f4\7w\2\2\u06f4")NEWLINE buf.write("\u06f5\7u\2\2\u06f5\u011e\3\2\2\2\u06f6\u06f7\7<\2\2\u06f7")NEWLINE buf.write("\u06f8\7v\2\2\u06f8\u06f9\7j\2\2\u06f9\u06fa\7g\2\2\u06fa")NEWLINE buf.write("\u06fb\7q\2\2\u06fb\u06fc\7t\2\2\u06fc\u06fd\7k\2\2\u06fd")NEWLINE buf.write("\u06fe\7g\2\2\u06fe\u06ff\7u\2\2\u06ff\u0120\3\2\2\2\u0700")NEWLINE buf.write("\u0701\7<\2\2\u0701\u0702\7x\2\2\u0702\u0703\7c\2\2\u0703")NEWLINE buf.write("\u0704\7n\2\2\u0704\u0705\7w\2\2\u0705\u0706\7g\2\2\u0706")NEWLINE buf.write("\u0707\7u\2\2\u0707\u0122\3\2\2\2\u0708\u0709\7<\2\2\u0709")NEWLINE buf.write("\u070a\7x\2\2\u070a\u070b\7g\2\2\u070b\u070c\7t\2\2\u070c")NEWLINE buf.write("\u070d\7d\2\2\u070d\u070e\7q\2\2\u070e\u070f\7u\2\2\u070f")NEWLINE buf.write("\u0710\7k\2\2\u0710\u0711\7v\2\2\u0711\u0712\7{\2\2\u0712")NEWLINE buf.write("\u0124\3\2\2\2\u0713\u0714\7<\2\2\u0714\u0715\7x\2\2\u0715")NEWLINE buf.write("\u0716\7g\2\2\u0716\u0717\7t\2\2\u0717\u0718\7u\2\2\u0718")NEWLINE buf.write("\u0719\7k\2\2\u0719\u071a\7q\2\2\u071a\u071b\7p\2\2\u071b")NEWLINE buf.write("\u0126\3\2\2\2\u071c\u0721\5\u00c7d\2\u071d\u0720\5\u00c5")NEWLINE buf.write("c\2\u071e\u0720\5\u00c7d\2\u071f\u071d\3\2\2\2\u071f\u071e")NEWLINE buf.write("\3\2\2\2\u0720\u0723\3\2\2\2\u0721\u071f\3\2\2\2\u0721")NEWLINE buf.write("\u0722\3\2\2\2\u0722\u0128\3\2\2\2\u0723\u0721\3\2\2\2")NEWLINE buf.write("\u0724\u0726\t\13\2\2\u0725\u0724\3\2\2\2\u0726\u0727")NEWLINE buf.write("\3\2\2\2\u0727\u0725\3\2\2\2\u0727\u0728\3\2\2\2\u0728")NEWLINE buf.write("\u0729\3\2\2\2\u0729\u072a\b\u0095\2\2\u072a\u012a\3\2")NEWLINE buf.write("\2\2\24\2\u0133\u0141\u0143\u014b\u014d\u0169\u0496\u0499")NEWLINE buf.write("\u04a1\u04a9\u04b0\u04c1\u04c5\u04c9\u071f\u0721\u0727")NEWLINE buf.write("\3\b\2\2")NEWLINE return buf.getvalue()NEWLINENEWLINENEWLINEclass SMTLIBv2Lexer(Lexer):NEWLINENEWLINE atn = ATNDeserializer().deserialize(serializedATN())NEWLINENEWLINE decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]NEWLINENEWLINE T__0 = 1NEWLINE Comment = 2NEWLINE ParOpen = 3NEWLINE ParClose = 4NEWLINE Semicolon = 5NEWLINE String = 6NEWLINE QuotedSymbol = 7NEWLINE RegConst = 8NEWLINE PS_Not = 9NEWLINE PS_Bool = 10NEWLINE PS_Int = 11NEWLINE PS_Real = 12NEWLINE PS_ContinuedExecution = 13NEWLINE PS_Error = 14NEWLINE PS_False = 15NEWLINE PS_ImmediateExit = 16NEWLINE PS_Incomplete = 17NEWLINE PS_Logic = 18NEWLINE PS_Memout = 19NEWLINE PS_Sat = 20NEWLINE PS_Success = 21NEWLINE PS_Theory = 22NEWLINE PS_True = 23NEWLINE PS_Unknown = 24NEWLINE PS_Unsupported = 25NEWLINE PS_Unsat = 26NEWLINE CMD_Assert = 27NEWLINE CMD_AssertSoft = 28NEWLINE Simplify = 29NEWLINE CMD_CheckSat = 30NEWLINE CMD_CheckSatAssuming = 31NEWLINE CMD_CheckSatUsing = 32NEWLINE CMD_Labels = 33NEWLINE CMD_Minimize = 34NEWLINE CMD_Maximize = 35NEWLINE CMD_DeclareConst = 36NEWLINE CMD_DeclareDatatype = 37NEWLINE CMD_DeclareCodatatype = 38NEWLINE CMD_DeclareDatatypes = 39NEWLINE CMD_DeclareCodatatypes = 40NEWLINE CMD_DeclareFun = 41NEWLINE CMD_DeclareSort = 42NEWLINE CMD_Define = 43NEWLINE CMD_DefineFun = 44NEWLINE CMD_DefineConst = 45NEWLINE CMD_DefineFunRec = 46NEWLINE CMD_DefineFunsRec = 47NEWLINE CMD_DefineSort = 48NEWLINE CMD_Display = 49NEWLINE CMD_Echo = 50NEWLINE CMD_Eval = 51NEWLINE CMD_Exit = 52NEWLINE CMD_GetObjectives = 53NEWLINE CMD_GetAssertions = 54NEWLINE CMD_GetAssignment = 55NEWLINE CMD_GetInfo = 56NEWLINE CMD_GetModel = 57NEWLINE CMD_BlockModel = 58NEWLINE CMD_GetOption = 59NEWLINE CMD_PolyFactor = 60NEWLINE CMD_GetProof = 61NEWLINE CMD_GetUnsatAssumptions = 62NEWLINE CMD_GetUnsatCore = 63NEWLINE CMD_GetValue = 64NEWLINE CMD_Pop = 65NEWLINE CMD_Push = 66NEWLINE CMD_Reset = 67NEWLINE CMD_ResetAssertions = 68NEWLINE CMD_SetInfo = 69NEWLINE CMD_SetLogic = 70NEWLINE CMD_SetOption = 71NEWLINE TAC_Then = 72NEWLINE TAC_AndThen = 73NEWLINE TAC_ParThen = 74NEWLINE TAC_OrElse = 75NEWLINE TAC_ParOrElse = 76NEWLINE TAC_ParOr = 77NEWLINE TAC_TryFor = 78NEWLINE TAC_UsingParams = 79NEWLINE GRW_Exclamation = 80NEWLINE GRW_Underscore = 81NEWLINE GRW_As = 82NEWLINE GRW_Binary = 83NEWLINE GRW_Decimal = 84NEWLINE GRW_Exists = 85NEWLINE GRW_Hexadecimal = 86NEWLINE GRW_Forall = 87NEWLINE GRW_Let = 88NEWLINE GRW_Match = 89NEWLINE GRW_Numeral = 90NEWLINE GRW_Par = 91NEWLINE Numeral = 92NEWLINE Binary = 93NEWLINE HexDecimal = 94NEWLINE Decimal = 95NEWLINE Colon = 96NEWLINE PK_AllStatistics = 97NEWLINE PK_AssertionStackLevels = 98NEWLINE PK_Authors = 99NEWLINE PK_Category = 100NEWLINE PK_Chainable = 101NEWLINE PK_Definition = 102NEWLINE PK_DiagnosticOutputChannel = 103NEWLINE PK_ErrorBehaviour = 104NEWLINE PK_Extension = 105NEWLINE PK_Funs = 106NEWLINE PK_FunsDescription = 107NEWLINE PK_GlobalDeclarations = 108NEWLINE PK_InteractiveMode = 109NEWLINE PK_Language = 110NEWLINE PK_LeftAssoc = 111NEWLINE PK_License = 112NEWLINE PK_Named = 113NEWLINE PK_Name = 114NEWLINE PK_Notes = 115NEWLINE PK_Pattern = 116NEWLINE PK_PrintSuccess = 117NEWLINE PK_ProduceAssertions = 118NEWLINE PK_ProduceAssignments = 119NEWLINE PK_ProduceModels = 120NEWLINE PK_ProduceProofs = 121NEWLINE PK_ProduceUnsatAssumptions = 122NEWLINE PK_ProduceUnsatCores = 123NEWLINE PK_RandomSeed = 124NEWLINE PK_ReasonUnknown = 125NEWLINE PK_RegularOutputChannel = 126NEWLINE PK_ReproducibleResourceLimit = 127NEWLINE PK_RightAssoc = 128NEWLINE PK_SmtLibVersion = 129NEWLINE PK_Sorts = 130NEWLINE PK_SortsDescription = 131NEWLINE PK_Source = 132NEWLINE PK_Status = 133NEWLINE PK_Theories = 134NEWLINE PK_Values = 135NEWLINE PK_Verbosity = 136NEWLINE PK_Version = 137NEWLINE UndefinedSymbol = 138NEWLINE WS = 139NEWLINENEWLINE channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]NEWLINENEWLINE modeNames = [ "DEFAULT_MODE" ]NEWLINENEWLINE literalNames = [ "<INVALID>",NEWLINE "' bv'", "'('", "')'", "';'", "'not'", "'Bool'", "'Int'", "'Real'", NEWLINE "'continued-execution'", "'error'", "'false'", "'immediate-exit'", NEWLINE "'incomplete'", "'logic'", "'memout'", "'sat'", "'success'", NEWLINE "'theory'", "'true'", "'unknown'", "'unsupported'", "'unsat'", NEWLINE "'assert'", "'assert-soft'", "'simplify'", "'check-sat'", "'check-sat-assuming'", NEWLINE "'check-sat-using'", "'labels'", "'minimize'", "'maximize'", NEWLINE "'declare-const'", "'declare-datatype'", "'declare-codatatype'", NEWLINE "'declare-datatypes'", "'declare-codatatypes'", "'declare-fun'", NEWLINE "'declare-sort'", "'define'", "'define-fun'", "'define-const'", NEWLINE "'define-fun-rec'", "'define-funs-rec'", "'define-sort'", "'display'", NEWLINE "'echo'", "'eval'", "'exit'", "'get-objectives'", "'get-assertions'", NEWLINE "'get-assignment'", "'get-info'", "'get-model'", "'block-model'", NEWLINE "'get-option'", "'poly/factor'", "'get-proof'", "'get-unsat-assumptions'", NEWLINE "'get-unsat-core'", "'get-value'", "'pop'", "'push'", "'reset'", NEWLINE "'reset-assertions'", "'set-info'", "'set-logic'", "'set-option'", NEWLINE "'then'", "'and-then'", "'par-then'", "'or-else'", "'par-or-else'", NEWLINE "'par-or'", "'try-for'", "'using-params'", "'!'", "'_'", "'as'", NEWLINE "'BINARY'", "'DECIMAL'", "'exists'", "'HEXADECIMAL'", "'forall'", NEWLINE "'let'", "'match'", "'NUMERAL'", "'par'", "':'", "':all-statistics'", NEWLINE "':assertion-stack-levels'", "':authors'", "':category'", "':chainable'", NEWLINE "':definition'", "':diagnostic-output-channel'", "':error-behavior'", NEWLINE "':extensions'", "':funs'", "':funs-description'", "':global-declarations'", NEWLINE "':interactive-mode'", "':language'", "':left-assoc'", "':license'", NEWLINE "':named'", "':name'", "':notes'", "':pattern'", "':print-success'", NEWLINE "':produce-assertions'", "':produce-assignments'", "':produce-models'", NEWLINE "':produce-proofs'", "':produce-unsat-assumptions'", "':produce-unsat-cores'", NEWLINE "':random-seed'", "':reason-unknown'", "':regular-output-channel'", NEWLINE "':reproducible-resource-limit'", "':right-assoc'", "':smt-lib-version'", NEWLINE "':sorts'", "':sorts-description'", "':source'", "':status'", NEWLINE "':theories'", "':values'", "':verbosity'", "':version'" ]NEWLINENEWLINE symbolicNames = [ "<INVALID>",NEWLINE "Comment", "ParOpen", "ParClose", "Semicolon", "String", "QuotedSymbol", NEWLINE "RegConst", "PS_Not", "PS_Bool", "PS_Int", "PS_Real", "PS_ContinuedExecution", NEWLINE "PS_Error", "PS_False", "PS_ImmediateExit", "PS_Incomplete", NEWLINE "PS_Logic", "PS_Memout", "PS_Sat", "PS_Success", "PS_Theory", NEWLINE "PS_True", "PS_Unknown", "PS_Unsupported", "PS_Unsat", "CMD_Assert", NEWLINE "CMD_AssertSoft", "Simplify", "CMD_CheckSat", "CMD_CheckSatAssuming", NEWLINE "CMD_CheckSatUsing", "CMD_Labels", "CMD_Minimize", "CMD_Maximize", NEWLINE "CMD_DeclareConst", "CMD_DeclareDatatype", "CMD_DeclareCodatatype", NEWLINE "CMD_DeclareDatatypes", "CMD_DeclareCodatatypes", "CMD_DeclareFun", NEWLINE "CMD_DeclareSort", "CMD_Define", "CMD_DefineFun", "CMD_DefineConst", NEWLINE "CMD_DefineFunRec", "CMD_DefineFunsRec", "CMD_DefineSort", "CMD_Display", NEWLINE "CMD_Echo", "CMD_Eval", "CMD_Exit", "CMD_GetObjectives", "CMD_GetAssertions", NEWLINE "CMD_GetAssignment", "CMD_GetInfo", "CMD_GetModel", "CMD_BlockModel", NEWLINE "CMD_GetOption", "CMD_PolyFactor", "CMD_GetProof", "CMD_GetUnsatAssumptions", NEWLINE "CMD_GetUnsatCore", "CMD_GetValue", "CMD_Pop", "CMD_Push", "CMD_Reset", NEWLINE "CMD_ResetAssertions", "CMD_SetInfo", "CMD_SetLogic", "CMD_SetOption", NEWLINE "TAC_Then", "TAC_AndThen", "TAC_ParThen", "TAC_OrElse", "TAC_ParOrElse", NEWLINE "TAC_ParOr", "TAC_TryFor", "TAC_UsingParams", "GRW_Exclamation", NEWLINE "GRW_Underscore", "GRW_As", "GRW_Binary", "GRW_Decimal", "GRW_Exists", NEWLINE "GRW_Hexadecimal", "GRW_Forall", "GRW_Let", "GRW_Match", "GRW_Numeral", NEWLINE "GRW_Par", "Numeral", "Binary", "HexDecimal", "Decimal", "Colon", NEWLINE "PK_AllStatistics", "PK_AssertionStackLevels", "PK_Authors", NEWLINE "PK_Category", "PK_Chainable", "PK_Definition", "PK_DiagnosticOutputChannel", NEWLINE "PK_ErrorBehaviour", "PK_Extension", "PK_Funs", "PK_FunsDescription", NEWLINE "PK_GlobalDeclarations", "PK_InteractiveMode", "PK_Language", NEWLINE "PK_LeftAssoc", "PK_License", "PK_Named", "PK_Name", "PK_Notes", NEWLINE "PK_Pattern", "PK_PrintSuccess", "PK_ProduceAssertions", "PK_ProduceAssignments", NEWLINE "PK_ProduceModels", "PK_ProduceProofs", "PK_ProduceUnsatAssumptions", NEWLINE "PK_ProduceUnsatCores", "PK_RandomSeed", "PK_ReasonUnknown", NEWLINE "PK_RegularOutputChannel", "PK_ReproducibleResourceLimit", "PK_RightAssoc", NEWLINE "PK_SmtLibVersion", "PK_Sorts", "PK_SortsDescription", "PK_Source", NEWLINE "PK_Status", "PK_Theories", "PK_Values", "PK_Verbosity", "PK_Version", NEWLINE "UndefinedSymbol", "WS" ]NEWLINENEWLINE ruleNames = [ "T__0", "Comment", "ParOpen", "ParClose", "Semicolon", NEWLINE "String", "QuotedSymbol", "RegConst", "PS_Not", "PS_Bool", NEWLINE "PS_Int", "PS_Real", "PS_ContinuedExecution", "PS_Error", NEWLINE "PS_False", "PS_ImmediateExit", "PS_Incomplete", "PS_Logic", NEWLINE "PS_Memout", "PS_Sat", "PS_Success", "PS_Theory", "PS_True", NEWLINE "PS_Unknown", "PS_Unsupported", "PS_Unsat", "CMD_Assert", NEWLINE "CMD_AssertSoft", "Simplify", "CMD_CheckSat", "CMD_CheckSatAssuming", NEWLINE "CMD_CheckSatUsing", "CMD_Labels", "CMD_Minimize", "CMD_Maximize", NEWLINE "CMD_DeclareConst", "CMD_DeclareDatatype", "CMD_DeclareCodatatype", NEWLINE "CMD_DeclareDatatypes", "CMD_DeclareCodatatypes", "CMD_DeclareFun", NEWLINE "CMD_DeclareSort", "CMD_Define", "CMD_DefineFun", "CMD_DefineConst", NEWLINE "CMD_DefineFunRec", "CMD_DefineFunsRec", "CMD_DefineSort", NEWLINE "CMD_Display", "CMD_Echo", "CMD_Eval", "CMD_Exit", "CMD_GetObjectives", NEWLINE "CMD_GetAssertions", "CMD_GetAssignment", "CMD_GetInfo", NEWLINE "CMD_GetModel", "CMD_BlockModel", "CMD_GetOption", "CMD_PolyFactor", NEWLINE "CMD_GetProof", "CMD_GetUnsatAssumptions", "CMD_GetUnsatCore", NEWLINE "CMD_GetValue", "CMD_Pop", "CMD_Push", "CMD_Reset", "CMD_ResetAssertions", NEWLINE "CMD_SetInfo", "CMD_SetLogic", "CMD_SetOption", "TAC_Then", NEWLINE "TAC_AndThen", "TAC_ParThen", "TAC_OrElse", "TAC_ParOrElse", NEWLINE "TAC_ParOr", "TAC_TryFor", "TAC_UsingParams", "GRW_Exclamation", NEWLINE "GRW_Underscore", "GRW_As", "GRW_Binary", "GRW_Decimal", NEWLINE "GRW_Exists", "GRW_Hexadecimal", "GRW_Forall", "GRW_Let", NEWLINE "GRW_Match", "GRW_Numeral", "GRW_Par", "Numeral", "Binary", NEWLINE "HexDecimal", "Decimal", "HexDigit", "Colon", "Digit", NEWLINE "Sym", "BinaryDigit", "PrintableChar", "PrintableCharNoDquote", NEWLINE "PrintableCharNoBackslash", "EscapedSpace", "WhiteSpaceChar", NEWLINE "PK_AllStatistics", "PK_AssertionStackLevels", "PK_Authors", NEWLINE "PK_Category", "PK_Chainable", "PK_Definition", "PK_DiagnosticOutputChannel", NEWLINE "PK_ErrorBehaviour", "PK_Extension", "PK_Funs", "PK_FunsDescription", NEWLINE "PK_GlobalDeclarations", "PK_InteractiveMode", "PK_Language", NEWLINE "PK_LeftAssoc", "PK_License", "PK_Named", "PK_Name", "PK_Notes", NEWLINE "PK_Pattern", "PK_PrintSuccess", "PK_ProduceAssertions", NEWLINE "PK_ProduceAssignments", "PK_ProduceModels", "PK_ProduceProofs", NEWLINE "PK_ProduceUnsatAssumptions", "PK_ProduceUnsatCores", NEWLINE "PK_RandomSeed", "PK_ReasonUnknown", "PK_RegularOutputChannel", NEWLINE "PK_ReproducibleResourceLimit", "PK_RightAssoc", "PK_SmtLibVersion", NEWLINE "PK_Sorts", "PK_SortsDescription", "PK_Source", "PK_Status", NEWLINE "PK_Theories", "PK_Values", "PK_Verbosity", "PK_Version", NEWLINE "UndefinedSymbol", "WS" ]NEWLINENEWLINE grammarFileName = "SMTLIBv2.g4"NEWLINENEWLINE def __init__(self, input=None, output:TextIO = sys.stdout):NEWLINE super().__init__(input, output)NEWLINE self.checkVersion("4.9.2")NEWLINE self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())NEWLINE self._actions = NoneNEWLINE self._predicates = NoneNEWLINENEWLINENEWLINE |
"""JSON Web Encryption utilities."""NEWLINENEWLINEimport binasciiNEWLINEimport jsonNEWLINENEWLINEfrom collections import OrderedDictNEWLINEfrom typing import Any, Dict, Iterable, List, Mapping, Optional, UnionNEWLINENEWLINEfrom marshmallow import fields, Schema, ValidationErrorNEWLINENEWLINEfrom ..wallet.util import b64_to_bytes, bytes_to_b64NEWLINENEWLINEIDENT_ENC_KEY = "encrypted_key"NEWLINEIDENT_HEADER = "header"NEWLINEIDENT_PROTECTED = "protected"NEWLINEIDENT_RECIPIENTS = "recipients"NEWLINENEWLINENEWLINEdef b64url(value: Union[bytes, str]) -> str:NEWLINE """Encode a string or bytes value as unpadded base64-URL."""NEWLINE if isinstance(value, str):NEWLINE value = value.encode("utf-8")NEWLINE return bytes_to_b64(value, urlsafe=True, pad=False)NEWLINENEWLINENEWLINEdef from_b64url(value: str) -> bytes:NEWLINE """Decode an unpadded base64-URL value."""NEWLINE try:NEWLINE return b64_to_bytes(value, urlsafe=True)NEWLINE except binascii.Error:NEWLINE raise ValidationError("Error decoding base64 value")NEWLINENEWLINENEWLINEclass B64Value(fields.Str):NEWLINE """A marshmallow-compatible wrapper for base64-URL values."""NEWLINENEWLINE def _serialize(self, value, attr, obj, **kwargs) -> Optional[str]:NEWLINE if value is None:NEWLINE return NoneNEWLINE if not isinstance(value, bytes):NEWLINE return TypeError("Expected bytes")NEWLINE return b64url(value)NEWLINENEWLINE def _deserialize(self, value, attr, data, **kwargs) -> Any:NEWLINE value = super()._deserialize(value, attr, data, **kwargs)NEWLINE return from_b64url(value)NEWLINENEWLINENEWLINEclass JweSchema(Schema):NEWLINE """JWE envelope schema."""NEWLINENEWLINE protected = fields.Str(required=True)NEWLINE unprotected = fields.Dict(required=False)NEWLINE recipients = fields.List(fields.Dict(), required=False)NEWLINE ciphertext = B64Value(required=True)NEWLINE iv = B64Value(required=True)NEWLINE tag = B64Value(required=True)NEWLINE aad = B64Value(required=False)NEWLINE # flattened:NEWLINE header = fields.Dict(required=False)NEWLINE encrypted_key = B64Value(required=False)NEWLINENEWLINENEWLINEclass JweRecipientSchema(Schema):NEWLINE """JWE recipient schema."""NEWLINENEWLINE encrypted_key = B64Value(required=True)NEWLINE header = fields.Dict(many=True, required=False)NEWLINENEWLINENEWLINEclass JweRecipient:NEWLINE """A single message recipient."""NEWLINENEWLINE def __init__(self, *, encrypted_key: bytes, header: dict = None) -> "JweRecipient":NEWLINE """Initialize the JWE recipient."""NEWLINE self.encrypted_key = encrypted_keyNEWLINE self.header = header or {}NEWLINENEWLINE @classmethodNEWLINE def deserialize(cls, entry: Mapping[str, Any]) -> "JweRecipient":NEWLINE """Deserialize a JWE recipient from a mapping."""NEWLINE vals = JweRecipientSchema().load(entry)NEWLINE return cls(**vals)NEWLINENEWLINE def serialize(self) -> dict:NEWLINE """Serialize the JWE recipient to a mapping."""NEWLINE ret = OrderedDict([("encrypted_key", b64url(self.encrypted_key))])NEWLINE if self.header:NEWLINE ret["header"] = self.headerNEWLINE return retNEWLINENEWLINENEWLINEclass JweEnvelope:NEWLINE """JWE envelope instance."""NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE protected: dict = None,NEWLINE protected_b64: bytes = None,NEWLINE unprotected: dict = None,NEWLINE ciphertext: bytes = None,NEWLINE iv: bytes = None,NEWLINE tag: bytes = None,NEWLINE aad: bytes = None,NEWLINE with_protected_recipients: bool = False,NEWLINE with_flatten_recipients: bool = True,NEWLINE ):NEWLINE """Initialize a new JWE envelope instance."""NEWLINE self.protected = protectedNEWLINE self.protected_b64 = protected_b64NEWLINE self.unprotected = unprotected or OrderedDict()NEWLINE self.ciphertext = ciphertextNEWLINE self.iv = ivNEWLINE self.tag = tagNEWLINE self.aad = aadNEWLINE self.with_protected_recipients = with_protected_recipientsNEWLINE self.with_flatten_recipients = with_flatten_recipientsNEWLINE self._recipients: List[JweRecipient] = []NEWLINENEWLINE @classmethodNEWLINE def from_json(cls, message: Union[bytes, str]) -> "JweEnvelope":NEWLINE """Decode a JWE envelope from a JSON string or bytes value."""NEWLINE try:NEWLINE return cls._deserialize(JweSchema().loads(message))NEWLINE except json.JSONDecodeError:NEWLINE raise ValidationError("Invalid JWE: not JSON")NEWLINENEWLINE @classmethodNEWLINE def deserialize(cls, message: Mapping[str, Any]) -> "JweEnvelope":NEWLINE """Deserialize a JWE envelope from a mapping."""NEWLINE return cls._deserialize(JweSchema().load(message))NEWLINENEWLINE @classmethodNEWLINE def _deserialize(cls, parsed: Mapping[str, Any]) -> "JweEnvelope":NEWLINE protected_b64 = parsed[IDENT_PROTECTED]NEWLINE try:NEWLINE protected: dict = json.loads(from_b64url(protected_b64))NEWLINE except json.JSONDecodeError:NEWLINE raise ValidationError(NEWLINE "Invalid JWE: invalid JSON for protected headers"NEWLINE ) from NoneNEWLINE unprotected = parsed.get("unprotected") or dict()NEWLINE if protected.keys() & unprotected.keys():NEWLINE raise ValidationError("Invalid JWE: duplicate header")NEWLINENEWLINE encrypted_key = protected.get(IDENT_ENC_KEY) or parsed.get(IDENT_ENC_KEY)NEWLINE recipients = NoneNEWLINE protected_recipients = FalseNEWLINE flat_recipients = FalseNEWLINENEWLINE if IDENT_RECIPIENTS in protected:NEWLINE recipients = protected.pop(IDENT_RECIPIENTS)NEWLINE if IDENT_RECIPIENTS in parsed:NEWLINE raise ValidationError("Invalid JWE: duplicate recipients block")NEWLINE protected_recipients = TrueNEWLINE elif IDENT_RECIPIENTS in parsed:NEWLINE recipients = parsed[IDENT_RECIPIENTS]NEWLINENEWLINE if IDENT_ENC_KEY in protected:NEWLINE encrypted_key = from_b64url(protected.pop(IDENT_ENC_KEY))NEWLINE header = protected.pop(IDENT_HEADER) if IDENT_HEADER in protected else NoneNEWLINE protected_recipients = TrueNEWLINE elif IDENT_ENC_KEY in parsed:NEWLINE encrypted_key = parsed[IDENT_ENC_KEY]NEWLINE header = parsed.get(IDENT_HEADER)NEWLINENEWLINE if recipients:NEWLINE if encrypted_key:NEWLINE raise ValidationError("Invalid JWE: flattened form with 'recipients'")NEWLINE recipients = [JweRecipient.deserialize(recip) for recip in recipients]NEWLINE elif encrypted_key:NEWLINE recipients = [NEWLINE JweRecipient(NEWLINE encrypted_key=encrypted_key,NEWLINE header=header,NEWLINE )NEWLINE ]NEWLINE flat_recipients = TrueNEWLINE else:NEWLINE raise ValidationError("Invalid JWE: no recipients")NEWLINENEWLINE inst = cls(NEWLINE protected=protected,NEWLINE protected_b64=protected_b64,NEWLINE unprotected=unprotected,NEWLINE ciphertext=parsed["ciphertext"],NEWLINE iv=parsed.get("iv"),NEWLINE tag=parsed["tag"],NEWLINE aad=parsed.get("aad"),NEWLINE with_protected_recipients=protected_recipients,NEWLINE with_flatten_recipients=flat_recipients,NEWLINE )NEWLINE all_h = protected.keys() | unprotected.keys()NEWLINE for recip in recipients:NEWLINE if recip.header and recip.header.keys() & all_h:NEWLINE raise ValidationError("Invalid JWE: duplicate header")NEWLINE inst.add_recipient(recip)NEWLINENEWLINE return instNEWLINENEWLINE def serialize(self) -> dict:NEWLINE """Serialize the JWE envelope to a mapping."""NEWLINE if self.protected_b64 is None:NEWLINE raise ValidationError("Missing protected: use set_protected")NEWLINE if self.ciphertext is None:NEWLINE raise ValidationError("Missing ciphertext for JWE")NEWLINE if self.iv is None:NEWLINE raise ValidationError("Missing iv (nonce) for JWE")NEWLINE if self.tag is None:NEWLINE raise ValidationError("Missing tag for JWE")NEWLINE env = OrderedDict()NEWLINE env["protected"] = self.protected_b64NEWLINE if self.unprotected:NEWLINE env["unprotected"] = self.unprotected.copy()NEWLINE if not self.with_protected_recipients:NEWLINE recipients = self.recipients_jsonNEWLINE if self.with_flatten_recipients and len(recipients) == 1:NEWLINE for k in recipients[0]:NEWLINE env[k] = recipients[0][k]NEWLINE elif recipients:NEWLINE env[IDENT_RECIPIENTS] = recipientsNEWLINE else:NEWLINE raise ValidationError("Missing message recipients")NEWLINE env["iv"] = b64url(self.iv)NEWLINE env["ciphertext"] = b64url(self.ciphertext)NEWLINE env["tag"] = b64url(self.tag)NEWLINE if self.aad:NEWLINE env["aad"] = b64url(self.aad)NEWLINE return envNEWLINENEWLINE def to_json(self) -> str:NEWLINE """Serialize the JWE envelope to a JSON string."""NEWLINE return json.dumps(self.serialize())NEWLINENEWLINE def add_recipient(self, recip: JweRecipient):NEWLINE """Add a recipient to the JWE envelope."""NEWLINE self._recipients.append(recip)NEWLINENEWLINE def set_protected(NEWLINE self,NEWLINE protected: Mapping[str, Any],NEWLINE ):NEWLINE """Set the protected headers of the JWE envelope."""NEWLINE protected = OrderedDict(protected.items())NEWLINE if self.with_protected_recipients:NEWLINE recipients = self.recipients_jsonNEWLINE if self.with_flatten_recipients and len(recipients) == 1:NEWLINE protected.update(recipients[0])NEWLINE elif recipients:NEWLINE protected[IDENT_RECIPIENTS] = recipientsNEWLINE else:NEWLINE raise ValidationError("Missing message recipients")NEWLINE self.protected_b64 = b64url(json.dumps(protected))NEWLINENEWLINE @propertyNEWLINE def protected_bytes(self) -> bytes:NEWLINE """Access the protected data encoded as bytes.NEWLINENEWLINE This value is used in the additional authenticated data when encrypting.NEWLINE """NEWLINE return (NEWLINE self.protected_b64.encode("utf-8")NEWLINE if self.protected_b64 is not NoneNEWLINE else NoneNEWLINE )NEWLINENEWLINE def set_payload(self, ciphertext: bytes, iv: bytes, tag: bytes, aad: bytes = None):NEWLINE """Set the payload of the JWE envelope."""NEWLINE self.ciphertext = ciphertextNEWLINE self.iv = ivNEWLINE self.tag = tagNEWLINE self.aad = aadNEWLINENEWLINE @propertyNEWLINE def recipients(self) -> Iterable[JweRecipient]:NEWLINE """Accessor for an iterator over the JWE recipients.NEWLINENEWLINE The headers for each recipient include protected and unprotected headers from theNEWLINE outer envelope.NEWLINE """NEWLINE header = self.protected.copy()NEWLINE header.update(self.unprotected)NEWLINE for recip in self._recipients:NEWLINE if recip.header:NEWLINE recip_h = header.copy()NEWLINE recip_h.update(recip.header)NEWLINE yield JweRecipient(encrypted_key=recip.encrypted_key, header=recip_h)NEWLINE else:NEWLINE yield JweRecipient(encrypted_key=recip.encrypted_key, header=header)NEWLINENEWLINE @propertyNEWLINE def recipients_json(self) -> List[Dict[str, Any]]:NEWLINE """Encode the current recipients for JSON."""NEWLINE return [recip.serialize() for recip in self._recipients]NEWLINENEWLINE @propertyNEWLINE def recipient_key_ids(self) -> Iterable[JweRecipient]:NEWLINE """Accessor for an iterator over the JWE recipient key identifiers."""NEWLINE for recip in self._recipients:NEWLINE if recip.header and "kid" in recip.header:NEWLINE yield recip.header["kid"]NEWLINENEWLINE def get_recipient(self, kid: str) -> JweRecipient:NEWLINE """Find a recipient by key ID."""NEWLINE for recip in self._recipients:NEWLINE if recip.header and recip.header.get("kid") == kid:NEWLINE header = self.protected.copy()NEWLINE header.update(self.unprotected)NEWLINE header.update(recip.header)NEWLINE return JweRecipient(encrypted_key=recip.encrypted_key, header=header)NEWLINENEWLINE @propertyNEWLINE def combined_aad(self) -> bytes:NEWLINE """Accessor for the additional authenticated data."""NEWLINE aad = self.protected_bytesNEWLINE if self.aad:NEWLINE aad += b"." + b64url(self.aad).encode("utf-8")NEWLINE return aadNEWLINE |
# generated by datamodel-codegen:NEWLINE# filename: schema/api/services/updateDatabaseService.jsonNEWLINE# timestamp: 2021-10-01T19:50:55+00:00NEWLINENEWLINEfrom __future__ import annotationsNEWLINENEWLINEfrom typing import OptionalNEWLINENEWLINEfrom pydantic import BaseModel, FieldNEWLINENEWLINEfrom ...type import jdbcConnection, scheduleNEWLINENEWLINENEWLINEclass UpdateDatabaseServiceEntityRequest(BaseModel):NEWLINE description: Optional[str] = Field(NEWLINE None, description='Description of Database service entity.'NEWLINE )NEWLINE jdbc: Optional[jdbcConnection.JdbcInfo] = NoneNEWLINE ingestionSchedule: Optional[schedule.Schedule] = Field(NEWLINE None, description='Schedule for running metadata ingestion jobs'NEWLINE )NEWLINE |
class ServerFlushed:NEWLINE def __init__(self, request):NEWLINE self.request = requestNEWLINE |
_base_ = [NEWLINE 'r50_sz224_4xb64_head1_lr0_1_step_ep20.py',NEWLINE]NEWLINENEWLINE# optimizerNEWLINEoptimizer = dict(paramwise_options={'\\Ahead.': dict(lr_mult=100)})NEWLINE |
NEWLINEimport reNEWLINENEWLINENEWLINEclass RegexValidator(object):NEWLINE def __init__(self, pattern, excludes):NEWLINE if not pattern or pattern == '':NEWLINE pattern = '.*' # match anythingNEWLINE if not excludes or excludes == '':NEWLINE excludes = 'a^' # match nothingNEWLINENEWLINE self._pattern = re.compile(pattern)NEWLINE self._excludes = re.compile(excludes)NEWLINENEWLINE def is_valid(self, string):NEWLINE return self._pattern.match(string) and not self._excludes.match(string)NEWLINENEWLINENEWLINEclass FilesPathValidator(RegexValidator):NEWLINE def __init__(self, excluded_paths, pattern_regex, excludes_regex):NEWLINE self._excluded_paths = excluded_pathsNEWLINENEWLINE super(FilesPathValidator, self).__init__(pattern_regex, excludes_regex)NEWLINENEWLINE def is_valid(self, string):NEWLINE if string not in self._excluded_paths:NEWLINE return super(FilesPathValidator, self).is_valid(string)NEWLINE return FalseNEWLINENEWLINE |
# -*- coding: utf-8 -*-NEWLINEfrom __future__ import absolute_import, division, print_function, unicode_literalsNEWLINENEWLINEfrom copy import deepcopyNEWLINENEWLINEfrom django.test.testcases import TestCaseNEWLINENEWLINEfrom djstripe.models import CouponNEWLINENEWLINEfrom . import FAKE_COUPONNEWLINENEWLINENEWLINEclass TransferTest(TestCase):NEWLINE def test_retrieve_coupon(self):NEWLINE coupon_data = deepcopy(FAKE_COUPON)NEWLINE coupon = Coupon.sync_from_stripe_data(coupon_data)NEWLINE self.assertEqual(coupon.stripe_id, FAKE_COUPON["id"])NEWLINENEWLINENEWLINEclass HumanReadableCouponTest(TestCase):NEWLINE def test_human_readable_usd_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-amount-off-forever", amount_off=10, currency="usd",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "$10.00 USD off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_eur_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-amount-off-forever", amount_off=10, currency="eur",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "€10.00 EUR off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-forever", percent_off=10, currency="usd",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_once(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-once", percent_off=10, currency="usd",NEWLINE duration="once",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off once")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_one_month(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-1month", percent_off=10, currency="usd",NEWLINE duration="repeating", duration_in_months=1,NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off for 1 month")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_three_months(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-3month", percent_off=10, currency="usd",NEWLINE duration="repeating", duration_in_months=3,NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off for 3 months")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINE |
# (C) Datadog, Inc. 2018-presentNEWLINE# All rights reservedNEWLINE# Licensed under Simplified BSD License (see LICENSE)NEWLINENEWLINEimport copyNEWLINEimport loggingNEWLINEimport osNEWLINENEWLINEfrom datadog_checks.base.stubs.aggregator import AggregatorStubNEWLINEfrom datadog_checks.base.utils.common import get_docker_hostnameNEWLINEfrom datadog_checks.dev.docker import get_container_ipNEWLINEfrom datadog_checks.snmp import SnmpCheckNEWLINENEWLINElog = logging.getLogger(__name__)NEWLINENEWLINEHOST = get_docker_hostname()NEWLINEPORT = 1161NEWLINEHERE = os.path.dirname(os.path.abspath(__file__))NEWLINECOMPOSE_DIR = os.path.join(HERE, 'compose')NEWLINENEWLINEAUTH_PROTOCOLS = {'MD5': 'usmHMACMD5AuthProtocol', 'SHA': 'usmHMACSHAAuthProtocol'}NEWLINEPRIV_PROTOCOLS = {'DES': 'usmDESPrivProtocol', 'AES': 'usmAesCfb128Protocol'}NEWLINEAUTH_KEY = 'doggiepass'NEWLINEPRIV_KEY = 'doggiePRIVkey'NEWLINESNMP_CONTAINER_NAME = 'dd-snmp'NEWLINENEWLINECHECK_TAGS = ['snmp_device:{}'.format(HOST)]NEWLINENEWLINESNMP_CONF = {'name': 'snmp_conf', 'ip_address': HOST, 'port': PORT, 'community_string': 'public'}NEWLINENEWLINESNMP_V3_CONF = {NEWLINE 'name': 'snmp_v3_conf',NEWLINE 'ip_address': HOST,NEWLINE 'port': PORT,NEWLINE 'user': None,NEWLINE 'authKey': None,NEWLINE 'privKey': None,NEWLINE 'authProtocol': None,NEWLINE 'privProtocol': None,NEWLINE 'context_name': 'public',NEWLINE}NEWLINENEWLINEMIBS_FOLDER = {'mibs_folder': os.path.join(HERE, "mibs")}NEWLINENEWLINEIGNORE_NONINCREASING_OID = {'ignore_nonincreasing_oid': True}NEWLINENEWLINESUPPORTED_METRIC_TYPES = [NEWLINE {'OID': "1.3.6.1.2.1.7.1.0", 'name': "IAmACounter32"}, # Counter32NEWLINE {'OID': "1.3.6.1.2.1.4.31.1.1.6.1", 'name': "IAmACounter64"}, # Counter64NEWLINE {'OID': "1.3.6.1.2.1.4.24.6.0", 'name': "IAmAGauge32"}, # Gauge32NEWLINE {'OID': "1.3.6.1.2.1.88.1.1.1.0", 'name': "IAmAnInteger"}, # IntegerNEWLINE]NEWLINENEWLINEUNSUPPORTED_METRICS = [{'OID': "1.3.6.1.2.1.25.6.3.1.5.1", 'name': "IAmString"}] # String (not supported)NEWLINENEWLINECAST_METRICS = [NEWLINE {'OID': "1.3.6.1.4.1.2021.10.1.3.1", 'name': "cpuload1"}, # OctetStringNEWLINE {'OID': "1.3.6.1.4.1.2021.10.1.6.1", 'name': "cpuload2"}, # OpaqueNEWLINE]NEWLINENEWLINECONSTRAINED_OID = [{"MIB": "RFC1213-MIB", "symbol": "tcpRtoAlgorithm"}]NEWLINENEWLINEDUMMY_MIB_OID = [NEWLINE ({"MIB": "DUMMY-MIB", "symbol": "scalar"}, AggregatorStub.GAUGE, 10), # IntegerNEWLINE # Additional types we support but that are not part of the original SNMP protocol.NEWLINE ({"MIB": "DUMMY-MIB", "symbol": "dummyCounterGauge"}, AggregatorStub.GAUGE, 90), # CounterBasedGauge64NEWLINE ({"MIB": "DUMMY-MIB", "symbol": "dummyZeroCounter"}, AggregatorStub.RATE, 120), # ZeroBasedCounter64NEWLINE]NEWLINENEWLINEFORCED_METRICS = [NEWLINE {'OID': "1.3.6.1.2.1.4.24.6.0", 'name': "IAmAGauge32", 'forced_type': 'counter'}, # Gauge32NEWLINE {'OID': "1.3.6.1.2.1.4.31.1.1.6.1", 'name': "IAmACounter64", 'forced_type': 'gauge'}, # Counter32NEWLINE]NEWLINEINVALID_FORCED_METRICS = [NEWLINE {'OID': "1.3.6.1.2.1.4.24.6.0", 'name': "IAmAGauge32", 'forced_type': 'counter'}, # Gauge32NEWLINE {'OID': "1.3.6.1.2.1.4.31.1.1.6.1", 'name': "IAmACounter64", 'forced_type': 'histogram'}, # Counter32NEWLINE]NEWLINENEWLINESCALAR_OBJECTS = [NEWLINE {'OID': "1.3.6.1.2.1.7.1.0", 'name': "udpDatagrams"},NEWLINE {'OID': "1.3.6.1.2.1.6.10.0", 'name': "tcpInSegs"},NEWLINE {'OID': ".1.3.6.1.6.3.10.2.1.3.0", 'name': "snmpEngineTime"}, # OID with leading dotNEWLINE {'MIB': "TCP-MIB", 'symbol': "tcpCurrEstab"},NEWLINE]NEWLINENEWLINESCALAR_OBJECTS_WITH_TAGS = [NEWLINE {'OID': "1.3.6.1.2.1.7.1.0", 'name': "udpDatagrams", 'metric_tags': ['udpdgrams', 'UDP']},NEWLINE {'OID': "1.3.6.1.2.1.6.10.0", 'name': "tcpInSegs", 'metric_tags': ['tcpinsegs', 'TCP']},NEWLINE {'MIB': "TCP-MIB", 'symbol': "tcpCurrEstab", 'metric_tags': ['MIB', 'TCP', 'estab']},NEWLINE]NEWLINENEWLINETABULAR_OBJECTS = [NEWLINE {NEWLINE 'MIB': "IF-MIB",NEWLINE 'table': "ifTable",NEWLINE 'symbols': ["ifInOctets", "ifOutOctets"],NEWLINE 'metric_tags': [{'tag': "interface", 'column': "ifDescr"}, {'tag': "dumbindex", 'index': 1}],NEWLINE }NEWLINE]NEWLINENEWLINEBULK_TABULAR_OBJECTS = [NEWLINE {NEWLINE 'MIB': "IF-MIB",NEWLINE 'table': "ifTable",NEWLINE 'symbols': [NEWLINE "ifInOctets",NEWLINE "ifOutOctets",NEWLINE "ifInUcastPkts",NEWLINE "ifInUcastPkts",NEWLINE "ifInNUcastPkts",NEWLINE "ifInDiscards",NEWLINE "ifInErrors",NEWLINE "ifInUnknownProtos",NEWLINE ],NEWLINE 'metric_tags': [{'tag': "interface", 'column': "ifDescr"}, {'tag': "dumbindex", 'index': 1}],NEWLINE },NEWLINE {NEWLINE 'MIB': "IP-MIB",NEWLINE 'table': "ipSystemStatsTable",NEWLINE 'symbols': [NEWLINE "ipSystemStatsInReceives",NEWLINE "ipSystemStatsHCInReceives",NEWLINE "ipSystemStatsInOctets",NEWLINE "ipSystemStatsHCInOctets",NEWLINE "ipSystemStatsInHdrErrors",NEWLINE "ipSystemStatsInNoRoutes",NEWLINE "ipSystemStatsInAddrErrors",NEWLINE "ipSystemStatsInUnknownProtos",NEWLINE "ipSystemStatsInTruncatedPkts",NEWLINE "ipSystemStatsInForwDatagrams",NEWLINE "ipSystemStatsHCInForwDatagrams",NEWLINE "ipSystemStatsReasmReqds",NEWLINE "ipSystemStatsReasmOKs",NEWLINE "ipSystemStatsReasmFails",NEWLINE "ipSystemStatsInDiscards",NEWLINE "ipSystemStatsInDelivers",NEWLINE "ipSystemStatsHCInDelivers",NEWLINE "ipSystemStatsOutRequests",NEWLINE "ipSystemStatsHCOutRequests",NEWLINE "ipSystemStatsOutNoRoutes",NEWLINE "ipSystemStatsOutForwDatagrams",NEWLINE "ipSystemStatsHCOutForwDatagrams",NEWLINE "ipSystemStatsOutDiscards",NEWLINE "ipSystemStatsOutFragReqds",NEWLINE "ipSystemStatsOutFragOKs",NEWLINE "ipSystemStatsOutFragFails",NEWLINE "ipSystemStatsOutFragCreates",NEWLINE "ipSystemStatsOutTransmits",NEWLINE "ipSystemStatsHCOutTransmits",NEWLINE "ipSystemStatsOutOctets",NEWLINE "ipSystemStatsHCOutOctets",NEWLINE "ipSystemStatsInMcastPkts",NEWLINE ],NEWLINE },NEWLINE]NEWLINENEWLINEINVALID_METRICS = [{'MIB': "IF-MIB", 'table': "noIdeaWhatIAmDoingHere", 'symbols': ["ImWrong", "MeToo"]}]NEWLINENEWLINEPLAY_WITH_GET_NEXT_METRICS = [NEWLINE {"OID": "1.3.6.1.2.1.4.31.3.1.3.2", "name": "needFallback"},NEWLINE {"OID": "1.3.6.1.2.1.4.31.3.1.3.2.1", "name": "noFallbackAndSameResult"},NEWLINE]NEWLINENEWLINERESOLVED_TABULAR_OBJECTS = [NEWLINE {NEWLINE "MIB": "IF-MIB",NEWLINE "table": "ifTable",NEWLINE "symbols": [NEWLINE {"name": "ifInOctets", "OID": "1.3.6.1.2.1.2.2.1.10"},NEWLINE {"name": "ifOutOctets", "OID": "1.3.6.1.2.1.2.2.1.16"},NEWLINE ],NEWLINE "metric_tags": [NEWLINE {"tag": "interface", "column": {"name": "ifDescr", "OID": "1.3.6.1.2.1.2.2.1.2"}},NEWLINE {"tag": "dumbindex", "index": 1, "mapping": {1: "one", 2: "two", 3: "three", 90: "other"}},NEWLINE ],NEWLINE }NEWLINE]NEWLINENEWLINENEWLINEdef generate_instance_config(metrics, template=None):NEWLINE template = template if template else SNMP_CONFNEWLINE instance_config = copy.copy(template)NEWLINE instance_config['metrics'] = metricsNEWLINE instance_config['name'] = HOSTNEWLINE return instance_configNEWLINENEWLINENEWLINEdef generate_container_instance_config(metrics):NEWLINE conf = copy.deepcopy(SNMP_CONF)NEWLINE conf['ip_address'] = get_container_ip(SNMP_CONTAINER_NAME)NEWLINE return generate_instance_config(metrics, template=conf)NEWLINENEWLINENEWLINEdef generate_v3_instance_config(metrics, name=None, user=None, auth=None, auth_key=None, priv=None, priv_key=None):NEWLINE instance_config = generate_instance_config(metrics, SNMP_V3_CONF)NEWLINENEWLINE if name:NEWLINE instance_config['name'] = nameNEWLINE if user:NEWLINE instance_config['user'] = userNEWLINE if auth:NEWLINE instance_config['authProtocol'] = authNEWLINE if auth_key:NEWLINE instance_config['authKey'] = auth_keyNEWLINE if priv:NEWLINE instance_config['privProtocol'] = privNEWLINE if priv_key:NEWLINE instance_config['privKey'] = priv_keyNEWLINENEWLINE return instance_configNEWLINENEWLINENEWLINEdef create_check(instance):NEWLINE return SnmpCheck('snmp', {}, [instance])NEWLINE |
formatter = "%r %r %r %r"NEWLINEprint (formatter % (1 ,2 ,3 , 4))NEWLINEprint (formatter % ("one","two","three","four"))NEWLINEprint (formatter % (True, False, False, True))NEWLINEprint (formatter % (formatter ,formatter, formatter, formatter))NEWLINEprint (formatter % NEWLINE ("I had this thing.",NEWLINE "That you could type up right.",NEWLINE "But it didn't sing.",NEWLINE "So I said goodnight.")NEWLINE )NEWLINE NEWLINE |
#!/usr/bin/pythonNEWLINE# Copyright 2012 William YuNEWLINE# [email protected]#NEWLINE# This file is part of POX.NEWLINE#NEWLINE# POX is free software: you can redistribute it and/or modifyNEWLINE# it under the terms of the GNU General Public License as published byNEWLINE# the Free Software Foundation, either version 3 of the License, orNEWLINE# (at your option) any later version.NEWLINE#NEWLINE# POX is distributed in the hope that it will be useful,NEWLINE# but WITHOUT ANY WARRANTY; without even the implied warranty ofNEWLINE# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theNEWLINE# GNU General Public License for more details.NEWLINE#NEWLINE# You should have received a copy of the GNU General Public LicenseNEWLINE# along with POX. If not, see <http://www.gnu.org/licenses/>.NEWLINE#NEWLINENEWLINE"""NEWLINEThis is a demonstration file created to show how to obtain flowNEWLINEand port statistics from OpenFlow 1.0-enabled switches. The flowNEWLINEstatistics handler contains a summary of web-only traffic.NEWLINE"""NEWLINENEWLINE# standard includesNEWLINEfrom pox.core import coreNEWLINEfrom pox.lib.util import dpidToStrNEWLINEimport pox.openflow.libopenflow_01 as ofNEWLINEfrom collections import defaultdictNEWLINENEWLINE# include as part of the betta branchNEWLINEfrom pox.openflow.of_json import *NEWLINENEWLINEfrom pox.forwarding.my_l2_multi import SwitchNEWLINENEWLINENEWLINEtime_period = 5 # time between stats requestsNEWLINEthreshhold = 2000000 # = 3Mbit/s na 8 dla allNEWLINEpaths = defaultdict(lambda:defaultdict(lambda:[]))NEWLINElog = core.getLogger()NEWLINEsws = {} # switchesNEWLINE#host_switch_pair = defaultdict(lambda:None)NEWLINENEWLINENEWLINE# get paths from my_l2_multi moduleNEWLINEdef get_paths():NEWLINE global swsNEWLINE from pox.forwarding.my_l2_multi import switchesNEWLINE if sws != switches:NEWLINE sws = switchesNEWLINE log.debug("NOT EQUAL - switches has changed since last time we checked")NEWLINE # to do - > add some clearing for statsNEWLINE else:NEWLINE # log.debug("EQUAL")NEWLINE passNEWLINE for sw in sws.values():NEWLINE #log.debug("Switch %s, ports %s", dpidToStr(sw.dpid), sw.ports)NEWLINE passNEWLINENEWLINE global pathsNEWLINE from pox.forwarding.my_l2_multi import all_cooked_pathsNEWLINE if paths != all_cooked_paths:NEWLINE paths = all_cooked_pathsNEWLINE log.debug("NOT EQUAL - paths has changed since last time we checked")NEWLINE # to do - > add some clearing for statsNEWLINE else:NEWLINE log.debug("EQUAL - paths has not changed since last time we checked")NEWLINENEWLINENEWLINE from pox.forwarding.my_l2_multi import path_mapNEWLINE global path_mapNEWLINENEWLINE from pox.forwarding.my_l2_multi import host_switch_pairNEWLINE global host_switch_pairNEWLINENEWLINENEWLINENEWLINE# when _handle_portstats_received will receive stats for port on switchNEWLINE# it will send them here to be applied for paths,NEWLINE# stats here are bytes sent by this portNEWLINEdef apply_stats_to_paths(switch, port, stats):NEWLINE # global pathsNEWLINE # log.debug("Checking switch %s port %s ", switch, port )NEWLINE # for src in sws.values():NEWLINE # for dst in sws.values():NEWLINE # for path in paths[src][dst]:NEWLINE # for switch_port_pair in path:NEWLINE # #log.debug("switch-port pair %s, %s", dpidToStr(switch_port_pair[0].dpid), switch_port_pair[1] )NEWLINE # if switch == dpidToStr(switch_port_pair[0].dpid) and port == switch_port_pair[1]:NEWLINE # # log.debug("switch-port pair %s, %s", dpidToStr(switch_port_pair[0].dpid), switch_port_pair[1] )NEWLINE # # log.debug(path)NEWLINE # # switch_port_pair.append(stats) -> this isn't working, what is better?NEWLINE # # to do -> how append stats?NEWLINE # # print statsNEWLINE # passNEWLINE from pox.forwarding.my_l2_multi import CookedPathNEWLINE for cookedpathobj in CookedPath:NEWLINE for switch_port_pair in cookedpathobj.cooked_path:NEWLINE if switch == dpidToStr(switch_port_pair[0].dpid) and port == switch_port_pair[2]:NEWLINE cookedpathobj.bytes_diff_list[cookedpathobj.cooked_path.index(switch_port_pair)] = \NEWLINE stats - cookedpathobj.bytes_diff_list[cookedpathobj.cooked_path.index(switch_port_pair)]NEWLINE # log.debug("Switch-port pair %s, %s", dpidToStr(switch_port_pair[0].dpid), switch_port_pair[2])NEWLINE # log.debug("Bytes sent overall: %s", stats)NEWLINE log.debug("Path: %s", cookedpathobj.cooked_path)NEWLINE log.debug("Bytes diff list: %s", cookedpathobj.bytes_diff_list)NEWLINE cookedpathobj.path_coefficient = max(cookedpathobj.bytes_diff_list[:-1])NEWLINE # log.debug("Path coeff: %s", cookedpathobj.path_coefficient)NEWLINENEWLINE# handler for timer function that sends the requests to all theNEWLINE# switches connected to the controller.NEWLINEdef _timer_func ():NEWLINE get_paths()NEWLINE for connection in core.openflow._connections.values():NEWLINE connection.send(of.ofp_stats_request(body=of.ofp_flow_stats_request()))NEWLINE connection.send(of.ofp_stats_request(body=of.ofp_port_stats_request()))NEWLINE log.debug("Sent %i flow/port stats request(s)", len(core.openflow._connections))NEWLINENEWLINE# handler to display flow statistics received in JSON formatNEWLINE# structure of event.stats is defined by ofp_flow_stats()NEWLINEdef _handle_flowstats_received (event):NEWLINE stats = flow_stats_to_list(event.stats)NEWLINE #log.debug("FlowStatsReceived from %s: %s",NEWLINE # dpidToStr(event.connection.dpid), stats)NEWLINE for flow_stats in event.stats:NEWLINE # log.debug("Bytes in flow match%s: %s",NEWLINE # flow_stats.match, flow_stats.byte_count)NEWLINENEWLINE # ALL THIS HAS TO BE CHECK YET !!! - > no duplications, add flow deleting after some time, etc.NEWLINE # We want to gather stats for flow only in switch connected to src hostNEWLINE # to avoid duplicationNEWLINE if host_switch_pair[flow_stats.match.dl_src][0] == event.connection.dpid:NEWLINE # log.debug("Flow stats found ", flow_stats.match.dl_src, host_switch_pair[flow_stats.match.dl_src], event.connection.dpid)NEWLINE # Only IP flowsNEWLINE if flow_stats.match.dl_type == 0x800:NEWLINE log.debug('IP Matched')NEWLINE flow_match5 = [flow_stats.match.nw_proto, flow_stats.match.nw_src, flow_stats.match.nw_dst, \NEWLINE flow_stats.match.tp_src, flow_stats.match.tp_dst]NEWLINE from pox.forwarding.my_l2_multi import flow_listNEWLINE for flow in flow_list:NEWLINE #print "Flow match stat", flow_match5NEWLINE #print "Flow match List", flow.match, "\n"NEWLINE if flow.match5 == flow_match5:NEWLINE log.debug("Flow 5 Match found")NEWLINE if flow.changed == 1:NEWLINE break # we only change path onceNEWLINE # TO DO -> handle timeouts, different switches etc.NEWLINE # we want to take stats only from switch connected to host to avoid complicationsNEWLINE flow.byte_diff = flow_stats.byte_count - flow.byte_countNEWLINE log.debug("Bytes: received from stats %s, from this flow last checked %s, diff %s, bandwith in bits %s",NEWLINE flow_stats.byte_count, flow.byte_count, flow.byte_diff, flow.byte_diff/time_period*8)NEWLINE flow.byte_count = flow_stats.byte_countNEWLINENEWLINE if flow.byte_diff/time_period*8 > threshhold:NEWLINE log.debug("Uuuuuu, found big flow! %s", flow.match)NEWLINE print "Sw src, sw dst: ", flow.switch_src, flow.switch_dstNEWLINE intermediate = path_map[flow.switch_src][flow.switch_dst][1]NEWLINE if intermediate is None:NEWLINE print "Directly connected"NEWLINENEWLINE best_path = find_best_path(flow.switch_src, flow.switch_dst)NEWLINE print "best path, flow path:"NEWLINE print best_path, "\n", flow.pathNEWLINE if best_path != flow.path and best_path is not None:NEWLINE print "\nPath of big flow is not the best path - moved!\n"NEWLINE Switch.delete_path(sws[event.connection.dpid], flow.path, flow.match)NEWLINE Switch._install_path(sws[event.connection.dpid], best_path, flow.match)NEWLINE flow.path = best_pathNEWLINE flow.changed = 1NEWLINENEWLINE breakNEWLINENEWLINENEWLINE# handler to display port statistics received in JSON formatNEWLINEdef _handle_portstats_received (event):NEWLINE stats = flow_stats_to_list(event.stats)NEWLINE # log.debug("PortStatsReceived from %s: %s",NEWLINE # dpidToStr(event.connection.dpid), stats)NEWLINENEWLINE for f in event.stats:NEWLINE if int(f.port_no)<65534:NEWLINE apply_stats_to_paths(dpidToStr(event.connection.dpid), f.port_no, f.tx_bytes)NEWLINENEWLINENEWLINEdef find_best_path(src, dst):NEWLINE best_path_coeff = NoneNEWLINE best_path = NoneNEWLINE from pox.forwarding.my_l2_multi import CookedPathNEWLINE print "Cooked paths:"NEWLINE for cookedpathobj in CookedPath:NEWLINE if cookedpathobj.switch_src == src and cookedpathobj.switch_dst == dst:NEWLINE print cookedpathobj.cooked_pathNEWLINE print cookedpathobj.bytes_diff_list, cookedpathobj.path_coefficientNEWLINENEWLINE if best_path_coeff is None:NEWLINE best_path_coeff = cookedpathobj.path_coefficientNEWLINE best_path = cookedpathobj.cooked_pathNEWLINE log.debug("Best path: %s, coeff: %s", best_path, best_path_coeff)NEWLINE elif cookedpathobj.path_coefficient < best_path_coeff:NEWLINE best_path_coeff = cookedpathobj.path_coefficientNEWLINE best_path = cookedpathobj.cooked_pathNEWLINE log.debug("Best path: %s, coeff: %s", best_path, best_path_coeff)NEWLINE return best_pathNEWLINENEWLINENEWLINENEWLINENEWLINE# main functiont to launch the moduleNEWLINEdef launch ():NEWLINE from pox.lib.recoco import TimerNEWLINENEWLINE # attach handsers to listnersNEWLINE core.openflow.addListenerByName("FlowStatsReceived",NEWLINE _handle_flowstats_received)NEWLINE core.openflow.addListenerByName("PortStatsReceived",NEWLINE _handle_portstats_received)NEWLINENEWLINE # timer set to execute every five secondsNEWLINE Timer(time_period, _timer_func, recurring=True) |
import pickleNEWLINEimport sysNEWLINEimport warningsNEWLINEfrom copy import copy, deepcopyNEWLINEfrom io import StringIONEWLINEfrom textwrap import dedentNEWLINENEWLINEimport numpy as npNEWLINEimport pandas as pdNEWLINEimport pytestNEWLINENEWLINEimport xarray as xrNEWLINEfrom xarray import (NEWLINE DataArray,NEWLINE Dataset,NEWLINE IndexVariable,NEWLINE MergeError,NEWLINE Variable,NEWLINE align,NEWLINE backends,NEWLINE broadcast,NEWLINE open_dataset,NEWLINE set_options,NEWLINE)NEWLINEfrom xarray.core import dtypes, indexing, utilsNEWLINEfrom xarray.core.common import duck_array_ops, full_likeNEWLINEfrom xarray.core.npcompat import IS_NEP18_ACTIVENEWLINEfrom xarray.core.pycompat import integer_typesNEWLINENEWLINEfrom . import (NEWLINE InaccessibleArray,NEWLINE LooseVersion,NEWLINE UnexpectedDataAccess,NEWLINE assert_allclose,NEWLINE assert_array_equal,NEWLINE assert_equal,NEWLINE assert_identical,NEWLINE has_cftime,NEWLINE has_dask,NEWLINE raises_regex,NEWLINE requires_bottleneck,NEWLINE requires_cftime,NEWLINE requires_dask,NEWLINE requires_numbagg,NEWLINE requires_scipy,NEWLINE requires_sparse,NEWLINE source_ndarray,NEWLINE)NEWLINENEWLINEtry:NEWLINE import dask.array as daNEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINENEWLINEdef create_test_data(seed=None):NEWLINE rs = np.random.RandomState(seed)NEWLINE _vars = {NEWLINE "var1": ["dim1", "dim2"],NEWLINE "var2": ["dim1", "dim2"],NEWLINE "var3": ["dim3", "dim1"],NEWLINE }NEWLINE _dims = {"dim1": 8, "dim2": 9, "dim3": 10}NEWLINENEWLINE obj = Dataset()NEWLINE obj["time"] = ("time", pd.date_range("2000-01-01", periods=20))NEWLINE obj["dim2"] = ("dim2", 0.5 * np.arange(_dims["dim2"]))NEWLINE obj["dim3"] = ("dim3", list("abcdefghij"))NEWLINE for v, dims in sorted(_vars.items()):NEWLINE data = rs.normal(size=tuple(_dims[d] for d in dims))NEWLINE obj[v] = (dims, data, {"foo": "variable"})NEWLINE obj.coords["numbers"] = (NEWLINE "dim3",NEWLINE np.array([0, 1, 2, 0, 0, 1, 1, 2, 2, 3], dtype="int64"),NEWLINE )NEWLINE obj.encoding = {"foo": "bar"}NEWLINE assert all(obj.data.flags.writeable for obj in obj.variables.values())NEWLINE return objNEWLINENEWLINENEWLINEdef create_append_test_data(seed=None):NEWLINE rs = np.random.RandomState(seed)NEWLINENEWLINE lat = [2, 1, 0]NEWLINE lon = [0, 1, 2]NEWLINE nt1 = 3NEWLINE nt2 = 2NEWLINE time1 = pd.date_range("2000-01-01", periods=nt1)NEWLINE time2 = pd.date_range("2000-02-01", periods=nt2)NEWLINE string_var = np.array(["ae", "bc", "df"], dtype=object)NEWLINE string_var_to_append = np.array(["asdf", "asdfg"], dtype=object)NEWLINE unicode_var = ["áó", "áó", "áó"]NEWLINENEWLINE ds = xr.Dataset(NEWLINE data_vars={NEWLINE "da": xr.DataArray(NEWLINE rs.rand(3, 3, nt1),NEWLINE coords=[lat, lon, time1],NEWLINE dims=["lat", "lon", "time"],NEWLINE ),NEWLINE "string_var": xr.DataArray(string_var, coords=[time1], dims=["time"]),NEWLINE "unicode_var": xr.DataArray(NEWLINE unicode_var, coords=[time1], dims=["time"]NEWLINE ).astype(np.unicode_),NEWLINE }NEWLINE )NEWLINENEWLINE ds_to_append = xr.Dataset(NEWLINE data_vars={NEWLINE "da": xr.DataArray(NEWLINE rs.rand(3, 3, nt2),NEWLINE coords=[lat, lon, time2],NEWLINE dims=["lat", "lon", "time"],NEWLINE ),NEWLINE "string_var": xr.DataArray(NEWLINE string_var_to_append, coords=[time2], dims=["time"]NEWLINE ),NEWLINE "unicode_var": xr.DataArray(NEWLINE unicode_var[:nt2], coords=[time2], dims=["time"]NEWLINE ).astype(np.unicode_),NEWLINE }NEWLINE )NEWLINENEWLINE ds_with_new_var = xr.Dataset(NEWLINE data_vars={NEWLINE "new_var": xr.DataArray(NEWLINE rs.rand(3, 3, nt1 + nt2),NEWLINE coords=[lat, lon, time1.append(time2)],NEWLINE dims=["lat", "lon", "time"],NEWLINE )NEWLINE }NEWLINE )NEWLINENEWLINE assert all(objp.data.flags.writeable for objp in ds.variables.values())NEWLINE assert all(objp.data.flags.writeable for objp in ds_to_append.variables.values())NEWLINE return ds, ds_to_append, ds_with_new_varNEWLINENEWLINENEWLINEdef create_test_multiindex():NEWLINE mindex = pd.MultiIndex.from_product(NEWLINE [["a", "b"], [1, 2]], names=("level_1", "level_2")NEWLINE )NEWLINE return Dataset({}, {"x": mindex})NEWLINENEWLINENEWLINEdef create_test_stacked_array():NEWLINE x = DataArray(pd.Index(np.r_[:10], name="x"))NEWLINE y = DataArray(pd.Index(np.r_[:20], name="y"))NEWLINE a = x * yNEWLINE b = x * y * yNEWLINE return a, bNEWLINENEWLINENEWLINEclass InaccessibleVariableDataStore(backends.InMemoryDataStore):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self._indexvars = set()NEWLINENEWLINE def store(self, variables, *args, **kwargs):NEWLINE super().store(variables, *args, **kwargs)NEWLINE for k, v in variables.items():NEWLINE if isinstance(v, IndexVariable):NEWLINE self._indexvars.add(k)NEWLINENEWLINE def get_variables(self):NEWLINE def lazy_inaccessible(k, v):NEWLINE if k in self._indexvars:NEWLINE return vNEWLINE data = indexing.LazilyOuterIndexedArray(InaccessibleArray(v.values))NEWLINE return Variable(v.dims, data, v.attrs)NEWLINENEWLINE return {k: lazy_inaccessible(k, v) for k, v in self._variables.items()}NEWLINENEWLINENEWLINEclass TestDataset:NEWLINE def test_repr(self):NEWLINE data = create_test_data(seed=123)NEWLINE data.attrs["foo"] = "bar"NEWLINE # need to insert str dtype at runtime to handle different endiannessNEWLINE expected = dedent(NEWLINE """\NEWLINE <xarray.Dataset>NEWLINE Dimensions: (dim1: 8, dim2: 9, dim3: 10, time: 20)NEWLINE Coordinates:NEWLINE * time (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-20NEWLINE * dim2 (dim2) float64 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0NEWLINE * dim3 (dim3) %s 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'NEWLINE numbers (dim3) int64 0 1 2 0 0 1 1 2 2 3NEWLINE Dimensions without coordinates: dim1NEWLINE Data variables:NEWLINE var1 (dim1, dim2) float64 -1.086 0.9973 0.283 ... 0.1995 0.4684 -0.8312NEWLINE var2 (dim1, dim2) float64 1.162 -1.097 -2.123 ... 0.1302 1.267 0.3328NEWLINE var3 (dim3, dim1) float64 0.5565 -0.2121 0.4563 ... -0.2452 -0.3616NEWLINE Attributes:NEWLINE foo: bar"""NEWLINE % data["dim3"].dtypeNEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE with set_options(display_width=100):NEWLINE max_len = max(map(len, repr(data).split("\n")))NEWLINE assert 90 < max_len < 100NEWLINENEWLINE expected = dedent(NEWLINE """\NEWLINE <xarray.Dataset>NEWLINE Dimensions: ()NEWLINE Data variables:NEWLINE *empty*"""NEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(Dataset()).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE # verify that ... doesn't appear for scalar coordinatesNEWLINE data = Dataset({"foo": ("x", np.ones(10))}).mean()NEWLINE expected = dedent(NEWLINE """\NEWLINE <xarray.Dataset>NEWLINE Dimensions: ()NEWLINE Data variables:NEWLINE foo float64 1.0"""NEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE # verify long attributes are truncatedNEWLINE data = Dataset(attrs={"foo": "bar" * 1000})NEWLINE assert len(repr(data)) < 1000NEWLINENEWLINE def test_repr_multiindex(self):NEWLINE data = create_test_multiindex()NEWLINE expected = dedent(NEWLINE """\NEWLINE <xarray.Dataset>NEWLINE Dimensions: (x: 4)NEWLINE Coordinates:NEWLINE * x (x) MultiIndexNEWLINE - level_1 (x) object 'a' 'a' 'b' 'b'NEWLINE - level_2 (x) int64 1 2 1 2NEWLINE Data variables:NEWLINE *empty*"""NEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE # verify that long level names are not truncatedNEWLINE mindex = pd.MultiIndex.from_product(NEWLINE [["a", "b"], [1, 2]], names=("a_quite_long_level_name", "level_2")NEWLINE )NEWLINE data = Dataset({}, {"x": mindex})NEWLINE expected = dedent(NEWLINE """\NEWLINE <xarray.Dataset>NEWLINE Dimensions: (x: 4)NEWLINE Coordinates:NEWLINE * x (x) MultiIndexNEWLINE - a_quite_long_level_name (x) object 'a' 'a' 'b' 'b'NEWLINE - level_2 (x) int64 1 2 1 2NEWLINE Data variables:NEWLINE *empty*"""NEWLINE )NEWLINE actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))NEWLINE print(actual)NEWLINE assert expected == actualNEWLINENEWLINE def test_repr_period_index(self):NEWLINE data = create_test_data(seed=456)NEWLINE data.coords["time"] = pd.period_range("2000-01-01", periods=20, freq="B")NEWLINENEWLINE # check that creating the repr doesn't raise an error #GH645NEWLINE repr(data)NEWLINENEWLINE def test_unicode_data(self):NEWLINE # regression test for GH834NEWLINE data = Dataset({"foø": ["ba®"]}, attrs={"å": "∑"})NEWLINE repr(data) # should not raiseNEWLINENEWLINE byteorder = "<" if sys.byteorder == "little" else ">"NEWLINE expected = dedent(NEWLINE """\NEWLINE <xarray.Dataset>NEWLINE Dimensions: (foø: 1)NEWLINE Coordinates:NEWLINE * foø (foø) %cU3 %rNEWLINE Data variables:NEWLINE *empty*NEWLINE Attributes:NEWLINE å: ∑"""NEWLINE % (byteorder, "ba®")NEWLINE )NEWLINE actual = str(data)NEWLINE assert expected == actualNEWLINENEWLINE @pytest.mark.skipif(not IS_NEP18_ACTIVE, reason="requires __array_function__")NEWLINE def test_repr_nep18(self):NEWLINE class Array:NEWLINE def __init__(self):NEWLINE self.shape = (2,)NEWLINE self.dtype = np.dtype(np.float64)NEWLINENEWLINE def __array_function__(self, *args, **kwargs):NEWLINE passNEWLINENEWLINE def __repr__(self):NEWLINE return "Custom\nArray"NEWLINENEWLINE dataset = Dataset({"foo": ("x", Array())})NEWLINE expected = dedent(NEWLINE """\NEWLINE <xarray.Dataset>NEWLINE Dimensions: (x: 2)NEWLINE Dimensions without coordinates: xNEWLINE Data variables:NEWLINE foo (x) float64 Custom Array"""NEWLINE )NEWLINE assert expected == repr(dataset)NEWLINENEWLINE def test_info(self):NEWLINE ds = create_test_data(seed=123)NEWLINE ds = ds.drop_vars("dim3") # string type prints differently in PY2 vs PY3NEWLINE ds.attrs["unicode_attr"] = "ba®"NEWLINE ds.attrs["string_attr"] = "bar"NEWLINENEWLINE buf = StringIO()NEWLINE ds.info(buf=buf)NEWLINENEWLINE expected = dedent(NEWLINE """\NEWLINE xarray.Dataset {NEWLINE dimensions:NEWLINE \tdim1 = 8 ;NEWLINE \tdim2 = 9 ;NEWLINE \tdim3 = 10 ;NEWLINE \ttime = 20 ;NEWLINENEWLINE variables:NEWLINE \tdatetime64[ns] time(time) ;NEWLINE \tfloat64 dim2(dim2) ;NEWLINE \tfloat64 var1(dim1, dim2) ;NEWLINE \t\tvar1:foo = variable ;NEWLINE \tfloat64 var2(dim1, dim2) ;NEWLINE \t\tvar2:foo = variable ;NEWLINE \tfloat64 var3(dim3, dim1) ;NEWLINE \t\tvar3:foo = variable ;NEWLINE \tint64 numbers(dim3) ;NEWLINENEWLINE // global attributes:NEWLINE \t:unicode_attr = ba® ;NEWLINE \t:string_attr = bar ;NEWLINE }"""NEWLINE )NEWLINE actual = buf.getvalue()NEWLINE assert expected == actualNEWLINE buf.close()NEWLINENEWLINE def test_constructor(self):NEWLINE x1 = ("x", 2 * np.arange(100))NEWLINE x2 = ("x", np.arange(1000))NEWLINE z = (["x", "y"], np.arange(1000).reshape(100, 10))NEWLINENEWLINE with raises_regex(ValueError, "conflicting sizes"):NEWLINE Dataset({"a": x1, "b": x2})NEWLINE with raises_regex(ValueError, "disallows such variables"):NEWLINE Dataset({"a": x1, "x": z})NEWLINE with raises_regex(TypeError, "tuple of form"):NEWLINE Dataset({"x": (1, 2, 3, 4, 5, 6, 7)})NEWLINE with raises_regex(ValueError, "already exists as a scalar"):NEWLINE Dataset({"x": 0, "y": ("x", [1, 2, 3])})NEWLINENEWLINE # verify handling of DataArraysNEWLINE expected = Dataset({"x": x1, "z": z})NEWLINE actual = Dataset({"z": expected["z"]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_constructor_invalid_dims(self):NEWLINE # regression for GH1120NEWLINE with pytest.raises(MergeError):NEWLINE Dataset(NEWLINE data_vars=dict(v=("y", [1, 2, 3, 4])),NEWLINE coords=dict(y=DataArray([0.1, 0.2, 0.3, 0.4], dims="x")),NEWLINE )NEWLINENEWLINE def test_constructor_1d(self):NEWLINE expected = Dataset({"x": (["x"], 5.0 + np.arange(5))})NEWLINE actual = Dataset({"x": 5.0 + np.arange(5)})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = Dataset({"x": [5, 6, 7, 8, 9]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_constructor_0d(self):NEWLINE expected = Dataset({"x": ([], 1)})NEWLINE for arg in [1, np.array(1), expected["x"]]:NEWLINE actual = Dataset({"x": arg})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE class Arbitrary:NEWLINE passNEWLINENEWLINE d = pd.Timestamp("2000-01-01T12")NEWLINE args = [NEWLINE True,NEWLINE None,NEWLINE 3.4,NEWLINE np.nan,NEWLINE "hello",NEWLINE b"raw",NEWLINE np.datetime64("2000-01-01"),NEWLINE d,NEWLINE d.to_pydatetime(),NEWLINE Arbitrary(),NEWLINE ]NEWLINE for arg in args:NEWLINE print(arg)NEWLINE expected = Dataset({"x": ([], arg)})NEWLINE actual = Dataset({"x": arg})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_constructor_deprecated(self):NEWLINE with raises_regex(ValueError, "DataArray dimensions"):NEWLINE DataArray([1, 2, 3], coords={"x": [0, 1, 2]})NEWLINENEWLINE def test_constructor_auto_align(self):NEWLINE a = DataArray([1, 2], [("x", [0, 1])])NEWLINE b = DataArray([3, 4], [("x", [1, 2])])NEWLINENEWLINE # verify align uses outer joinNEWLINE expected = Dataset(NEWLINE {"a": ("x", [1, 2, np.nan]), "b": ("x", [np.nan, 3, 4])}, {"x": [0, 1, 2]}NEWLINE )NEWLINE actual = Dataset({"a": a, "b": b})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # regression test for GH346NEWLINE assert isinstance(actual.variables["x"], IndexVariable)NEWLINENEWLINE # variable with different dimensionsNEWLINE c = ("y", [3, 4])NEWLINE expected2 = expected.merge({"c": c})NEWLINE actual = Dataset({"a": a, "b": b, "c": c})NEWLINE assert_identical(expected2, actual)NEWLINENEWLINE # variable that is only aligned against the aligned variablesNEWLINE d = ("x", [3, 2, 1])NEWLINE expected3 = expected.merge({"d": d})NEWLINE actual = Dataset({"a": a, "b": b, "d": d})NEWLINE assert_identical(expected3, actual)NEWLINENEWLINE e = ("x", [0, 0])NEWLINE with raises_regex(ValueError, "conflicting sizes"):NEWLINE Dataset({"a": a, "b": b, "e": e})NEWLINENEWLINE def test_constructor_pandas_sequence(self):NEWLINENEWLINE ds = self.make_example_math_dataset()NEWLINE pandas_objs = {NEWLINE var_name: ds[var_name].to_pandas() for var_name in ["foo", "bar"]NEWLINE }NEWLINE ds_based_on_pandas = Dataset(pandas_objs, ds.coords, attrs=ds.attrs)NEWLINE del ds_based_on_pandas["x"]NEWLINE assert_equal(ds, ds_based_on_pandas)NEWLINENEWLINE # reindex pandas obj, check align worksNEWLINE rearranged_index = reversed(pandas_objs["foo"].index)NEWLINE pandas_objs["foo"] = pandas_objs["foo"].reindex(rearranged_index)NEWLINE ds_based_on_pandas = Dataset(pandas_objs, ds.coords, attrs=ds.attrs)NEWLINE del ds_based_on_pandas["x"]NEWLINE assert_equal(ds, ds_based_on_pandas)NEWLINENEWLINE def test_constructor_pandas_single(self):NEWLINENEWLINE das = [NEWLINE DataArray(np.random.rand(4), dims=["a"]), # seriesNEWLINE DataArray(np.random.rand(4, 3), dims=["a", "b"]), # dfNEWLINE ]NEWLINENEWLINE if LooseVersion(pd.__version__) < "0.25.0":NEWLINE das.append(DataArray(np.random.rand(4, 3, 2), dims=["a", "b", "c"]))NEWLINENEWLINE with warnings.catch_warnings():NEWLINE warnings.filterwarnings("ignore", r"\W*Panel is deprecated")NEWLINE for a in das:NEWLINE pandas_obj = a.to_pandas()NEWLINE ds_based_on_pandas = Dataset(pandas_obj)NEWLINE for dim in ds_based_on_pandas.data_vars:NEWLINE assert_array_equal(ds_based_on_pandas[dim], pandas_obj[dim])NEWLINENEWLINE def test_constructor_compat(self):NEWLINE data = {"x": DataArray(0, coords={"y": 1}), "y": ("z", [1, 1, 1])}NEWLINE expected = Dataset({"x": 0}, {"y": ("z", [1, 1, 1])})NEWLINE actual = Dataset(data)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE data = {"y": ("z", [1, 1, 1]), "x": DataArray(0, coords={"y": 1})}NEWLINE actual = Dataset(data)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE original = Dataset(NEWLINE {"a": (("x", "y"), np.ones((2, 3)))},NEWLINE {"c": (("x", "y"), np.zeros((2, 3))), "x": [0, 1]},NEWLINE )NEWLINE expected = Dataset(NEWLINE {"a": ("x", np.ones(2)), "b": ("y", np.ones(3))},NEWLINE {"c": (("x", "y"), np.zeros((2, 3))), "x": [0, 1]},NEWLINE )NEWLINENEWLINE actual = Dataset(NEWLINE {"a": original["a"][:, 0], "b": original["a"][0].drop_vars("x")}NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE data = {"x": DataArray(0, coords={"y": 3}), "y": ("z", [1, 1, 1])}NEWLINE with pytest.raises(MergeError):NEWLINE Dataset(data)NEWLINENEWLINE data = {"x": DataArray(0, coords={"y": 1}), "y": [1, 1]}NEWLINE actual = Dataset(data)NEWLINE expected = Dataset({"x": 0}, {"y": [1, 1]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_constructor_with_coords(self):NEWLINE with raises_regex(ValueError, "found in both data_vars and"):NEWLINE Dataset({"a": ("x", [1])}, {"a": ("x", [1])})NEWLINENEWLINE ds = Dataset({}, {"a": ("x", [1])})NEWLINE assert not ds.data_varsNEWLINE assert list(ds.coords.keys()) == ["a"]NEWLINENEWLINE mindex = pd.MultiIndex.from_product(NEWLINE [["a", "b"], [1, 2]], names=("level_1", "level_2")NEWLINE )NEWLINE with raises_regex(ValueError, "conflicting MultiIndex"):NEWLINE Dataset({}, {"x": mindex, "y": mindex})NEWLINE Dataset({}, {"x": mindex, "level_1": range(4)})NEWLINENEWLINE def test_properties(self):NEWLINE ds = create_test_data()NEWLINE assert ds.dims == {"dim1": 8, "dim2": 9, "dim3": 10, "time": 20}NEWLINE assert list(ds.dims) == sorted(ds.dims)NEWLINE assert ds.sizes == ds.dimsNEWLINENEWLINE # These exact types aren't public API, but this makes sure we don'tNEWLINE # change them inadvertently:NEWLINE assert isinstance(ds.dims, utils.Frozen)NEWLINE assert isinstance(ds.dims.mapping, utils.SortedKeysDict)NEWLINE assert type(ds.dims.mapping.mapping) is dictNEWLINENEWLINE assert list(ds) == list(ds.data_vars)NEWLINE assert list(ds.keys()) == list(ds.data_vars)NEWLINE assert "aasldfjalskdfj" not in ds.variablesNEWLINE assert "dim1" in repr(ds.variables)NEWLINE assert len(ds) == 3NEWLINE assert bool(ds)NEWLINENEWLINE assert list(ds.data_vars) == ["var1", "var2", "var3"]NEWLINE assert list(ds.data_vars.keys()) == ["var1", "var2", "var3"]NEWLINE assert "var1" in ds.data_varsNEWLINE assert "dim1" not in ds.data_varsNEWLINE assert "numbers" not in ds.data_varsNEWLINE assert len(ds.data_vars) == 3NEWLINENEWLINE assert set(ds.indexes) == {"dim2", "dim3", "time"}NEWLINE assert len(ds.indexes) == 3NEWLINE assert "dim2" in repr(ds.indexes)NEWLINENEWLINE assert list(ds.coords) == ["time", "dim2", "dim3", "numbers"]NEWLINE assert "dim2" in ds.coordsNEWLINE assert "numbers" in ds.coordsNEWLINE assert "var1" not in ds.coordsNEWLINE assert "dim1" not in ds.coordsNEWLINE assert len(ds.coords) == 4NEWLINENEWLINE assert Dataset({"x": np.int64(1), "y": np.float32([1, 2])}).nbytes == 16NEWLINENEWLINE def test_asarray(self):NEWLINE ds = Dataset({"x": 0})NEWLINE with raises_regex(TypeError, "cannot directly convert"):NEWLINE np.asarray(ds)NEWLINENEWLINE def test_get_index(self):NEWLINE ds = Dataset({"foo": (("x", "y"), np.zeros((2, 3)))}, coords={"x": ["a", "b"]})NEWLINE assert ds.get_index("x").equals(pd.Index(["a", "b"]))NEWLINE assert ds.get_index("y").equals(pd.Index([0, 1, 2]))NEWLINE with pytest.raises(KeyError):NEWLINE ds.get_index("z")NEWLINENEWLINE def test_attr_access(self):NEWLINE ds = Dataset(NEWLINE {"tmin": ("x", [42], {"units": "Celcius"})}, attrs={"title": "My test data"}NEWLINE )NEWLINE assert_identical(ds.tmin, ds["tmin"])NEWLINE assert_identical(ds.tmin.x, ds.x)NEWLINENEWLINE assert ds.title == ds.attrs["title"]NEWLINE assert ds.tmin.units == ds["tmin"].attrs["units"]NEWLINENEWLINE assert {"tmin", "title"} <= set(dir(ds))NEWLINE assert "units" in set(dir(ds.tmin))NEWLINENEWLINE # should defer to variable of same nameNEWLINE ds.attrs["tmin"] = -999NEWLINE assert ds.attrs["tmin"] == -999NEWLINE assert_identical(ds.tmin, ds["tmin"])NEWLINENEWLINE def test_variable(self):NEWLINE a = Dataset()NEWLINE d = np.random.random((10, 3))NEWLINE a["foo"] = (("time", "x"), d)NEWLINE assert "foo" in a.variablesNEWLINE assert "foo" in aNEWLINE a["bar"] = (("time", "x"), d)NEWLINE # order of creation is preservedNEWLINE assert list(a.variables) == ["foo", "bar"]NEWLINE assert_array_equal(a["foo"].values, d)NEWLINE # try to add variable with dim (10,3) with data that's (3,10)NEWLINE with pytest.raises(ValueError):NEWLINE a["qux"] = (("time", "x"), d.T)NEWLINENEWLINE def test_modify_inplace(self):NEWLINE a = Dataset()NEWLINE vec = np.random.random((10,))NEWLINE attributes = {"foo": "bar"}NEWLINE a["x"] = ("x", vec, attributes)NEWLINE assert "x" in a.coordsNEWLINE assert isinstance(a.coords["x"].to_index(), pd.Index)NEWLINE assert_identical(a.coords["x"].variable, a.variables["x"])NEWLINE b = Dataset()NEWLINE b["x"] = ("x", vec, attributes)NEWLINE assert_identical(a["x"], b["x"])NEWLINE assert a.dims == b.dimsNEWLINE # this should workNEWLINE a["x"] = ("x", vec[:5])NEWLINE a["z"] = ("x", np.arange(5))NEWLINE with pytest.raises(ValueError):NEWLINE # now it shouldn't, since there is a conflicting lengthNEWLINE a["x"] = ("x", vec[:4])NEWLINE arr = np.random.random((10, 1))NEWLINE scal = np.array(0)NEWLINE with pytest.raises(ValueError):NEWLINE a["y"] = ("y", arr)NEWLINE with pytest.raises(ValueError):NEWLINE a["y"] = ("y", scal)NEWLINE assert "y" not in a.dimsNEWLINENEWLINE def test_coords_properties(self):NEWLINE # use int64 for repr consistency on windowsNEWLINE data = Dataset(NEWLINE {NEWLINE "x": ("x", np.array([-1, -2], "int64")),NEWLINE "y": ("y", np.array([0, 1, 2], "int64")),NEWLINE "foo": (["x", "y"], np.random.randn(2, 3)),NEWLINE },NEWLINE {"a": ("x", np.array([4, 5], "int64")), "b": np.int64(-10)},NEWLINE )NEWLINENEWLINE assert 4 == len(data.coords)NEWLINENEWLINE assert ["x", "y", "a", "b"] == list(data.coords)NEWLINENEWLINE assert_identical(data.coords["x"].variable, data["x"].variable)NEWLINE assert_identical(data.coords["y"].variable, data["y"].variable)NEWLINENEWLINE assert "x" in data.coordsNEWLINE assert "a" in data.coordsNEWLINE assert 0 not in data.coordsNEWLINE assert "foo" not in data.coordsNEWLINENEWLINE with pytest.raises(KeyError):NEWLINE data.coords["foo"]NEWLINE with pytest.raises(KeyError):NEWLINE data.coords[0]NEWLINENEWLINE expected = dedent(NEWLINE """\NEWLINE Coordinates:NEWLINE * x (x) int64 -1 -2NEWLINE * y (y) int64 0 1 2NEWLINE a (x) int64 4 5NEWLINE b int64 -10"""NEWLINE )NEWLINE actual = repr(data.coords)NEWLINE assert expected == actualNEWLINENEWLINE assert {"x": 2, "y": 3} == data.coords.dimsNEWLINENEWLINE def test_coords_modify(self):NEWLINE data = Dataset(NEWLINE {NEWLINE "x": ("x", [-1, -2]),NEWLINE "y": ("y", [0, 1, 2]),NEWLINE "foo": (["x", "y"], np.random.randn(2, 3)),NEWLINE },NEWLINE {"a": ("x", [4, 5]), "b": -10},NEWLINE )NEWLINENEWLINE actual = data.copy(deep=True)NEWLINE actual.coords["x"] = ("x", ["a", "b"])NEWLINE assert_array_equal(actual["x"], ["a", "b"])NEWLINENEWLINE actual = data.copy(deep=True)NEWLINE actual.coords["z"] = ("z", ["a", "b"])NEWLINE assert_array_equal(actual["z"], ["a", "b"])NEWLINENEWLINE actual = data.copy(deep=True)NEWLINE with raises_regex(ValueError, "conflicting sizes"):NEWLINE actual.coords["x"] = ("x", [-1])NEWLINE assert_identical(actual, data) # should not be modifiedNEWLINENEWLINE actual = data.copy()NEWLINE del actual.coords["b"]NEWLINE expected = data.reset_coords("b", drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE del data.coords["not_found"]NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE del data.coords["foo"]NEWLINENEWLINE actual = data.copy(deep=True)NEWLINE actual.coords.update({"c": 11})NEWLINE expected = data.merge({"c": 11}).set_coords("c")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_update_index(self):NEWLINE actual = Dataset(coords={"x": [1, 2, 3]})NEWLINE actual["x"] = ["a", "b", "c"]NEWLINE assert actual.indexes["x"].equals(pd.Index(["a", "b", "c"]))NEWLINENEWLINE def test_coords_setitem_with_new_dimension(self):NEWLINE actual = Dataset()NEWLINE actual.coords["foo"] = ("x", [1, 2, 3])NEWLINE expected = Dataset(coords={"foo": ("x", [1, 2, 3])})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_coords_setitem_multiindex(self):NEWLINE data = create_test_multiindex()NEWLINE with raises_regex(ValueError, "conflicting MultiIndex"):NEWLINE data.coords["level_1"] = range(4)NEWLINENEWLINE def test_coords_set(self):NEWLINE one_coord = Dataset({"x": ("x", [0]), "yy": ("x", [1]), "zzz": ("x", [2])})NEWLINE two_coords = Dataset({"zzz": ("x", [2])}, {"x": ("x", [0]), "yy": ("x", [1])})NEWLINE all_coords = Dataset(NEWLINE coords={"x": ("x", [0]), "yy": ("x", [1]), "zzz": ("x", [2])}NEWLINE )NEWLINENEWLINE actual = one_coord.set_coords("x")NEWLINE assert_identical(one_coord, actual)NEWLINE actual = one_coord.set_coords(["x"])NEWLINE assert_identical(one_coord, actual)NEWLINENEWLINE actual = one_coord.set_coords("yy")NEWLINE assert_identical(two_coords, actual)NEWLINENEWLINE actual = one_coord.set_coords(["yy", "zzz"])NEWLINE assert_identical(all_coords, actual)NEWLINENEWLINE actual = one_coord.reset_coords()NEWLINE assert_identical(one_coord, actual)NEWLINE actual = two_coords.reset_coords()NEWLINE assert_identical(one_coord, actual)NEWLINE actual = all_coords.reset_coords()NEWLINE assert_identical(one_coord, actual)NEWLINENEWLINE actual = all_coords.reset_coords(["yy", "zzz"])NEWLINE assert_identical(one_coord, actual)NEWLINE actual = all_coords.reset_coords("zzz")NEWLINE assert_identical(two_coords, actual)NEWLINENEWLINE with raises_regex(ValueError, "cannot remove index"):NEWLINE one_coord.reset_coords("x")NEWLINENEWLINE actual = all_coords.reset_coords("zzz", drop=True)NEWLINE expected = all_coords.drop_vars("zzz")NEWLINE assert_identical(expected, actual)NEWLINE expected = two_coords.drop_vars("zzz")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_coords_to_dataset(self):NEWLINE orig = Dataset({"foo": ("y", [-1, 0, 1])}, {"x": 10, "y": [2, 3, 4]})NEWLINE expected = Dataset(coords={"x": 10, "y": [2, 3, 4]})NEWLINE actual = orig.coords.to_dataset()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_coords_merge(self):NEWLINE orig_coords = Dataset(coords={"a": ("x", [1, 2]), "x": [0, 1]}).coordsNEWLINE other_coords = Dataset(coords={"b": ("x", ["a", "b"]), "x": [0, 1]}).coordsNEWLINE expected = Dataset(NEWLINE coords={"a": ("x", [1, 2]), "b": ("x", ["a", "b"]), "x": [0, 1]}NEWLINE )NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINE actual = other_coords.merge(orig_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE other_coords = Dataset(coords={"x": ("x", ["a"])}).coordsNEWLINE with pytest.raises(MergeError):NEWLINE orig_coords.merge(other_coords)NEWLINE other_coords = Dataset(coords={"x": ("x", ["a", "b"])}).coordsNEWLINE with pytest.raises(MergeError):NEWLINE orig_coords.merge(other_coords)NEWLINE other_coords = Dataset(coords={"x": ("x", ["a", "b", "c"])}).coordsNEWLINE with pytest.raises(MergeError):NEWLINE orig_coords.merge(other_coords)NEWLINENEWLINE other_coords = Dataset(coords={"a": ("x", [8, 9])}).coordsNEWLINE expected = Dataset(coords={"x": range(2)})NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINE actual = other_coords.merge(orig_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE other_coords = Dataset(coords={"x": np.nan}).coordsNEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(orig_coords.to_dataset(), actual)NEWLINE actual = other_coords.merge(orig_coords)NEWLINE assert_identical(orig_coords.to_dataset(), actual)NEWLINENEWLINE def test_coords_merge_mismatched_shape(self):NEWLINE orig_coords = Dataset(coords={"a": ("x", [1, 1])}).coordsNEWLINE other_coords = Dataset(coords={"a": 1}).coordsNEWLINE expected = orig_coords.to_dataset()NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE other_coords = Dataset(coords={"a": ("y", [1])}).coordsNEWLINE expected = Dataset(coords={"a": (["x", "y"], [[1], [1]])})NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = other_coords.merge(orig_coords)NEWLINE assert_identical(expected.transpose(), actual)NEWLINENEWLINE orig_coords = Dataset(coords={"a": ("x", [np.nan])}).coordsNEWLINE other_coords = Dataset(coords={"a": np.nan}).coordsNEWLINE expected = orig_coords.to_dataset()NEWLINE actual = orig_coords.merge(other_coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_data_vars_properties(self):NEWLINE ds = Dataset()NEWLINE ds["foo"] = (("x",), [1.0])NEWLINE ds["bar"] = 2.0NEWLINENEWLINE assert set(ds.data_vars) == {"foo", "bar"}NEWLINE assert "foo" in ds.data_varsNEWLINE assert "x" not in ds.data_varsNEWLINE assert_identical(ds["foo"], ds.data_vars["foo"])NEWLINENEWLINE expected = dedent(NEWLINE """\NEWLINE Data variables:NEWLINE foo (x) float64 1.0NEWLINE bar float64 2.0"""NEWLINE )NEWLINE actual = repr(ds.data_vars)NEWLINE assert expected == actualNEWLINENEWLINE def test_equals_and_identical(self):NEWLINE data = create_test_data(seed=42)NEWLINE assert data.equals(data)NEWLINE assert data.identical(data)NEWLINENEWLINE data2 = create_test_data(seed=42)NEWLINE data2.attrs["foobar"] = "baz"NEWLINE assert data.equals(data2)NEWLINE assert not data.identical(data2)NEWLINENEWLINE del data2["time"]NEWLINE assert not data.equals(data2)NEWLINENEWLINE data = create_test_data(seed=42).rename({"var1": None})NEWLINE assert data.equals(data)NEWLINE assert data.identical(data)NEWLINENEWLINE data2 = data.reset_coords()NEWLINE assert not data2.equals(data)NEWLINE assert not data2.identical(data)NEWLINENEWLINE def test_equals_failures(self):NEWLINE data = create_test_data()NEWLINE assert not data.equals("foo")NEWLINE assert not data.identical(123)NEWLINE assert not data.broadcast_equals({1: 2})NEWLINENEWLINE def test_broadcast_equals(self):NEWLINE data1 = Dataset(coords={"x": 0})NEWLINE data2 = Dataset(coords={"x": [0]})NEWLINE assert data1.broadcast_equals(data2)NEWLINE assert not data1.equals(data2)NEWLINE assert not data1.identical(data2)NEWLINENEWLINE def test_attrs(self):NEWLINE data = create_test_data(seed=42)NEWLINE data.attrs = {"foobar": "baz"}NEWLINE assert data.attrs["foobar"], "baz"NEWLINE assert isinstance(data.attrs, dict)NEWLINENEWLINE @requires_daskNEWLINE def test_chunk(self):NEWLINE data = create_test_data()NEWLINE for v in data.variables.values():NEWLINE assert isinstance(v.data, np.ndarray)NEWLINE assert data.chunks == {}NEWLINENEWLINE reblocked = data.chunk()NEWLINE for k, v in reblocked.variables.items():NEWLINE if k in reblocked.dims:NEWLINE assert isinstance(v.data, np.ndarray)NEWLINE else:NEWLINE assert isinstance(v.data, da.Array)NEWLINENEWLINE expected_chunks = {"dim1": (8,), "dim2": (9,), "dim3": (10,)}NEWLINE assert reblocked.chunks == expected_chunksNEWLINENEWLINE reblocked = data.chunk({"time": 5, "dim1": 5, "dim2": 5, "dim3": 5})NEWLINE # time is not a dim in any of the data_vars, so itNEWLINE # doesn't get chunkedNEWLINE expected_chunks = {"dim1": (5, 3), "dim2": (5, 4), "dim3": (5, 5)}NEWLINE assert reblocked.chunks == expected_chunksNEWLINENEWLINE reblocked = data.chunk(expected_chunks)NEWLINE assert reblocked.chunks == expected_chunksNEWLINENEWLINE # reblock on already blocked dataNEWLINE reblocked = reblocked.chunk(expected_chunks)NEWLINE assert reblocked.chunks == expected_chunksNEWLINE assert_identical(reblocked, data)NEWLINENEWLINE with raises_regex(ValueError, "some chunks"):NEWLINE data.chunk({"foo": 10})NEWLINENEWLINE @requires_daskNEWLINE def test_dask_is_lazy(self):NEWLINE store = InaccessibleVariableDataStore()NEWLINE create_test_data().dump_to_store(store)NEWLINE ds = open_dataset(store).chunk()NEWLINENEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE ds.load()NEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE ds["var1"].valuesNEWLINENEWLINE # these should not raise UnexpectedDataAccess:NEWLINE ds.var1.dataNEWLINE ds.isel(time=10)NEWLINE ds.isel(time=slice(10), dim1=[0]).isel(dim1=0, dim2=-1)NEWLINE ds.transpose()NEWLINE ds.mean()NEWLINE ds.fillna(0)NEWLINE ds.rename({"dim1": "foobar"})NEWLINE ds.set_coords("var1")NEWLINE ds.drop_vars("var1")NEWLINENEWLINE def test_isel(self):NEWLINE data = create_test_data()NEWLINE slicers = {"dim1": slice(None, None, 2), "dim2": slice(0, 2)}NEWLINE ret = data.isel(**slicers)NEWLINENEWLINE # Verify that only the specified dimension was alteredNEWLINE assert list(data.dims) == list(ret.dims)NEWLINE for d in data.dims:NEWLINE if d in slicers:NEWLINE assert ret.dims[d] == np.arange(data.dims[d])[slicers[d]].sizeNEWLINE else:NEWLINE assert data.dims[d] == ret.dims[d]NEWLINE # Verify that the data is what we expectNEWLINE for v in data.variables:NEWLINE assert data[v].dims == ret[v].dimsNEWLINE assert data[v].attrs == ret[v].attrsNEWLINE slice_list = [slice(None)] * data[v].values.ndimNEWLINE for d, s in slicers.items():NEWLINE if d in data[v].dims:NEWLINE inds = np.nonzero(np.array(data[v].dims) == d)[0]NEWLINE for ind in inds:NEWLINE slice_list[ind] = sNEWLINE expected = data[v].values[tuple(slice_list)]NEWLINE actual = ret[v].valuesNEWLINE np.testing.assert_array_equal(expected, actual)NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE data.isel(not_a_dim=slice(0, 2))NEWLINENEWLINE ret = data.isel(dim1=0)NEWLINE assert {"time": 20, "dim2": 9, "dim3": 10} == ret.dimsNEWLINE assert set(data.data_vars) == set(ret.data_vars)NEWLINE assert set(data.coords) == set(ret.coords)NEWLINE assert set(data.indexes) == set(ret.indexes)NEWLINENEWLINE ret = data.isel(time=slice(2), dim1=0, dim2=slice(5))NEWLINE assert {"time": 2, "dim2": 5, "dim3": 10} == ret.dimsNEWLINE assert set(data.data_vars) == set(ret.data_vars)NEWLINE assert set(data.coords) == set(ret.coords)NEWLINE assert set(data.indexes) == set(ret.indexes)NEWLINENEWLINE ret = data.isel(time=0, dim1=0, dim2=slice(5))NEWLINE assert {"dim2": 5, "dim3": 10} == ret.dimsNEWLINE assert set(data.data_vars) == set(ret.data_vars)NEWLINE assert set(data.coords) == set(ret.coords)NEWLINE assert set(data.indexes) == set(list(ret.indexes) + ["time"])NEWLINENEWLINE def test_isel_fancy(self):NEWLINE # isel with fancy indexing.NEWLINE data = create_test_data()NEWLINENEWLINE pdim1 = [1, 2, 3]NEWLINE pdim2 = [4, 5, 1]NEWLINE pdim3 = [1, 2, 3]NEWLINE actual = data.isel(NEWLINE dim1=(("test_coord",), pdim1),NEWLINE dim2=(("test_coord",), pdim2),NEWLINE dim3=(("test_coord",), pdim3),NEWLINE )NEWLINE assert "test_coord" in actual.dimsNEWLINE assert actual.coords["test_coord"].shape == (len(pdim1),)NEWLINENEWLINE # Should work with DataArrayNEWLINE actual = data.isel(NEWLINE dim1=DataArray(pdim1, dims="test_coord"),NEWLINE dim2=(("test_coord",), pdim2),NEWLINE dim3=(("test_coord",), pdim3),NEWLINE )NEWLINE assert "test_coord" in actual.dimsNEWLINE assert actual.coords["test_coord"].shape == (len(pdim1),)NEWLINE expected = data.isel(NEWLINE dim1=(("test_coord",), pdim1),NEWLINE dim2=(("test_coord",), pdim2),NEWLINE dim3=(("test_coord",), pdim3),NEWLINE )NEWLINE assert_identical(actual, expected)NEWLINENEWLINE # DataArray with coordinateNEWLINE idx1 = DataArray(pdim1, dims=["a"], coords={"a": np.random.randn(3)})NEWLINE idx2 = DataArray(pdim2, dims=["b"], coords={"b": np.random.randn(3)})NEWLINE idx3 = DataArray(pdim3, dims=["c"], coords={"c": np.random.randn(3)})NEWLINE # Should work with DataArrayNEWLINE actual = data.isel(dim1=idx1, dim2=idx2, dim3=idx3)NEWLINE assert "a" in actual.dimsNEWLINE assert "b" in actual.dimsNEWLINE assert "c" in actual.dimsNEWLINE assert "time" in actual.coordsNEWLINE assert "dim2" in actual.coordsNEWLINE assert "dim3" in actual.coordsNEWLINE expected = data.isel(NEWLINE dim1=(("a",), pdim1), dim2=(("b",), pdim2), dim3=(("c",), pdim3)NEWLINE )NEWLINE expected = expected.assign_coords(a=idx1["a"], b=idx2["b"], c=idx3["c"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE idx1 = DataArray(pdim1, dims=["a"], coords={"a": np.random.randn(3)})NEWLINE idx2 = DataArray(pdim2, dims=["a"])NEWLINE idx3 = DataArray(pdim3, dims=["a"])NEWLINE # Should work with DataArrayNEWLINE actual = data.isel(dim1=idx1, dim2=idx2, dim3=idx3)NEWLINE assert "a" in actual.dimsNEWLINE assert "time" in actual.coordsNEWLINE assert "dim2" in actual.coordsNEWLINE assert "dim3" in actual.coordsNEWLINE expected = data.isel(NEWLINE dim1=(("a",), pdim1), dim2=(("a",), pdim2), dim3=(("a",), pdim3)NEWLINE )NEWLINE expected = expected.assign_coords(a=idx1["a"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = data.isel(dim1=(("points",), pdim1), dim2=(("points",), pdim2))NEWLINE assert "points" in actual.dimsNEWLINE assert "dim3" in actual.dimsNEWLINE assert "dim3" not in actual.data_varsNEWLINE np.testing.assert_array_equal(data["dim2"][pdim2], actual["dim2"])NEWLINENEWLINE # test that the order of the indexers doesn't matterNEWLINE assert_identical(NEWLINE data.isel(dim1=(("points",), pdim1), dim2=(("points",), pdim2)),NEWLINE data.isel(dim2=(("points",), pdim2), dim1=(("points",), pdim1)),NEWLINE )NEWLINE # make sure we're raising errors in the right placesNEWLINE with raises_regex(IndexError, "Dimensions of indexers mismatch"):NEWLINE data.isel(dim1=(("points",), [1, 2]), dim2=(("points",), [1, 2, 3]))NEWLINE with raises_regex(TypeError, "cannot use a Dataset"):NEWLINE data.isel(dim1=Dataset({"points": [1, 2]}))NEWLINENEWLINE # test to be sure we keep around variables that were not indexedNEWLINE ds = Dataset({"x": [1, 2, 3, 4], "y": 0})NEWLINE actual = ds.isel(x=(("points",), [0, 1, 2]))NEWLINE assert_identical(ds["y"], actual["y"])NEWLINENEWLINE # tests using index or DataArray as indexersNEWLINE stations = Dataset()NEWLINE stations["station"] = (("station",), ["A", "B", "C"])NEWLINE stations["dim1s"] = (("station",), [1, 2, 3])NEWLINE stations["dim2s"] = (("station",), [4, 5, 1])NEWLINENEWLINE actual = data.isel(dim1=stations["dim1s"], dim2=stations["dim2s"])NEWLINE assert "station" in actual.coordsNEWLINE assert "station" in actual.dimsNEWLINE assert_identical(actual["station"].drop_vars(["dim2"]), stations["station"])NEWLINENEWLINE with raises_regex(ValueError, "conflicting values for "):NEWLINE data.isel(NEWLINE dim1=DataArray(NEWLINE [0, 1, 2], dims="station", coords={"station": [0, 1, 2]}NEWLINE ),NEWLINE dim2=DataArray(NEWLINE [0, 1, 2], dims="station", coords={"station": [0, 1, 3]}NEWLINE ),NEWLINE )NEWLINENEWLINE # multi-dimensional selectionNEWLINE stations = Dataset()NEWLINE stations["a"] = (("a",), ["A", "B", "C"])NEWLINE stations["b"] = (("b",), [0, 1])NEWLINE stations["dim1s"] = (("a", "b"), [[1, 2], [2, 3], [3, 4]])NEWLINE stations["dim2s"] = (("a",), [4, 5, 1])NEWLINE actual = data.isel(dim1=stations["dim1s"], dim2=stations["dim2s"])NEWLINE assert "a" in actual.coordsNEWLINE assert "a" in actual.dimsNEWLINE assert "b" in actual.coordsNEWLINE assert "b" in actual.dimsNEWLINE assert "dim2" in actual.coordsNEWLINE assert "a" in actual["dim2"].dimsNEWLINENEWLINE assert_identical(actual["a"].drop_vars(["dim2"]), stations["a"])NEWLINE assert_identical(actual["b"], stations["b"])NEWLINE expected_var1 = data["var1"].variable[NEWLINE stations["dim1s"].variable, stations["dim2s"].variableNEWLINE ]NEWLINE expected_var2 = data["var2"].variable[NEWLINE stations["dim1s"].variable, stations["dim2s"].variableNEWLINE ]NEWLINE expected_var3 = data["var3"].variable[slice(None), stations["dim1s"].variable]NEWLINE assert_equal(actual["a"].drop_vars("dim2"), stations["a"])NEWLINE assert_array_equal(actual["var1"], expected_var1)NEWLINE assert_array_equal(actual["var2"], expected_var2)NEWLINE assert_array_equal(actual["var3"], expected_var3)NEWLINENEWLINE def test_isel_dataarray(self):NEWLINE """ Test for indexing by DataArray """NEWLINE data = create_test_data()NEWLINE # indexing with DataArray with same-name coordinates.NEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4), dims=["dim1"], coords={"dim1": np.random.randn(3)}NEWLINE )NEWLINE actual = data.isel(dim1=indexing_da)NEWLINE assert_identical(indexing_da["dim1"], actual["dim1"])NEWLINE assert_identical(data["dim2"], actual["dim2"])NEWLINENEWLINE # Conflict in the dimension coordinateNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4), dims=["dim2"], coords={"dim2": np.random.randn(3)}NEWLINE )NEWLINE with raises_regex(IndexError, "dimension coordinate 'dim2'"):NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE # Also the case for DataArrayNEWLINE with raises_regex(IndexError, "dimension coordinate 'dim2'"):NEWLINE actual = data["var2"].isel(dim2=indexing_da)NEWLINE with raises_regex(IndexError, "dimension coordinate 'dim2'"):NEWLINE data["dim2"].isel(dim2=indexing_da)NEWLINENEWLINE # same name coordinate which does not conflictNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4), dims=["dim2"], coords={"dim2": data["dim2"].values[1:4]}NEWLINE )NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert_identical(actual["dim2"], indexing_da["dim2"])NEWLINENEWLINE # Silently drop conflicted (non-dimensional) coordinate of indexerNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4),NEWLINE dims=["dim2"],NEWLINE coords={NEWLINE "dim2": data["dim2"].values[1:4],NEWLINE "numbers": ("dim2", np.arange(2, 5)),NEWLINE },NEWLINE )NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert_identical(actual["numbers"], data["numbers"])NEWLINENEWLINE # boolean data array with coordinate with the same nameNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 10), dims=["dim2"], coords={"dim2": data["dim2"].values}NEWLINE )NEWLINE indexing_da = indexing_da < 3NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert_identical(actual["dim2"], data["dim2"][:2])NEWLINENEWLINE # boolean data array with non-dimensioncoordinateNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 10),NEWLINE dims=["dim2"],NEWLINE coords={NEWLINE "dim2": data["dim2"].values,NEWLINE "non_dim": (("dim2",), np.random.randn(9)),NEWLINE "non_dim2": 0,NEWLINE },NEWLINE )NEWLINE indexing_da = indexing_da < 3NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert_identical(NEWLINE actual["dim2"].drop_vars("non_dim").drop_vars("non_dim2"), data["dim2"][:2]NEWLINE )NEWLINE assert_identical(actual["non_dim"], indexing_da["non_dim"][:2])NEWLINE assert_identical(actual["non_dim2"], indexing_da["non_dim2"])NEWLINENEWLINE # non-dimension coordinate will be also attachedNEWLINE indexing_da = DataArray(NEWLINE np.arange(1, 4),NEWLINE dims=["dim2"],NEWLINE coords={"non_dim": (("dim2",), np.random.randn(3))},NEWLINE )NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert "non_dim" in actualNEWLINE assert "non_dim" in actual.coordsNEWLINENEWLINE # Index by a scalar DataArrayNEWLINE indexing_da = DataArray(3, dims=[], coords={"station": 2})NEWLINE actual = data.isel(dim2=indexing_da)NEWLINE assert "station" in actualNEWLINE actual = data.isel(dim2=indexing_da["station"])NEWLINE assert "station" in actualNEWLINENEWLINE # indexer generated from coordinatesNEWLINE indexing_ds = Dataset({}, coords={"dim2": [0, 1, 2]})NEWLINE with raises_regex(IndexError, "dimension coordinate 'dim2'"):NEWLINE actual = data.isel(dim2=indexing_ds["dim2"])NEWLINENEWLINE def test_sel(self):NEWLINE data = create_test_data()NEWLINE int_slicers = {"dim1": slice(None, None, 2), "dim2": slice(2), "dim3": slice(3)}NEWLINE loc_slicers = {NEWLINE "dim1": slice(None, None, 2),NEWLINE "dim2": slice(0, 0.5),NEWLINE "dim3": slice("a", "c"),NEWLINE }NEWLINE assert_equal(data.isel(**int_slicers), data.sel(**loc_slicers))NEWLINE data["time"] = ("time", pd.date_range("2000-01-01", periods=20))NEWLINE assert_equal(data.isel(time=0), data.sel(time="2000-01-01"))NEWLINE assert_equal(NEWLINE data.isel(time=slice(10)), data.sel(time=slice("2000-01-01", "2000-01-10"))NEWLINE )NEWLINE assert_equal(data, data.sel(time=slice("1999", "2005")))NEWLINE times = pd.date_range("2000-01-01", periods=3)NEWLINE assert_equal(data.isel(time=slice(3)), data.sel(time=times))NEWLINE assert_equal(NEWLINE data.isel(time=slice(3)), data.sel(time=(data["time.dayofyear"] <= 3))NEWLINE )NEWLINENEWLINE td = pd.to_timedelta(np.arange(3), unit="days")NEWLINE data = Dataset({"x": ("td", np.arange(3)), "td": td})NEWLINE assert_equal(data, data.sel(td=td))NEWLINE assert_equal(data, data.sel(td=slice("3 days")))NEWLINE assert_equal(data.isel(td=0), data.sel(td=pd.Timedelta("0 days")))NEWLINE assert_equal(data.isel(td=0), data.sel(td=pd.Timedelta("0h")))NEWLINE assert_equal(data.isel(td=slice(1, 3)), data.sel(td=slice("1 days", "2 days")))NEWLINENEWLINE def test_sel_dataarray(self):NEWLINE data = create_test_data()NEWLINENEWLINE ind = DataArray([0.0, 0.5, 1.0], dims=["dim2"])NEWLINE actual = data.sel(dim2=ind)NEWLINE assert_equal(actual, data.isel(dim2=[0, 1, 2]))NEWLINENEWLINE # with different dimensionNEWLINE ind = DataArray([0.0, 0.5, 1.0], dims=["new_dim"])NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=Variable("new_dim", [0, 1, 2]))NEWLINE assert "new_dim" in actual.dimsNEWLINE assert_equal(actual, expected)NEWLINENEWLINE # Multi-dimensionalNEWLINE ind = DataArray([[0.0], [0.5], [1.0]], dims=["new_dim", "new_dim2"])NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=Variable(("new_dim", "new_dim2"), [[0], [1], [2]]))NEWLINE assert "new_dim" in actual.dimsNEWLINE assert "new_dim2" in actual.dimsNEWLINE assert_equal(actual, expected)NEWLINENEWLINE # with coordinateNEWLINE ind = DataArray(NEWLINE [0.0, 0.5, 1.0], dims=["new_dim"], coords={"new_dim": ["a", "b", "c"]}NEWLINE )NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=[0, 1, 2]).rename({"dim2": "new_dim"})NEWLINE assert "new_dim" in actual.dimsNEWLINE assert "new_dim" in actual.coordsNEWLINE assert_equal(NEWLINE actual.drop_vars("new_dim").drop_vars("dim2"), expected.drop_vars("new_dim")NEWLINE )NEWLINE assert_equal(actual["new_dim"].drop_vars("dim2"), ind["new_dim"])NEWLINENEWLINE # with conflicted coordinate (silently ignored)NEWLINE ind = DataArray(NEWLINE [0.0, 0.5, 1.0], dims=["dim2"], coords={"dim2": ["a", "b", "c"]}NEWLINE )NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=[0, 1, 2])NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # with conflicted coordinate (silently ignored)NEWLINE ind = DataArray(NEWLINE [0.0, 0.5, 1.0],NEWLINE dims=["new_dim"],NEWLINE coords={"new_dim": ["a", "b", "c"], "dim2": 3},NEWLINE )NEWLINE actual = data.sel(dim2=ind)NEWLINE assert_equal(NEWLINE actual["new_dim"].drop_vars("dim2"), ind["new_dim"].drop_vars("dim2")NEWLINE )NEWLINE expected = data.isel(dim2=[0, 1, 2])NEWLINE expected["dim2"] = (("new_dim"), expected["dim2"].values)NEWLINE assert_equal(actual["dim2"].drop_vars("new_dim"), expected["dim2"])NEWLINE assert actual["var1"].dims == ("dim1", "new_dim")NEWLINENEWLINE # with non-dimensional coordinateNEWLINE ind = DataArray(NEWLINE [0.0, 0.5, 1.0],NEWLINE dims=["dim2"],NEWLINE coords={NEWLINE "dim2": ["a", "b", "c"],NEWLINE "numbers": ("dim2", [0, 1, 2]),NEWLINE "new_dim": ("dim2", [1.1, 1.2, 1.3]),NEWLINE },NEWLINE )NEWLINE actual = data.sel(dim2=ind)NEWLINE expected = data.isel(dim2=[0, 1, 2])NEWLINE assert_equal(actual.drop_vars("new_dim"), expected)NEWLINE assert np.allclose(actual["new_dim"].values, ind["new_dim"].values)NEWLINENEWLINE def test_sel_dataarray_mindex(self):NEWLINE midx = pd.MultiIndex.from_product([list("abc"), [0, 1]], names=("one", "two"))NEWLINE mds = xr.Dataset(NEWLINE {"var": (("x", "y"), np.random.rand(6, 3))},NEWLINE coords={"x": midx, "y": range(3)},NEWLINE )NEWLINENEWLINE actual_isel = mds.isel(x=xr.DataArray(np.arange(3), dims="x"))NEWLINE actual_sel = mds.sel(x=DataArray(mds.indexes["x"][:3], dims="x"))NEWLINE assert actual_isel["x"].dims == ("x",)NEWLINE assert actual_sel["x"].dims == ("x",)NEWLINE assert_identical(actual_isel, actual_sel)NEWLINENEWLINE actual_isel = mds.isel(x=xr.DataArray(np.arange(3), dims="z"))NEWLINE actual_sel = mds.sel(x=Variable("z", mds.indexes["x"][:3]))NEWLINE assert actual_isel["x"].dims == ("z",)NEWLINE assert actual_sel["x"].dims == ("z",)NEWLINE assert_identical(actual_isel, actual_sel)NEWLINENEWLINE # with coordinateNEWLINE actual_isel = mds.isel(NEWLINE x=xr.DataArray(np.arange(3), dims="z", coords={"z": [0, 1, 2]})NEWLINE )NEWLINE actual_sel = mds.sel(NEWLINE x=xr.DataArray(mds.indexes["x"][:3], dims="z", coords={"z": [0, 1, 2]})NEWLINE )NEWLINE assert actual_isel["x"].dims == ("z",)NEWLINE assert actual_sel["x"].dims == ("z",)NEWLINE assert_identical(actual_isel, actual_sel)NEWLINENEWLINE # Vectorized indexing with level-variables raises an errorNEWLINE with raises_regex(ValueError, "Vectorized selection is "):NEWLINE mds.sel(one=["a", "b"])NEWLINENEWLINE with raises_regex(NEWLINE ValueError,NEWLINE "Vectorized selection is " "not available along MultiIndex variable:" " x",NEWLINE ):NEWLINE mds.sel(NEWLINE x=xr.DataArray(NEWLINE [np.array(midx[:2]), np.array(midx[-2:])], dims=["a", "b"]NEWLINE )NEWLINE )NEWLINENEWLINE def test_sel_drop(self):NEWLINE data = Dataset({"foo": ("x", [1, 2, 3])}, {"x": [0, 1, 2]})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.sel(x=0, drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE expected = Dataset({"foo": 1}, {"x": 0})NEWLINE selected = data.sel(x=0, drop=False)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE data = Dataset({"foo": ("x", [1, 2, 3])})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.sel(x=0, drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE def test_isel_drop(self):NEWLINE data = Dataset({"foo": ("x", [1, 2, 3])}, {"x": [0, 1, 2]})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.isel(x=0, drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE expected = Dataset({"foo": 1}, {"x": 0})NEWLINE selected = data.isel(x=0, drop=False)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE def test_head(self):NEWLINE data = create_test_data()NEWLINENEWLINE expected = data.isel(time=slice(5), dim2=slice(6))NEWLINE actual = data.head(time=5, dim2=6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel(time=slice(0))NEWLINE actual = data.head(time=0)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(6) for dim in data.dims})NEWLINE actual = data.head(6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(5) for dim in data.dims})NEWLINE actual = data.head()NEWLINE assert_equal(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "either dict-like or a single int"):NEWLINE data.head([3])NEWLINE with raises_regex(TypeError, "expected integer type"):NEWLINE data.head(dim2=3.1)NEWLINE with raises_regex(ValueError, "expected positive int"):NEWLINE data.head(time=-3)NEWLINENEWLINE def test_tail(self):NEWLINE data = create_test_data()NEWLINENEWLINE expected = data.isel(time=slice(-5, None), dim2=slice(-6, None))NEWLINE actual = data.tail(time=5, dim2=6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel(dim1=slice(0))NEWLINE actual = data.tail(dim1=0)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(-6, None) for dim in data.dims})NEWLINE actual = data.tail(6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(-5, None) for dim in data.dims})NEWLINE actual = data.tail()NEWLINE assert_equal(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "either dict-like or a single int"):NEWLINE data.tail([3])NEWLINE with raises_regex(TypeError, "expected integer type"):NEWLINE data.tail(dim2=3.1)NEWLINE with raises_regex(ValueError, "expected positive int"):NEWLINE data.tail(time=-3)NEWLINENEWLINE def test_thin(self):NEWLINE data = create_test_data()NEWLINENEWLINE expected = data.isel(time=slice(None, None, 5), dim2=slice(None, None, 6))NEWLINE actual = data.thin(time=5, dim2=6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE expected = data.isel({dim: slice(None, None, 6) for dim in data.dims})NEWLINE actual = data.thin(6)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "either dict-like or a single int"):NEWLINE data.thin([3])NEWLINE with raises_regex(TypeError, "expected integer type"):NEWLINE data.thin(dim2=3.1)NEWLINE with raises_regex(ValueError, "cannot be zero"):NEWLINE data.thin(time=0)NEWLINE with raises_regex(ValueError, "expected positive int"):NEWLINE data.thin(time=-3)NEWLINENEWLINE @pytest.mark.filterwarnings("ignore::DeprecationWarning")NEWLINE def test_sel_fancy(self):NEWLINE data = create_test_data()NEWLINENEWLINE # add in a range() indexNEWLINE data["dim1"] = data.dim1NEWLINENEWLINE pdim1 = [1, 2, 3]NEWLINE pdim2 = [4, 5, 1]NEWLINE pdim3 = [1, 2, 3]NEWLINE expected = data.isel(NEWLINE dim1=Variable(("test_coord",), pdim1),NEWLINE dim2=Variable(("test_coord",), pdim2),NEWLINE dim3=Variable(("test_coord"), pdim3),NEWLINE )NEWLINE actual = data.sel(NEWLINE dim1=Variable(("test_coord",), data.dim1[pdim1]),NEWLINE dim2=Variable(("test_coord",), data.dim2[pdim2]),NEWLINE dim3=Variable(("test_coord",), data.dim3[pdim3]),NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # DataArray IndexerNEWLINE idx_t = DataArray(NEWLINE data["time"][[3, 2, 1]].values, dims=["a"], coords={"a": ["a", "b", "c"]}NEWLINE )NEWLINE idx_2 = DataArray(NEWLINE data["dim2"][[3, 2, 1]].values, dims=["a"], coords={"a": ["a", "b", "c"]}NEWLINE )NEWLINE idx_3 = DataArray(NEWLINE data["dim3"][[3, 2, 1]].values, dims=["a"], coords={"a": ["a", "b", "c"]}NEWLINE )NEWLINE actual = data.sel(time=idx_t, dim2=idx_2, dim3=idx_3)NEWLINE expected = data.isel(NEWLINE time=Variable(("a",), [3, 2, 1]),NEWLINE dim2=Variable(("a",), [3, 2, 1]),NEWLINE dim3=Variable(("a",), [3, 2, 1]),NEWLINE )NEWLINE expected = expected.assign_coords(a=idx_t["a"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE idx_t = DataArray(NEWLINE data["time"][[3, 2, 1]].values, dims=["a"], coords={"a": ["a", "b", "c"]}NEWLINE )NEWLINE idx_2 = DataArray(NEWLINE data["dim2"][[2, 1, 3]].values, dims=["b"], coords={"b": [0, 1, 2]}NEWLINE )NEWLINE idx_3 = DataArray(NEWLINE data["dim3"][[1, 2, 1]].values, dims=["c"], coords={"c": [0.0, 1.1, 2.2]}NEWLINE )NEWLINE actual = data.sel(time=idx_t, dim2=idx_2, dim3=idx_3)NEWLINE expected = data.isel(NEWLINE time=Variable(("a",), [3, 2, 1]),NEWLINE dim2=Variable(("b",), [2, 1, 3]),NEWLINE dim3=Variable(("c",), [1, 2, 1]),NEWLINE )NEWLINE expected = expected.assign_coords(a=idx_t["a"], b=idx_2["b"], c=idx_3["c"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # test from sel_pointsNEWLINE data = Dataset({"foo": (("x", "y"), np.arange(9).reshape(3, 3))})NEWLINE data.coords.update({"x": [0, 1, 2], "y": [0, 1, 2]})NEWLINENEWLINE expected = Dataset(NEWLINE {"foo": ("points", [0, 4, 8])},NEWLINE coords={NEWLINE "x": Variable(("points",), [0, 1, 2]),NEWLINE "y": Variable(("points",), [0, 1, 2]),NEWLINE },NEWLINE )NEWLINE actual = data.sel(NEWLINE x=Variable(("points",), [0, 1, 2]), y=Variable(("points",), [0, 1, 2])NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected.coords.update({"x": ("points", [0, 1, 2]), "y": ("points", [0, 1, 2])})NEWLINE actual = data.sel(NEWLINE x=Variable(("points",), [0.1, 1.1, 2.5]),NEWLINE y=Variable(("points",), [0, 1.2, 2.0]),NEWLINE method="pad",NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE idx_x = DataArray([0, 1, 2], dims=["a"], coords={"a": ["a", "b", "c"]})NEWLINE idx_y = DataArray([0, 2, 1], dims=["b"], coords={"b": [0, 3, 6]})NEWLINE expected_ary = data["foo"][[0, 1, 2], [0, 2, 1]]NEWLINE actual = data.sel(x=idx_x, y=idx_y)NEWLINE assert_array_equal(expected_ary, actual["foo"])NEWLINE assert_identical(actual["a"].drop_vars("x"), idx_x["a"])NEWLINE assert_identical(actual["b"].drop_vars("y"), idx_y["b"])NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE data.sel(x=[2.5], y=[2.0], method="pad", tolerance=1e-3)NEWLINENEWLINE def test_sel_method(self):NEWLINE data = create_test_data()NEWLINENEWLINE expected = data.sel(dim2=1)NEWLINE actual = data.sel(dim2=0.95, method="nearest")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data.sel(dim2=0.95, method="nearest", tolerance=1)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE actual = data.sel(dim2=np.pi, method="nearest", tolerance=0)NEWLINENEWLINE expected = data.sel(dim2=[1.5])NEWLINE actual = data.sel(dim2=[1.45], method="backfill")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(NotImplementedError, "slice objects"):NEWLINE data.sel(dim2=slice(1, 3), method="ffill")NEWLINENEWLINE with raises_regex(TypeError, "``method``"):NEWLINE # this should not pass silentlyNEWLINE data.sel(method=data)NEWLINENEWLINE # cannot pass method if there is no associated coordinateNEWLINE with raises_regex(ValueError, "cannot supply"):NEWLINE data.sel(dim1=0, method="nearest")NEWLINENEWLINE def test_loc(self):NEWLINE data = create_test_data()NEWLINE expected = data.sel(dim3="a")NEWLINE actual = data.loc[dict(dim3="a")]NEWLINE assert_identical(expected, actual)NEWLINE with raises_regex(TypeError, "can only lookup dict"):NEWLINE data.loc["a"]NEWLINE with pytest.raises(TypeError):NEWLINE data.loc[dict(dim3="a")] = 0NEWLINENEWLINE def test_selection_multiindex(self):NEWLINE mindex = pd.MultiIndex.from_product(NEWLINE [["a", "b"], [1, 2], [-1, -2]], names=("one", "two", "three")NEWLINE )NEWLINE mdata = Dataset(data_vars={"var": ("x", range(8))}, coords={"x": mindex})NEWLINENEWLINE def test_sel(lab_indexer, pos_indexer, replaced_idx=False, renamed_dim=None):NEWLINE ds = mdata.sel(x=lab_indexer)NEWLINE expected_ds = mdata.isel(x=pos_indexer)NEWLINE if not replaced_idx:NEWLINE assert_identical(ds, expected_ds)NEWLINE else:NEWLINE if renamed_dim:NEWLINE assert ds["var"].dims[0] == renamed_dimNEWLINE ds = ds.rename({renamed_dim: "x"})NEWLINE assert_identical(ds["var"].variable, expected_ds["var"].variable)NEWLINE assert not ds["x"].equals(expected_ds["x"])NEWLINENEWLINE test_sel(("a", 1, -1), 0)NEWLINE test_sel(("b", 2, -2), -1)NEWLINE test_sel(("a", 1), [0, 1], replaced_idx=True, renamed_dim="three")NEWLINE test_sel(("a",), range(4), replaced_idx=True)NEWLINE test_sel("a", range(4), replaced_idx=True)NEWLINE test_sel([("a", 1, -1), ("b", 2, -2)], [0, 7])NEWLINE test_sel(slice("a", "b"), range(8))NEWLINE test_sel(slice(("a", 1), ("b", 1)), range(6))NEWLINE test_sel({"one": "a", "two": 1, "three": -1}, 0)NEWLINE test_sel({"one": "a", "two": 1}, [0, 1], replaced_idx=True, renamed_dim="three")NEWLINE test_sel({"one": "a"}, range(4), replaced_idx=True)NEWLINENEWLINE assert_identical(mdata.loc[{"x": {"one": "a"}}], mdata.sel(x={"one": "a"}))NEWLINE assert_identical(mdata.loc[{"x": "a"}], mdata.sel(x="a"))NEWLINE assert_identical(mdata.loc[{"x": ("a", 1)}], mdata.sel(x=("a", 1)))NEWLINE assert_identical(mdata.loc[{"x": ("a", 1, -1)}], mdata.sel(x=("a", 1, -1)))NEWLINENEWLINE assert_identical(mdata.sel(x={"one": "a", "two": 1}), mdata.sel(one="a", two=1))NEWLINENEWLINE def test_broadcast_like(self):NEWLINE original1 = DataArray(NEWLINE np.random.randn(5), [("x", range(5))], name="a"NEWLINE ).to_dataset()NEWLINENEWLINE original2 = DataArray(np.random.randn(6), [("y", range(6))], name="b")NEWLINENEWLINE expected1, expected2 = broadcast(original1, original2)NEWLINENEWLINE assert_identical(NEWLINE original1.broadcast_like(original2), expected1.transpose("y", "x")NEWLINE )NEWLINENEWLINE assert_identical(original2.broadcast_like(original1), expected2)NEWLINENEWLINE def test_reindex_like(self):NEWLINE data = create_test_data()NEWLINE data["letters"] = ("dim3", 10 * ["a"])NEWLINENEWLINE expected = data.isel(dim1=slice(10), time=slice(13))NEWLINE actual = data.reindex_like(expected)NEWLINE assert_identical(actual, expected)NEWLINENEWLINE expected = data.copy(deep=True)NEWLINE expected["dim3"] = ("dim3", list("cdefghijkl"))NEWLINE expected["var3"][:-2] = expected["var3"][2:].valuesNEWLINE expected["var3"][-2:] = np.nanNEWLINE expected["letters"] = expected["letters"].astype(object)NEWLINE expected["letters"][-2:] = np.nanNEWLINE expected["numbers"] = expected["numbers"].astype(float)NEWLINE expected["numbers"][:-2] = expected["numbers"][2:].valuesNEWLINE expected["numbers"][-2:] = np.nanNEWLINE actual = data.reindex_like(expected)NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_reindex(self):NEWLINE data = create_test_data()NEWLINE assert_identical(data, data.reindex())NEWLINENEWLINE expected = data.assign_coords(dim1=data["dim1"])NEWLINE actual = data.reindex(dim1=data["dim1"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = data.reindex(dim1=data["dim1"].values)NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = data.reindex(dim1=data["dim1"].to_index())NEWLINE assert_identical(actual, expected)NEWLINENEWLINE with raises_regex(ValueError, "cannot reindex or align along dimension"):NEWLINE data.reindex(dim1=data["dim1"][:5])NEWLINENEWLINE expected = data.isel(dim2=slice(5))NEWLINE actual = data.reindex(dim2=data["dim2"][:5])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE # test dict-like argumentNEWLINE actual = data.reindex({"dim2": data["dim2"]})NEWLINE expected = dataNEWLINE assert_identical(actual, expected)NEWLINE with raises_regex(ValueError, "cannot specify both"):NEWLINE data.reindex({"x": 0}, x=0)NEWLINE with raises_regex(ValueError, "dictionary"):NEWLINE data.reindex("foo")NEWLINENEWLINE # invalid dimensionNEWLINE with raises_regex(ValueError, "invalid reindex dim"):NEWLINE data.reindex(invalid=0)NEWLINENEWLINE # out of orderNEWLINE expected = data.sel(dim2=data["dim2"][:5:-1])NEWLINE actual = data.reindex(dim2=data["dim2"][:5:-1])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE # regression test for #279NEWLINE expected = Dataset({"x": ("time", np.random.randn(5))}, {"time": range(5)})NEWLINE time2 = DataArray(np.arange(5), dims="time2")NEWLINE with pytest.raises(ValueError):NEWLINE actual = expected.reindex(time=time2)NEWLINENEWLINE # another regression testNEWLINE ds = Dataset(NEWLINE {"foo": (["x", "y"], np.zeros((3, 4)))}, {"x": range(3), "y": range(4)}NEWLINE )NEWLINE expected = Dataset(NEWLINE {"foo": (["x", "y"], np.zeros((3, 2)))}, {"x": [0, 1, 3], "y": [0, 1]}NEWLINE )NEWLINE expected["foo"][-1] = np.nanNEWLINE actual = ds.reindex(x=[0, 1, 3], y=[0, 1])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reindex_warning(self):NEWLINE data = create_test_data()NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE # DataArray with different dimension raises Future warningNEWLINE ind = xr.DataArray([0.0, 1.0], dims=["new_dim"], name="ind")NEWLINE data.reindex(dim2=ind)NEWLINENEWLINE # Should not warnNEWLINE ind = xr.DataArray([0.0, 1.0], dims=["dim2"], name="ind")NEWLINE with pytest.warns(None) as ws:NEWLINE data.reindex(dim2=ind)NEWLINE assert len(ws) == 0NEWLINENEWLINE def test_reindex_variables_copied(self):NEWLINE data = create_test_data()NEWLINE reindexed_data = data.reindex(copy=False)NEWLINE for k in data.variables:NEWLINE assert reindexed_data.variables[k] is not data.variables[k]NEWLINENEWLINE def test_reindex_method(self):NEWLINE ds = Dataset({"x": ("y", [10, 20]), "y": [0, 1]})NEWLINE y = [-0.5, 0.5, 1.5]NEWLINE actual = ds.reindex(y=y, method="backfill")NEWLINE expected = Dataset({"x": ("y", [10, 20, np.nan]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.reindex(y=y, method="backfill", tolerance=0.1)NEWLINE expected = Dataset({"x": ("y", 3 * [np.nan]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.reindex(y=y, method="pad")NEWLINE expected = Dataset({"x": ("y", [np.nan, 10, 20]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE alt = Dataset({"y": y})NEWLINE actual = ds.reindex_like(alt, method="pad")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0])NEWLINE def test_reindex_fill_value(self, fill_value):NEWLINE ds = Dataset({"x": ("y", [10, 20]), "y": [0, 1]})NEWLINE y = [0, 1, 2]NEWLINE actual = ds.reindex(y=y, fill_value=fill_value)NEWLINE if fill_value == dtypes.NA:NEWLINE # if we supply the default, we expect the missing value for aNEWLINE # float arrayNEWLINE fill_value = np.nanNEWLINE expected = Dataset({"x": ("y", [10, 20, fill_value]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0])NEWLINE def test_reindex_like_fill_value(self, fill_value):NEWLINE ds = Dataset({"x": ("y", [10, 20]), "y": [0, 1]})NEWLINE y = [0, 1, 2]NEWLINE alt = Dataset({"y": y})NEWLINE actual = ds.reindex_like(alt, fill_value=fill_value)NEWLINE if fill_value == dtypes.NA:NEWLINE # if we supply the default, we expect the missing value for aNEWLINE # float arrayNEWLINE fill_value = np.nanNEWLINE expected = Dataset({"x": ("y", [10, 20, fill_value]), "y": y})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0])NEWLINE def test_align_fill_value(self, fill_value):NEWLINE x = Dataset({"foo": DataArray([1, 2], dims=["x"], coords={"x": [1, 2]})})NEWLINE y = Dataset({"bar": DataArray([1, 2], dims=["x"], coords={"x": [1, 3]})})NEWLINE x2, y2 = align(x, y, join="outer", fill_value=fill_value)NEWLINE if fill_value == dtypes.NA:NEWLINE # if we supply the default, we expect the missing value for aNEWLINE # float arrayNEWLINE fill_value = np.nanNEWLINENEWLINE expected_x2 = Dataset(NEWLINE {"foo": DataArray([1, 2, fill_value], dims=["x"], coords={"x": [1, 2, 3]})}NEWLINE )NEWLINE expected_y2 = Dataset(NEWLINE {"bar": DataArray([1, fill_value, 2], dims=["x"], coords={"x": [1, 2, 3]})}NEWLINE )NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_align(self):NEWLINE left = create_test_data()NEWLINE right = left.copy(deep=True)NEWLINE right["dim3"] = ("dim3", list("cdefghijkl"))NEWLINE right["var3"][:-2] = right["var3"][2:].valuesNEWLINE right["var3"][-2:] = np.random.randn(*right["var3"][-2:].shape)NEWLINE right["numbers"][:-2] = right["numbers"][2:].valuesNEWLINE right["numbers"][-2:] = -10NEWLINENEWLINE intersection = list("cdefghij")NEWLINE union = list("abcdefghijkl")NEWLINENEWLINE left2, right2 = align(left, right, join="inner")NEWLINE assert_array_equal(left2["dim3"], intersection)NEWLINE assert_identical(left2, right2)NEWLINENEWLINE left2, right2 = align(left, right, join="outer")NEWLINENEWLINE assert_array_equal(left2["dim3"], union)NEWLINE assert_equal(left2["dim3"].variable, right2["dim3"].variable)NEWLINENEWLINE assert_identical(left2.sel(dim3=intersection), right2.sel(dim3=intersection))NEWLINE assert np.isnan(left2["var3"][-2:]).all()NEWLINE assert np.isnan(right2["var3"][:2]).all()NEWLINENEWLINE left2, right2 = align(left, right, join="left")NEWLINE assert_equal(left2["dim3"].variable, right2["dim3"].variable)NEWLINE assert_equal(left2["dim3"].variable, left["dim3"].variable)NEWLINENEWLINE assert_identical(left2.sel(dim3=intersection), right2.sel(dim3=intersection))NEWLINE assert np.isnan(right2["var3"][:2]).all()NEWLINENEWLINE left2, right2 = align(left, right, join="right")NEWLINE assert_equal(left2["dim3"].variable, right2["dim3"].variable)NEWLINE assert_equal(left2["dim3"].variable, right["dim3"].variable)NEWLINENEWLINE assert_identical(left2.sel(dim3=intersection), right2.sel(dim3=intersection))NEWLINENEWLINE assert np.isnan(left2["var3"][-2:]).all()NEWLINENEWLINE with raises_regex(ValueError, "invalid value for join"):NEWLINE align(left, right, join="foobar")NEWLINE with pytest.raises(TypeError):NEWLINE align(left, right, foo="bar")NEWLINENEWLINE def test_align_exact(self):NEWLINE left = xr.Dataset(coords={"x": [0, 1]})NEWLINE right = xr.Dataset(coords={"x": [1, 2]})NEWLINENEWLINE left1, left2 = xr.align(left, left, join="exact")NEWLINE assert_identical(left1, left)NEWLINE assert_identical(left2, left)NEWLINENEWLINE with raises_regex(ValueError, "indexes .* not equal"):NEWLINE xr.align(left, right, join="exact")NEWLINENEWLINE def test_align_override(self):NEWLINE left = xr.Dataset(coords={"x": [0, 1, 2]})NEWLINE right = xr.Dataset(coords={"x": [0.1, 1.1, 2.1], "y": [1, 2, 3]})NEWLINE expected_right = xr.Dataset(coords={"x": [0, 1, 2], "y": [1, 2, 3]})NEWLINENEWLINE new_left, new_right = xr.align(left, right, join="override")NEWLINE assert_identical(left, new_left)NEWLINE assert_identical(new_right, expected_right)NEWLINENEWLINE new_left, new_right = xr.align(left, right, exclude="x", join="override")NEWLINE assert_identical(left, new_left)NEWLINE assert_identical(right, new_right)NEWLINENEWLINE new_left, new_right = xr.align(NEWLINE left.isel(x=0, drop=True), right, exclude="x", join="override"NEWLINE )NEWLINE assert_identical(left.isel(x=0, drop=True), new_left)NEWLINE assert_identical(right, new_right)NEWLINENEWLINE with raises_regex(ValueError, "Indexes along dimension 'x' don't have"):NEWLINE xr.align(left.isel(x=0).expand_dims("x"), right, join="override")NEWLINENEWLINE def test_align_exclude(self):NEWLINE x = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[1, 2], [3, 4]], dims=["x", "y"], coords={"x": [1, 2], "y": [3, 4]}NEWLINE )NEWLINE }NEWLINE )NEWLINE y = Dataset(NEWLINE {NEWLINE "bar": DataArray(NEWLINE [[1, 2], [3, 4]], dims=["x", "y"], coords={"x": [1, 3], "y": [5, 6]}NEWLINE )NEWLINE }NEWLINE )NEWLINE x2, y2 = align(x, y, exclude=["y"], join="outer")NEWLINENEWLINE expected_x2 = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[1, 2], [3, 4], [np.nan, np.nan]],NEWLINE dims=["x", "y"],NEWLINE coords={"x": [1, 2, 3], "y": [3, 4]},NEWLINE )NEWLINE }NEWLINE )NEWLINE expected_y2 = Dataset(NEWLINE {NEWLINE "bar": DataArray(NEWLINE [[1, 2], [np.nan, np.nan], [3, 4]],NEWLINE dims=["x", "y"],NEWLINE coords={"x": [1, 2, 3], "y": [5, 6]},NEWLINE )NEWLINE }NEWLINE )NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_align_nocopy(self):NEWLINE x = Dataset({"foo": DataArray([1, 2, 3], coords=[("x", [1, 2, 3])])})NEWLINE y = Dataset({"foo": DataArray([1, 2], coords=[("x", [1, 2])])})NEWLINE expected_x2 = xNEWLINE expected_y2 = Dataset(NEWLINE {"foo": DataArray([1, 2, np.nan], coords=[("x", [1, 2, 3])])}NEWLINE )NEWLINENEWLINE x2, y2 = align(x, y, copy=False, join="outer")NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINE assert source_ndarray(x["foo"].data) is source_ndarray(x2["foo"].data)NEWLINENEWLINE x2, y2 = align(x, y, copy=True, join="outer")NEWLINE assert source_ndarray(x["foo"].data) is not source_ndarray(x2["foo"].data)NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_align_indexes(self):NEWLINE x = Dataset({"foo": DataArray([1, 2, 3], dims="x", coords=[("x", [1, 2, 3])])})NEWLINE (x2,) = align(x, indexes={"x": [2, 3, 1]})NEWLINE expected_x2 = Dataset(NEWLINE {"foo": DataArray([2, 3, 1], dims="x", coords={"x": [2, 3, 1]})}NEWLINE )NEWLINENEWLINE assert_identical(expected_x2, x2)NEWLINENEWLINE def test_align_non_unique(self):NEWLINE x = Dataset({"foo": ("x", [3, 4, 5]), "x": [0, 0, 1]})NEWLINE x1, x2 = align(x, x)NEWLINE assert x1.identical(x) and x2.identical(x)NEWLINENEWLINE y = Dataset({"bar": ("x", [6, 7]), "x": [0, 1]})NEWLINE with raises_regex(ValueError, "cannot reindex or align"):NEWLINE align(x, y)NEWLINENEWLINE def test_broadcast(self):NEWLINE ds = Dataset(NEWLINE {"foo": 0, "bar": ("x", [1]), "baz": ("y", [2, 3])}, {"c": ("x", [4])}NEWLINE )NEWLINE expected = Dataset(NEWLINE {NEWLINE "foo": (("x", "y"), [[0, 0]]),NEWLINE "bar": (("x", "y"), [[1, 1]]),NEWLINE "baz": (("x", "y"), [[2, 3]]),NEWLINE },NEWLINE {"c": ("x", [4])},NEWLINE )NEWLINE (actual,) = broadcast(ds)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE ds_x = Dataset({"foo": ("x", [1])})NEWLINE ds_y = Dataset({"bar": ("y", [2, 3])})NEWLINE expected_x = Dataset({"foo": (("x", "y"), [[1, 1]])})NEWLINE expected_y = Dataset({"bar": (("x", "y"), [[2, 3]])})NEWLINE actual_x, actual_y = broadcast(ds_x, ds_y)NEWLINE assert_identical(expected_x, actual_x)NEWLINE assert_identical(expected_y, actual_y)NEWLINENEWLINE array_y = ds_y["bar"]NEWLINE expected_y = expected_y["bar"]NEWLINE actual_x, actual_y = broadcast(ds_x, array_y)NEWLINE assert_identical(expected_x, actual_x)NEWLINE assert_identical(expected_y, actual_y)NEWLINENEWLINE def test_broadcast_nocopy(self):NEWLINE # Test that data is not copied if not neededNEWLINE x = Dataset({"foo": (("x", "y"), [[1, 1]])})NEWLINE y = Dataset({"bar": ("y", [2, 3])})NEWLINENEWLINE (actual_x,) = broadcast(x)NEWLINE assert_identical(x, actual_x)NEWLINE assert source_ndarray(actual_x["foo"].data) is source_ndarray(x["foo"].data)NEWLINENEWLINE actual_x, actual_y = broadcast(x, y)NEWLINE assert_identical(x, actual_x)NEWLINE assert source_ndarray(actual_x["foo"].data) is source_ndarray(x["foo"].data)NEWLINENEWLINE def test_broadcast_exclude(self):NEWLINE x = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[1, 2], [3, 4]], dims=["x", "y"], coords={"x": [1, 2], "y": [3, 4]}NEWLINE ),NEWLINE "bar": DataArray(5),NEWLINE }NEWLINE )NEWLINE y = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[1, 2]], dims=["z", "y"], coords={"z": [1], "y": [5, 6]}NEWLINE )NEWLINE }NEWLINE )NEWLINE x2, y2 = broadcast(x, y, exclude=["y"])NEWLINENEWLINE expected_x2 = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[[1, 2]], [[3, 4]]],NEWLINE dims=["x", "z", "y"],NEWLINE coords={"z": [1], "x": [1, 2], "y": [3, 4]},NEWLINE ),NEWLINE "bar": DataArray(NEWLINE [[5], [5]], dims=["x", "z"], coords={"x": [1, 2], "z": [1]}NEWLINE ),NEWLINE }NEWLINE )NEWLINE expected_y2 = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[[1, 2]], [[1, 2]]],NEWLINE dims=["x", "z", "y"],NEWLINE coords={"z": [1], "x": [1, 2], "y": [5, 6]},NEWLINE )NEWLINE }NEWLINE )NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_broadcast_misaligned(self):NEWLINE x = Dataset({"foo": DataArray([1, 2, 3], coords=[("x", [-1, -2, -3])])})NEWLINE y = Dataset(NEWLINE {NEWLINE "bar": DataArray(NEWLINE [[1, 2], [3, 4]],NEWLINE dims=["y", "x"],NEWLINE coords={"y": [1, 2], "x": [10, -3]},NEWLINE )NEWLINE }NEWLINE )NEWLINE x2, y2 = broadcast(x, y)NEWLINE expected_x2 = Dataset(NEWLINE {NEWLINE "foo": DataArray(NEWLINE [[3, 3], [2, 2], [1, 1], [np.nan, np.nan]],NEWLINE dims=["x", "y"],NEWLINE coords={"y": [1, 2], "x": [-3, -2, -1, 10]},NEWLINE )NEWLINE }NEWLINE )NEWLINE expected_y2 = Dataset(NEWLINE {NEWLINE "bar": DataArray(NEWLINE [[2, 4], [np.nan, np.nan], [np.nan, np.nan], [1, 3]],NEWLINE dims=["x", "y"],NEWLINE coords={"y": [1, 2], "x": [-3, -2, -1, 10]},NEWLINE )NEWLINE }NEWLINE )NEWLINE assert_identical(expected_x2, x2)NEWLINE assert_identical(expected_y2, y2)NEWLINENEWLINE def test_variable_indexing(self):NEWLINE data = create_test_data()NEWLINE v = data["var1"]NEWLINE d1 = data["dim1"]NEWLINE d2 = data["dim2"]NEWLINE assert_equal(v, v[d1.values])NEWLINE assert_equal(v, v[d1])NEWLINE assert_equal(v[:3], v[d1 < 3])NEWLINE assert_equal(v[:, 3:], v[:, d2 >= 1.5])NEWLINE assert_equal(v[:3, 3:], v[d1 < 3, d2 >= 1.5])NEWLINE assert_equal(v[:3, :2], v[range(3), range(2)])NEWLINE assert_equal(v[:3, :2], v.loc[d1[:3], d2[:2]])NEWLINENEWLINE def test_drop_variables(self):NEWLINE data = create_test_data()NEWLINENEWLINE assert_identical(data, data.drop_vars([]))NEWLINENEWLINE expected = Dataset({k: data[k] for k in data.variables if k != "time"})NEWLINE actual = data.drop_vars("time")NEWLINE assert_identical(expected, actual)NEWLINE actual = data.drop_vars(["time"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "cannot be found"):NEWLINE data.drop_vars("not_found_here")NEWLINENEWLINE actual = data.drop_vars("not_found_here", errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE actual = data.drop_vars(["not_found_here"], errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE actual = data.drop_vars(["time", "not_found_here"], errors="ignore")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # deprecated approach with `drop` works (straight copy paste from above)NEWLINENEWLINE with pytest.warns(PendingDeprecationWarning):NEWLINE actual = data.drop("not_found_here", errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE with pytest.warns(PendingDeprecationWarning):NEWLINE actual = data.drop(["not_found_here"], errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE with pytest.warns(PendingDeprecationWarning):NEWLINE actual = data.drop(["time", "not_found_here"], errors="ignore")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_drop_index_labels(self):NEWLINE data = Dataset({"A": (["x", "y"], np.random.randn(2, 3)), "x": ["a", "b"]})NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE actual = data.drop(["a"], dim="x")NEWLINE expected = data.isel(x=[1])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE actual = data.drop(["a", "b"], dim="x")NEWLINE expected = data.isel(x=slice(0, 0))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises(KeyError):NEWLINE # not contained in axisNEWLINE with pytest.warns(DeprecationWarning):NEWLINE data.drop(["c"], dim="x")NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE actual = data.drop(["c"], dim="x", errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE with pytest.warns(DeprecationWarning):NEWLINE data.drop(["c"], dim="x", errors="wrong_value")NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE actual = data.drop(["a", "b", "c"], "x", errors="ignore")NEWLINE expected = data.isel(x=slice(0, 0))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # DataArrays as labels are a nasty corner case as they are notNEWLINE # Iterable[Hashable] - DataArray.__iter__ yields scalar DataArrays.NEWLINE actual = data.drop_sel(x=DataArray(["a", "b", "c"]), errors="ignore")NEWLINE expected = data.isel(x=slice(0, 0))NEWLINE assert_identical(expected, actual)NEWLINE with pytest.warns(DeprecationWarning):NEWLINE data.drop(DataArray(["a", "b", "c"]), dim="x", errors="ignore")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "does not have coordinate labels"):NEWLINE data.drop_sel(y=1)NEWLINENEWLINE def test_drop_labels_by_keyword(self):NEWLINE data = Dataset(NEWLINE {"A": (["x", "y"], np.random.randn(2, 6)), "x": ["a", "b"], "y": range(6)}NEWLINE )NEWLINE # Basic functionality.NEWLINE assert len(data.coords["x"]) == 2NEWLINENEWLINE with pytest.warns(DeprecationWarning):NEWLINE ds1 = data.drop(["a"], dim="x")NEWLINE ds2 = data.drop_sel(x="a")NEWLINE ds3 = data.drop_sel(x=["a"])NEWLINE ds4 = data.drop_sel(x=["a", "b"])NEWLINE ds5 = data.drop_sel(x=["a", "b"], y=range(0, 6, 2))NEWLINENEWLINE arr = DataArray(range(3), dims=["c"])NEWLINE with pytest.warns(FutureWarning):NEWLINE data.drop(arr.coords)NEWLINE with pytest.warns(FutureWarning):NEWLINE data.drop(arr.indexes)NEWLINENEWLINE assert_array_equal(ds1.coords["x"], ["b"])NEWLINE assert_array_equal(ds2.coords["x"], ["b"])NEWLINE assert_array_equal(ds3.coords["x"], ["b"])NEWLINE assert ds4.coords["x"].size == 0NEWLINE assert ds5.coords["x"].size == 0NEWLINE assert_array_equal(ds5.coords["y"], [1, 3, 5])NEWLINENEWLINE # Error handling if user tries both approaches.NEWLINE with pytest.raises(ValueError):NEWLINE data.drop(labels=["a"], x="a")NEWLINE with pytest.raises(ValueError):NEWLINE data.drop(labels=["a"], dim="x", x="a")NEWLINE warnings.filterwarnings("ignore", r"\W*drop")NEWLINE with pytest.raises(ValueError):NEWLINE data.drop(dim="x", x="a")NEWLINENEWLINE def test_drop_dims(self):NEWLINE data = xr.Dataset(NEWLINE {NEWLINE "A": (["x", "y"], np.random.randn(2, 3)),NEWLINE "B": ("x", np.random.randn(2)),NEWLINE "x": ["a", "b"],NEWLINE "z": np.pi,NEWLINE }NEWLINE )NEWLINENEWLINE actual = data.drop_dims("x")NEWLINE expected = data.drop_vars(["A", "B", "x"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data.drop_dims("y")NEWLINE expected = data.drop_vars("A")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data.drop_dims(["x", "y"])NEWLINE expected = data.drop_vars(["A", "B", "x"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises((ValueError, KeyError)):NEWLINE data.drop_dims("z") # not a dimensionNEWLINENEWLINE with pytest.raises((ValueError, KeyError)):NEWLINE data.drop_dims(None)NEWLINENEWLINE actual = data.drop_dims("z", errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE actual = data.drop_dims(None, errors="ignore")NEWLINE assert_identical(data, actual)NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE actual = data.drop_dims("z", errors="wrong_value")NEWLINENEWLINE actual = data.drop_dims(["x", "y", "z"], errors="ignore")NEWLINE expected = data.drop_vars(["A", "B", "x"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_copy(self):NEWLINE data = create_test_data()NEWLINE data.attrs["Test"] = [1, 2, 3]NEWLINENEWLINE for copied in [data.copy(deep=False), copy(data)]:NEWLINE assert_identical(data, copied)NEWLINE assert data.encoding == copied.encodingNEWLINE # Note: IndexVariable objects with string dtype are alwaysNEWLINE # copied because of xarray.core.util.safe_cast_to_index.NEWLINE # Limiting the test to data variables.NEWLINE for k in data.data_vars:NEWLINE v0 = data.variables[k]NEWLINE v1 = copied.variables[k]NEWLINE assert source_ndarray(v0.data) is source_ndarray(v1.data)NEWLINE copied["foo"] = ("z", np.arange(5))NEWLINE assert "foo" not in dataNEWLINENEWLINE copied.attrs["foo"] = "bar"NEWLINE assert "foo" not in data.attrsNEWLINE assert data.attrs["Test"] is copied.attrs["Test"]NEWLINENEWLINE for copied in [data.copy(deep=True), deepcopy(data)]:NEWLINE assert_identical(data, copied)NEWLINE for k, v0 in data.variables.items():NEWLINE v1 = copied.variables[k]NEWLINE assert v0 is not v1NEWLINENEWLINE assert data.attrs["Test"] is not copied.attrs["Test"]NEWLINENEWLINE def test_copy_with_data(self):NEWLINE orig = create_test_data()NEWLINE new_data = {k: np.random.randn(*v.shape) for k, v in orig.data_vars.items()}NEWLINE actual = orig.copy(data=new_data)NEWLINENEWLINE expected = orig.copy()NEWLINE for k, v in new_data.items():NEWLINE expected[k].data = vNEWLINE assert_identical(expected, actual)NEWLINENEWLINE @pytest.mark.xfail(raises=AssertionError)NEWLINE @pytest.mark.parametrize(NEWLINE "deep, expected_orig",NEWLINE [NEWLINE [NEWLINE True,NEWLINE xr.DataArray(NEWLINE xr.IndexVariable("a", np.array([1, 2])),NEWLINE coords={"a": [1, 2]},NEWLINE dims=["a"],NEWLINE ),NEWLINE ],NEWLINE [NEWLINE False,NEWLINE xr.DataArray(NEWLINE xr.IndexVariable("a", np.array([999, 2])),NEWLINE coords={"a": [999, 2]},NEWLINE dims=["a"],NEWLINE ),NEWLINE ],NEWLINE ],NEWLINE )NEWLINE def test_copy_coords(self, deep, expected_orig):NEWLINE """The test fails for the shallow copy, and apparently only on WindowsNEWLINE for some reason. In windows coords seem to be immutable unless it's oneNEWLINE dataset deep copied from another."""NEWLINE ds = xr.DataArray(NEWLINE np.ones([2, 2, 2]),NEWLINE coords={"a": [1, 2], "b": ["x", "y"], "c": [0, 1]},NEWLINE dims=["a", "b", "c"],NEWLINE name="value",NEWLINE ).to_dataset()NEWLINE ds_cp = ds.copy(deep=deep)NEWLINE ds_cp.coords["a"].data[0] = 999NEWLINENEWLINE expected_cp = xr.DataArray(NEWLINE xr.IndexVariable("a", np.array([999, 2])),NEWLINE coords={"a": [999, 2]},NEWLINE dims=["a"],NEWLINE )NEWLINE assert_identical(ds_cp.coords["a"], expected_cp)NEWLINENEWLINE assert_identical(ds.coords["a"], expected_orig)NEWLINENEWLINE def test_copy_with_data_errors(self):NEWLINE orig = create_test_data()NEWLINE new_var1 = np.arange(orig["var1"].size).reshape(orig["var1"].shape)NEWLINE with raises_regex(ValueError, "Data must be dict-like"):NEWLINE orig.copy(data=new_var1)NEWLINE with raises_regex(ValueError, "only contain variables in original"):NEWLINE orig.copy(data={"not_in_original": new_var1})NEWLINE with raises_regex(ValueError, "contain all variables in original"):NEWLINE orig.copy(data={"var1": new_var1})NEWLINENEWLINE def test_rename(self):NEWLINE data = create_test_data()NEWLINE newnames = {"var1": "renamed_var1", "dim2": "renamed_dim2"}NEWLINE renamed = data.rename(newnames)NEWLINENEWLINE variables = dict(data.variables)NEWLINE for k, v in newnames.items():NEWLINE variables[v] = variables.pop(k)NEWLINENEWLINE for k, v in variables.items():NEWLINE dims = list(v.dims)NEWLINE for name, newname in newnames.items():NEWLINE if name in dims:NEWLINE dims[dims.index(name)] = newnameNEWLINENEWLINE assert_equal(NEWLINE Variable(dims, v.values, v.attrs),NEWLINE renamed[k].variable.to_base_variable(),NEWLINE )NEWLINE assert v.encoding == renamed[k].encodingNEWLINE assert type(v) is type(renamed.variables[k]) # noqa: E721NEWLINENEWLINE assert "var1" not in renamedNEWLINE assert "dim2" not in renamedNEWLINENEWLINE with raises_regex(ValueError, "cannot rename 'not_a_var'"):NEWLINE data.rename({"not_a_var": "nada"})NEWLINENEWLINE with raises_regex(ValueError, "'var1' conflicts"):NEWLINE data.rename({"var2": "var1"})NEWLINENEWLINE # verify that we can rename a variable without accessing the dataNEWLINE var1 = data["var1"]NEWLINE data["var1"] = (var1.dims, InaccessibleArray(var1.values))NEWLINE renamed = data.rename(newnames)NEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE renamed["renamed_var1"].valuesNEWLINENEWLINE renamed_kwargs = data.rename(**newnames)NEWLINE assert_identical(renamed, renamed_kwargs)NEWLINENEWLINE def test_rename_old_name(self):NEWLINE # regtest for GH1477NEWLINE data = create_test_data()NEWLINENEWLINE with raises_regex(ValueError, "'samecol' conflicts"):NEWLINE data.rename({"var1": "samecol", "var2": "samecol"})NEWLINENEWLINE # This shouldn't cause any problems.NEWLINE data.rename({"var1": "var2", "var2": "var1"})NEWLINENEWLINE def test_rename_same_name(self):NEWLINE data = create_test_data()NEWLINE newnames = {"var1": "var1", "dim2": "dim2"}NEWLINE renamed = data.rename(newnames)NEWLINE assert_identical(renamed, data)NEWLINENEWLINE def test_rename_inplace(self):NEWLINE times = pd.date_range("2000-01-01", periods=3)NEWLINE data = Dataset({"z": ("x", [2, 3, 4]), "t": ("t", times)})NEWLINE with pytest.raises(TypeError):NEWLINE data.rename({"x": "y"}, inplace=True)NEWLINENEWLINE def test_rename_dims(self):NEWLINE original = Dataset({"x": ("x", [0, 1, 2]), "y": ("x", [10, 11, 12]), "z": 42})NEWLINE expected = Dataset(NEWLINE {"x": ("x_new", [0, 1, 2]), "y": ("x_new", [10, 11, 12]), "z": 42}NEWLINE )NEWLINE expected = expected.set_coords("x")NEWLINE dims_dict = {"x": "x_new"}NEWLINE actual = original.rename_dims(dims_dict)NEWLINE assert_identical(expected, actual)NEWLINE actual_2 = original.rename_dims(**dims_dict)NEWLINE assert_identical(expected, actual_2)NEWLINENEWLINE # Test to raise ValueErrorNEWLINE dims_dict_bad = {"x_bad": "x_new"}NEWLINE with pytest.raises(ValueError):NEWLINE original.rename_dims(dims_dict_bad)NEWLINENEWLINE def test_rename_vars(self):NEWLINE original = Dataset({"x": ("x", [0, 1, 2]), "y": ("x", [10, 11, 12]), "z": 42})NEWLINE expected = Dataset(NEWLINE {"x_new": ("x", [0, 1, 2]), "y": ("x", [10, 11, 12]), "z": 42}NEWLINE )NEWLINE expected = expected.set_coords("x_new")NEWLINE name_dict = {"x": "x_new"}NEWLINE actual = original.rename_vars(name_dict)NEWLINE assert_identical(expected, actual)NEWLINE actual_2 = original.rename_vars(**name_dict)NEWLINE assert_identical(expected, actual_2)NEWLINENEWLINE # Test to raise ValueErrorNEWLINE names_dict_bad = {"x_bad": "x_new"}NEWLINE with pytest.raises(ValueError):NEWLINE original.rename_vars(names_dict_bad)NEWLINENEWLINE def test_swap_dims(self):NEWLINE original = Dataset({"x": [1, 2, 3], "y": ("x", list("abc")), "z": 42})NEWLINE expected = Dataset({"z": 42}, {"x": ("y", [1, 2, 3]), "y": list("abc")})NEWLINE actual = original.swap_dims({"x": "y"})NEWLINE assert_identical(expected, actual)NEWLINE assert isinstance(actual.variables["y"], IndexVariable)NEWLINE assert isinstance(actual.variables["x"], Variable)NEWLINE assert actual.indexes["y"].equals(pd.Index(list("abc")))NEWLINENEWLINE roundtripped = actual.swap_dims({"y": "x"})NEWLINE assert_identical(original.set_coords("y"), roundtripped)NEWLINENEWLINE with raises_regex(ValueError, "cannot swap"):NEWLINE original.swap_dims({"y": "x"})NEWLINE with raises_regex(ValueError, "replacement dimension"):NEWLINE original.swap_dims({"x": "z"})NEWLINENEWLINE def test_expand_dims_error(self):NEWLINE original = Dataset(NEWLINE {NEWLINE "x": ("a", np.random.randn(3)),NEWLINE "y": (["b", "a"], np.random.randn(4, 3)),NEWLINE "z": ("a", np.random.randn(3)),NEWLINE },NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINENEWLINE with raises_regex(ValueError, "already exists"):NEWLINE original.expand_dims(dim=["x"])NEWLINENEWLINE # Make sure it raises true error also for non-dimensional coordinatesNEWLINE # which has dimension.NEWLINE original = original.set_coords("z")NEWLINE with raises_regex(ValueError, "already exists"):NEWLINE original.expand_dims(dim=["z"])NEWLINENEWLINE original = Dataset(NEWLINE {NEWLINE "x": ("a", np.random.randn(3)),NEWLINE "y": (["b", "a"], np.random.randn(4, 3)),NEWLINE "z": ("a", np.random.randn(3)),NEWLINE },NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE with raises_regex(TypeError, "value of new dimension"):NEWLINE original.expand_dims({"d": 3.2})NEWLINE with raises_regex(ValueError, "both keyword and positional"):NEWLINE original.expand_dims({"d": 4}, e=4)NEWLINENEWLINE def test_expand_dims_int(self):NEWLINE original = Dataset(NEWLINE {"x": ("a", np.random.randn(3)), "y": (["b", "a"], np.random.randn(4, 3))},NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINENEWLINE actual = original.expand_dims(["z"], [1])NEWLINE expected = Dataset(NEWLINE {NEWLINE "x": original["x"].expand_dims("z", 1),NEWLINE "y": original["y"].expand_dims("z", 1),NEWLINE },NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINE # make sure squeeze restores the original data set.NEWLINE roundtripped = actual.squeeze("z")NEWLINE assert_identical(original, roundtripped)NEWLINENEWLINE # another test with a negative axisNEWLINE actual = original.expand_dims(["z"], [-1])NEWLINE expected = Dataset(NEWLINE {NEWLINE "x": original["x"].expand_dims("z", -1),NEWLINE "y": original["y"].expand_dims("z", -1),NEWLINE },NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINE # make sure squeeze restores the original data set.NEWLINE roundtripped = actual.squeeze("z")NEWLINE assert_identical(original, roundtripped)NEWLINENEWLINE def test_expand_dims_coords(self):NEWLINE original = Dataset({"x": ("a", np.array([1, 2, 3]))})NEWLINE expected = Dataset(NEWLINE {"x": (("b", "a"), np.array([[1, 2, 3], [1, 2, 3]]))}, coords={"b": [1, 2]}NEWLINE )NEWLINE actual = original.expand_dims(dict(b=[1, 2]))NEWLINE assert_identical(expected, actual)NEWLINE assert "b" not in original._coord_namesNEWLINENEWLINE def test_expand_dims_existing_scalar_coord(self):NEWLINE original = Dataset({"x": 1}, {"a": 2})NEWLINE expected = Dataset({"x": (("a",), [1])}, {"a": [2]})NEWLINE actual = original.expand_dims("a")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_isel_expand_dims_roundtrip(self):NEWLINE original = Dataset({"x": (("a",), [1])}, {"a": [2]})NEWLINE actual = original.isel(a=0).expand_dims("a")NEWLINE assert_identical(actual, original)NEWLINENEWLINE def test_expand_dims_mixed_int_and_coords(self):NEWLINE # Test expanding one dimension to have size > 1 that doesn't haveNEWLINE # coordinates, and also expanding another dimension to have size > 1NEWLINE # that DOES have coordinates.NEWLINE original = Dataset(NEWLINE {"x": ("a", np.random.randn(3)), "y": (["b", "a"], np.random.randn(4, 3))},NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE )NEWLINENEWLINE actual = original.expand_dims({"d": 4, "e": ["l", "m", "n"]})NEWLINENEWLINE expected = Dataset(NEWLINE {NEWLINE "x": xr.DataArray(NEWLINE original["x"].values * np.ones([4, 3, 3]),NEWLINE coords=dict(d=range(4), e=["l", "m", "n"], a=np.linspace(0, 1, 3)),NEWLINE dims=["d", "e", "a"],NEWLINE ).drop_vars("d"),NEWLINE "y": xr.DataArray(NEWLINE original["y"].values * np.ones([4, 3, 4, 3]),NEWLINE coords=dict(NEWLINE d=range(4),NEWLINE e=["l", "m", "n"],NEWLINE b=np.linspace(0, 1, 4),NEWLINE a=np.linspace(0, 1, 3),NEWLINE ),NEWLINE dims=["d", "e", "b", "a"],NEWLINE ).drop_vars("d"),NEWLINE },NEWLINE coords={"c": np.linspace(0, 1, 5)},NEWLINE )NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_expand_dims_kwargs_python36plus(self):NEWLINE original = Dataset(NEWLINE {"x": ("a", np.random.randn(3)), "y": (["b", "a"], np.random.randn(4, 3))},NEWLINE coords={NEWLINE "a": np.linspace(0, 1, 3),NEWLINE "b": np.linspace(0, 1, 4),NEWLINE "c": np.linspace(0, 1, 5),NEWLINE },NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE other_way = original.expand_dims(e=["l", "m", "n"])NEWLINE other_way_expected = Dataset(NEWLINE {NEWLINE "x": xr.DataArray(NEWLINE original["x"].values * np.ones([3, 3]),NEWLINE coords=dict(e=["l", "m", "n"], a=np.linspace(0, 1, 3)),NEWLINE dims=["e", "a"],NEWLINE ),NEWLINE "y": xr.DataArray(NEWLINE original["y"].values * np.ones([3, 4, 3]),NEWLINE coords=dict(NEWLINE e=["l", "m", "n"],NEWLINE b=np.linspace(0, 1, 4),NEWLINE a=np.linspace(0, 1, 3),NEWLINE ),NEWLINE dims=["e", "b", "a"],NEWLINE ),NEWLINE },NEWLINE coords={"c": np.linspace(0, 1, 5)},NEWLINE attrs={"key": "entry"},NEWLINE )NEWLINE assert_identical(other_way_expected, other_way)NEWLINENEWLINE def test_set_index(self):NEWLINE expected = create_test_multiindex()NEWLINE mindex = expected["x"].to_index()NEWLINE indexes = [mindex.get_level_values(n) for n in mindex.names]NEWLINE coords = {idx.name: ("x", idx) for idx in indexes}NEWLINE ds = Dataset({}, coords=coords)NEWLINENEWLINE obj = ds.set_index(x=mindex.names)NEWLINE assert_identical(obj, expected)NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE ds.set_index(x=mindex.names, inplace=True)NEWLINE assert_identical(ds, expected)NEWLINENEWLINE # ensure set_index with no existing index and a single data var givenNEWLINE # doesn't return multi-indexNEWLINE ds = Dataset(data_vars={"x_var": ("x", [0, 1, 2])})NEWLINE expected = Dataset(coords={"x": [0, 1, 2]})NEWLINE assert_identical(ds.set_index(x="x_var"), expected)NEWLINENEWLINE # Issue 3176: Ensure clear error message on key error.NEWLINE with pytest.raises(ValueError) as excinfo:NEWLINE ds.set_index(foo="bar")NEWLINE assert str(excinfo.value) == "bar is not the name of an existing variable."NEWLINENEWLINE def test_reset_index(self):NEWLINE ds = create_test_multiindex()NEWLINE mindex = ds["x"].to_index()NEWLINE indexes = [mindex.get_level_values(n) for n in mindex.names]NEWLINE coords = {idx.name: ("x", idx) for idx in indexes}NEWLINE expected = Dataset({}, coords=coords)NEWLINENEWLINE obj = ds.reset_index("x")NEWLINE assert_identical(obj, expected)NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE ds.reset_index("x", inplace=True)NEWLINENEWLINE def test_reorder_levels(self):NEWLINE ds = create_test_multiindex()NEWLINE mindex = ds["x"].to_index()NEWLINE midx = mindex.reorder_levels(["level_2", "level_1"])NEWLINE expected = Dataset({}, coords={"x": midx})NEWLINENEWLINE reindexed = ds.reorder_levels(x=["level_2", "level_1"])NEWLINE assert_identical(reindexed, expected)NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE ds.reorder_levels(x=["level_2", "level_1"], inplace=True)NEWLINENEWLINE ds = Dataset({}, coords={"x": [1, 2]})NEWLINE with raises_regex(ValueError, "has no MultiIndex"):NEWLINE ds.reorder_levels(x=["level_1", "level_2"])NEWLINENEWLINE def test_stack(self):NEWLINE ds = Dataset(NEWLINE {"a": ("x", [0, 1]), "b": (("x", "y"), [[0, 1], [2, 3]]), "y": ["a", "b"]}NEWLINE )NEWLINENEWLINE exp_index = pd.MultiIndex.from_product([[0, 1], ["a", "b"]], names=["x", "y"])NEWLINE expected = Dataset(NEWLINE {"a": ("z", [0, 0, 1, 1]), "b": ("z", [0, 1, 2, 3]), "z": exp_index}NEWLINE )NEWLINE actual = ds.stack(z=["x", "y"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE exp_index = pd.MultiIndex.from_product([["a", "b"], [0, 1]], names=["y", "x"])NEWLINE expected = Dataset(NEWLINE {"a": ("z", [0, 1, 0, 1]), "b": ("z", [0, 2, 1, 3]), "z": exp_index}NEWLINE )NEWLINE actual = ds.stack(z=["y", "x"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_unstack(self):NEWLINE index = pd.MultiIndex.from_product([[0, 1], ["a", "b"]], names=["x", "y"])NEWLINE ds = Dataset({"b": ("z", [0, 1, 2, 3]), "z": index})NEWLINE expected = Dataset(NEWLINE {"b": (("x", "y"), [[0, 1], [2, 3]]), "x": [0, 1], "y": ["a", "b"]}NEWLINE )NEWLINE for dim in ["z", ["z"], None]:NEWLINE actual = ds.unstack(dim)NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_unstack_errors(self):NEWLINE ds = Dataset({"x": [1, 2, 3]})NEWLINE with raises_regex(ValueError, "does not contain the dimensions"):NEWLINE ds.unstack("foo")NEWLINE with raises_regex(ValueError, "do not have a MultiIndex"):NEWLINE ds.unstack("x")NEWLINENEWLINE def test_stack_unstack_fast(self):NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": ("x", [0, 1]),NEWLINE "b": (("x", "y"), [[0, 1], [2, 3]]),NEWLINE "x": [0, 1],NEWLINE "y": ["a", "b"],NEWLINE }NEWLINE )NEWLINE actual = ds.stack(z=["x", "y"]).unstack("z")NEWLINE assert actual.broadcast_equals(ds)NEWLINENEWLINE actual = ds[["b"]].stack(z=["x", "y"]).unstack("z")NEWLINE assert actual.identical(ds[["b"]])NEWLINENEWLINE def test_stack_unstack_slow(self):NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": ("x", [0, 1]),NEWLINE "b": (("x", "y"), [[0, 1], [2, 3]]),NEWLINE "x": [0, 1],NEWLINE "y": ["a", "b"],NEWLINE }NEWLINE )NEWLINE stacked = ds.stack(z=["x", "y"])NEWLINE actual = stacked.isel(z=slice(None, None, -1)).unstack("z")NEWLINE assert actual.broadcast_equals(ds)NEWLINENEWLINE stacked = ds[["b"]].stack(z=["x", "y"])NEWLINE actual = stacked.isel(z=slice(None, None, -1)).unstack("z")NEWLINE assert actual.identical(ds[["b"]])NEWLINENEWLINE def test_to_stacked_array_invalid_sample_dims(self):NEWLINE data = xr.Dataset(NEWLINE data_vars={"a": (("x", "y"), [[0, 1, 2], [3, 4, 5]]), "b": ("x", [6, 7])},NEWLINE coords={"y": ["u", "v", "w"]},NEWLINE )NEWLINE with pytest.raises(ValueError):NEWLINE data.to_stacked_array("features", sample_dims=["y"])NEWLINENEWLINE def test_to_stacked_array_name(self):NEWLINE name = "adf9d"NEWLINENEWLINE # make a two dimensional datasetNEWLINE a, b = create_test_stacked_array()NEWLINE D = xr.Dataset({"a": a, "b": b})NEWLINE sample_dims = ["x"]NEWLINENEWLINE y = D.to_stacked_array("features", sample_dims, name=name)NEWLINE assert y.name == nameNEWLINENEWLINE def test_to_stacked_array_dtype_dims(self):NEWLINE # make a two dimensional datasetNEWLINE a, b = create_test_stacked_array()NEWLINE D = xr.Dataset({"a": a, "b": b})NEWLINE sample_dims = ["x"]NEWLINE y = D.to_stacked_array("features", sample_dims)NEWLINE assert y.indexes["features"].levels[1].dtype == D.y.dtypeNEWLINE assert y.dims == ("x", "features")NEWLINENEWLINE def test_to_stacked_array_to_unstacked_dataset(self):NEWLINE # make a two dimensional datasetNEWLINE a, b = create_test_stacked_array()NEWLINE D = xr.Dataset({"a": a, "b": b})NEWLINE sample_dims = ["x"]NEWLINE y = D.to_stacked_array("features", sample_dims).transpose("x", "features")NEWLINENEWLINE x = y.to_unstacked_dataset("features")NEWLINE assert_identical(D, x)NEWLINENEWLINE # test on just one sampleNEWLINE x0 = y[0].to_unstacked_dataset("features")NEWLINE d0 = D.isel(x=0)NEWLINE assert_identical(d0, x0)NEWLINENEWLINE def test_to_stacked_array_to_unstacked_dataset_different_dimension(self):NEWLINE # test when variables have different dimensionalityNEWLINE a, b = create_test_stacked_array()NEWLINE sample_dims = ["x"]NEWLINE D = xr.Dataset({"a": a, "b": b.isel(y=0)})NEWLINENEWLINE y = D.to_stacked_array("features", sample_dims)NEWLINE x = y.to_unstacked_dataset("features")NEWLINE assert_identical(D, x)NEWLINENEWLINE def test_update(self):NEWLINE data = create_test_data(seed=0)NEWLINE expected = data.copy()NEWLINE var2 = Variable("dim1", np.arange(8))NEWLINE actual = data.update({"var2": var2})NEWLINE expected["var2"] = var2NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data.copy()NEWLINE actual_result = actual.update(data)NEWLINE assert actual_result is actualNEWLINE assert_identical(expected, actual)NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE actual = data.update(data, inplace=False)NEWLINENEWLINE other = Dataset(attrs={"new": "attr"})NEWLINE actual = data.copy()NEWLINE actual.update(other)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_update_overwrite_coords(self):NEWLINE data = Dataset({"a": ("x", [1, 2])}, {"b": 3})NEWLINE data.update(Dataset(coords={"b": 4}))NEWLINE expected = Dataset({"a": ("x", [1, 2])}, {"b": 4})NEWLINE assert_identical(data, expected)NEWLINENEWLINE data = Dataset({"a": ("x", [1, 2])}, {"b": 3})NEWLINE data.update(Dataset({"c": 5}, coords={"b": 4}))NEWLINE expected = Dataset({"a": ("x", [1, 2]), "c": 5}, {"b": 4})NEWLINE assert_identical(data, expected)NEWLINENEWLINE data = Dataset({"a": ("x", [1, 2])}, {"b": 3})NEWLINE data.update({"c": DataArray(5, coords={"b": 4})})NEWLINE expected = Dataset({"a": ("x", [1, 2]), "c": 5}, {"b": 3})NEWLINE assert_identical(data, expected)NEWLINENEWLINE def test_update_auto_align(self):NEWLINE ds = Dataset({"x": ("t", [3, 4])}, {"t": [0, 1]})NEWLINENEWLINE expected = Dataset({"x": ("t", [3, 4]), "y": ("t", [np.nan, 5])}, {"t": [0, 1]})NEWLINE actual = ds.copy()NEWLINE other = {"y": ("t", [5]), "t": [1]}NEWLINE with raises_regex(ValueError, "conflicting sizes"):NEWLINE actual.update(other)NEWLINE actual.update(Dataset(other))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.copy()NEWLINE other = Dataset({"y": ("t", [5]), "t": [100]})NEWLINE actual.update(other)NEWLINE expected = Dataset(NEWLINE {"x": ("t", [3, 4]), "y": ("t", [np.nan] * 2)}, {"t": [0, 1]}NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_getitem(self):NEWLINE data = create_test_data()NEWLINE assert isinstance(data["var1"], DataArray)NEWLINE assert_equal(data["var1"].variable, data.variables["var1"])NEWLINE with pytest.raises(KeyError):NEWLINE data["notfound"]NEWLINE with pytest.raises(KeyError):NEWLINE data[["var1", "notfound"]]NEWLINENEWLINE actual = data[["var1", "var2"]]NEWLINE expected = Dataset({"var1": data["var1"], "var2": data["var2"]})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE actual = data["numbers"]NEWLINE expected = DataArray(NEWLINE data["numbers"].variable,NEWLINE {"dim3": data["dim3"], "numbers": data["numbers"]},NEWLINE dims="dim3",NEWLINE name="numbers",NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data[dict(dim1=0)]NEWLINE expected = data.isel(dim1=0)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_getitem_hashable(self):NEWLINE data = create_test_data()NEWLINE data[(3, 4)] = data["var1"] + 1NEWLINE expected = data["var1"] + 1NEWLINE expected.name = (3, 4)NEWLINE assert_identical(expected, data[(3, 4)])NEWLINE with raises_regex(KeyError, "('var1', 'var2')"):NEWLINE data[("var1", "var2")]NEWLINENEWLINE def test_virtual_variables_default_coords(self):NEWLINE dataset = Dataset({"foo": ("x", range(10))})NEWLINE expected = DataArray(range(10), dims="x", name="x")NEWLINE actual = dataset["x"]NEWLINE assert_identical(expected, actual)NEWLINE assert isinstance(actual.variable, IndexVariable)NEWLINENEWLINE actual = dataset[["x", "foo"]]NEWLINE expected = dataset.assign_coords(x=range(10))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_virtual_variables_time(self):NEWLINE # access virtual variablesNEWLINE data = create_test_data()NEWLINE expected = DataArray(NEWLINE 1 + np.arange(20), coords=[data["time"]], dims="time", name="dayofyear"NEWLINE )NEWLINENEWLINE assert_array_equal(NEWLINE data["time.month"].values, data.variables["time"].to_index().monthNEWLINE )NEWLINE assert_array_equal(data["time.season"].values, "DJF")NEWLINE # test virtual variable mathNEWLINE assert_array_equal(data["time.dayofyear"] + 1, 2 + np.arange(20))NEWLINE assert_array_equal(np.sin(data["time.dayofyear"]), np.sin(1 + np.arange(20)))NEWLINE # ensure they become coordinatesNEWLINE expected = Dataset({}, {"dayofyear": data["time.dayofyear"]})NEWLINE actual = data[["time.dayofyear"]]NEWLINE assert_equal(expected, actual)NEWLINE # non-coordinate variablesNEWLINE ds = Dataset({"t": ("x", pd.date_range("2000-01-01", periods=3))})NEWLINE assert (ds["t.year"] == 2000).all()NEWLINENEWLINE def test_virtual_variable_same_name(self):NEWLINE # regression test for GH367NEWLINE times = pd.date_range("2000-01-01", freq="H", periods=5)NEWLINE data = Dataset({"time": times})NEWLINE actual = data["time.time"]NEWLINE expected = DataArray(times.time, [("time", times)], name="time")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_virtual_variable_multiindex(self):NEWLINE # access multi-index levels as virtual variablesNEWLINE data = create_test_multiindex()NEWLINE expected = DataArray(NEWLINE ["a", "a", "b", "b"],NEWLINE name="level_1",NEWLINE coords=[data["x"].to_index()],NEWLINE dims="x",NEWLINE )NEWLINE assert_identical(expected, data["level_1"])NEWLINENEWLINE # combine multi-index level and datetimeNEWLINE dr_index = pd.date_range("1/1/2011", periods=4, freq="H")NEWLINE mindex = pd.MultiIndex.from_arrays(NEWLINE [["a", "a", "b", "b"], dr_index], names=("level_str", "level_date")NEWLINE )NEWLINE data = Dataset({}, {"x": mindex})NEWLINE expected = DataArray(NEWLINE mindex.get_level_values("level_date").hour,NEWLINE name="hour",NEWLINE coords=[mindex],NEWLINE dims="x",NEWLINE )NEWLINE assert_identical(expected, data["level_date.hour"])NEWLINENEWLINE # attribute style accessNEWLINE assert_identical(data.level_str, data["level_str"])NEWLINENEWLINE def test_time_season(self):NEWLINE ds = Dataset({"t": pd.date_range("2000-01-01", periods=12, freq="M")})NEWLINE seas = ["DJF"] * 2 + ["MAM"] * 3 + ["JJA"] * 3 + ["SON"] * 3 + ["DJF"]NEWLINE assert_array_equal(seas, ds["t.season"])NEWLINENEWLINE def test_slice_virtual_variable(self):NEWLINE data = create_test_data()NEWLINE assert_equal(NEWLINE data["time.dayofyear"][:10].variable, Variable(["time"], 1 + np.arange(10))NEWLINE )NEWLINE assert_equal(data["time.dayofyear"][0].variable, Variable([], 1))NEWLINENEWLINE def test_setitem(self):NEWLINE # assign a variableNEWLINE var = Variable(["dim1"], np.random.randn(8))NEWLINE data1 = create_test_data()NEWLINE data1["A"] = varNEWLINE data2 = data1.copy()NEWLINE data2["A"] = varNEWLINE assert_identical(data1, data2)NEWLINE # assign a dataset arrayNEWLINE dv = 2 * data2["A"]NEWLINE data1["B"] = dv.variableNEWLINE data2["B"] = dvNEWLINE assert_identical(data1, data2)NEWLINE # can't assign an ND array without dimensionsNEWLINE with raises_regex(ValueError, "without explicit dimension names"):NEWLINE data2["C"] = var.values.reshape(2, 4)NEWLINE # but can assign a 1D arrayNEWLINE data1["C"] = var.valuesNEWLINE data2["C"] = ("C", var.values)NEWLINE assert_identical(data1, data2)NEWLINE # can assign a scalarNEWLINE data1["scalar"] = 0NEWLINE data2["scalar"] = ([], 0)NEWLINE assert_identical(data1, data2)NEWLINE # can't use the same dimension name as a scalar varNEWLINE with raises_regex(ValueError, "already exists as a scalar"):NEWLINE data1["newvar"] = ("scalar", [3, 4, 5])NEWLINE # can't resize a used dimensionNEWLINE with raises_regex(ValueError, "arguments without labels"):NEWLINE data1["dim1"] = data1["dim1"][:5]NEWLINE # override an existing valueNEWLINE data1["A"] = 3 * data2["A"]NEWLINE assert_equal(data1["A"], 3 * data2["A"])NEWLINENEWLINE with pytest.raises(NotImplementedError):NEWLINE data1[{"x": 0}] = 0NEWLINENEWLINE def test_setitem_pandas(self):NEWLINENEWLINE ds = self.make_example_math_dataset()NEWLINE ds["x"] = np.arange(3)NEWLINE ds_copy = ds.copy()NEWLINE ds_copy["bar"] = ds["bar"].to_pandas()NEWLINENEWLINE assert_equal(ds, ds_copy)NEWLINENEWLINE def test_setitem_auto_align(self):NEWLINE ds = Dataset()NEWLINE ds["x"] = ("y", range(3))NEWLINE ds["y"] = 1 + np.arange(3)NEWLINE expected = Dataset({"x": ("y", range(3)), "y": 1 + np.arange(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds["y"] = DataArray(range(3), dims="y")NEWLINE expected = Dataset({"x": ("y", range(3))}, {"y": range(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds["x"] = DataArray([1, 2], coords=[("y", [0, 1])])NEWLINE expected = Dataset({"x": ("y", [1, 2, np.nan])}, {"y": range(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds["x"] = 42NEWLINE expected = Dataset({"x": 42, "y": range(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds["x"] = DataArray([4, 5, 6, 7], coords=[("y", [0, 1, 2, 3])])NEWLINE expected = Dataset({"x": ("y", [4, 5, 6])}, {"y": range(3)})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE def test_setitem_dimension_override(self):NEWLINE # regression test for GH-3377NEWLINE ds = xr.Dataset({"x": [0, 1, 2]})NEWLINE ds["x"] = ds["x"][:2]NEWLINE expected = Dataset({"x": [0, 1]})NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds = xr.Dataset({"x": [0, 1, 2]})NEWLINE ds["x"] = np.array([0, 1])NEWLINE assert_identical(ds, expected)NEWLINENEWLINE ds = xr.Dataset({"x": [0, 1, 2]})NEWLINE ds.coords["x"] = [0, 1]NEWLINE assert_identical(ds, expected)NEWLINENEWLINE def test_setitem_with_coords(self):NEWLINE # Regression test for GH:2068NEWLINE ds = create_test_data()NEWLINENEWLINE other = DataArray(NEWLINE np.arange(10), dims="dim3", coords={"numbers": ("dim3", np.arange(10))}NEWLINE )NEWLINE expected = ds.copy()NEWLINE expected["var3"] = other.drop_vars("numbers")NEWLINE actual = ds.copy()NEWLINE actual["var3"] = otherNEWLINE assert_identical(expected, actual)NEWLINE assert "numbers" in other.coords # should not change otherNEWLINENEWLINE # with alignmentNEWLINE other = ds["var3"].isel(dim3=slice(1, -1))NEWLINE other["numbers"] = ("dim3", np.arange(8))NEWLINE actual = ds.copy()NEWLINE actual["var3"] = otherNEWLINE assert "numbers" in other.coords # should not change otherNEWLINE expected = ds.copy()NEWLINE expected["var3"] = ds["var3"].isel(dim3=slice(1, -1))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # with non-duplicate coordsNEWLINE other = ds["var3"].isel(dim3=slice(1, -1))NEWLINE other["numbers"] = ("dim3", np.arange(8))NEWLINE other["position"] = ("dim3", np.arange(8))NEWLINE actual = ds.copy()NEWLINE actual["var3"] = otherNEWLINE assert "position" in actualNEWLINE assert "position" in other.coordsNEWLINENEWLINE # assigning a coordinate-only dataarrayNEWLINE actual = ds.copy()NEWLINE other = actual["numbers"]NEWLINE other[0] = 10NEWLINE actual["numbers"] = otherNEWLINE assert actual["numbers"][0] == 10NEWLINENEWLINE # GH: 2099NEWLINE ds = Dataset(NEWLINE {"var": ("x", [1, 2, 3])},NEWLINE coords={"x": [0, 1, 2], "z1": ("x", [1, 2, 3]), "z2": ("x", [1, 2, 3])},NEWLINE )NEWLINE ds["var"] = ds["var"] * 2NEWLINE assert np.allclose(ds["var"], [2, 4, 6])NEWLINENEWLINE def test_setitem_align_new_indexes(self):NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, {"x": [0, 1, 2]})NEWLINE ds["bar"] = DataArray([2, 3, 4], [("x", [1, 2, 3])])NEWLINE expected = Dataset(NEWLINE {"foo": ("x", [1, 2, 3]), "bar": ("x", [np.nan, 2, 3])}, {"x": [0, 1, 2]}NEWLINE )NEWLINE assert_identical(ds, expected)NEWLINENEWLINE def test_assign(self):NEWLINE ds = Dataset()NEWLINE actual = ds.assign(x=[0, 1, 2], y=2)NEWLINE expected = Dataset({"x": [0, 1, 2], "y": 2})NEWLINE assert_identical(actual, expected)NEWLINE assert list(actual.variables) == ["x", "y"]NEWLINE assert_identical(ds, Dataset())NEWLINENEWLINE actual = actual.assign(y=lambda ds: ds.x ** 2)NEWLINE expected = Dataset({"y": ("x", [0, 1, 4]), "x": [0, 1, 2]})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = actual.assign_coords(z=2)NEWLINE expected = Dataset({"y": ("x", [0, 1, 4])}, {"z": 2, "x": [0, 1, 2]})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE ds = Dataset({"a": ("x", range(3))}, {"b": ("x", ["A"] * 2 + ["B"])})NEWLINE actual = ds.groupby("b").assign(c=lambda ds: 2 * ds.a)NEWLINE expected = ds.merge({"c": ("x", [0, 2, 4])})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.groupby("b").assign(c=lambda ds: ds.a.sum())NEWLINE expected = ds.merge({"c": ("x", [1, 1, 2])})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.groupby("b").assign_coords(c=lambda ds: ds.a.sum())NEWLINE expected = expected.set_coords("c")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_assign_coords(self):NEWLINE ds = Dataset()NEWLINENEWLINE actual = ds.assign(x=[0, 1, 2], y=2)NEWLINE actual = actual.assign_coords(x=list("abc"))NEWLINE expected = Dataset({"x": list("abc"), "y": 2})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.assign(x=[0, 1, 2], y=[2, 3])NEWLINE actual = actual.assign_coords({"y": [2.0, 3.0]})NEWLINE expected = ds.assign(x=[0, 1, 2], y=[2.0, 3.0])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_assign_attrs(self):NEWLINE expected = Dataset(attrs=dict(a=1, b=2))NEWLINE new = Dataset()NEWLINE actual = new.assign_attrs(a=1, b=2)NEWLINE assert_identical(actual, expected)NEWLINE assert new.attrs == {}NEWLINENEWLINE expected.attrs["c"] = 3NEWLINE new_actual = actual.assign_attrs({"c": 3})NEWLINE assert_identical(new_actual, expected)NEWLINE assert actual.attrs == dict(a=1, b=2)NEWLINENEWLINE def test_assign_multiindex_level(self):NEWLINE data = create_test_multiindex()NEWLINE with raises_regex(ValueError, "conflicting MultiIndex"):NEWLINE data.assign(level_1=range(4))NEWLINE data.assign_coords(level_1=range(4))NEWLINE # raise an Error when any level name is used as dimension GH:2299NEWLINE with pytest.raises(ValueError):NEWLINE data["y"] = ("level_1", [0, 1])NEWLINENEWLINE def test_merge_multiindex_level(self):NEWLINE data = create_test_multiindex()NEWLINE other = Dataset({"z": ("level_1", [0, 1])}) # conflict dimensionNEWLINE with pytest.raises(ValueError):NEWLINE data.merge(other)NEWLINE other = Dataset({"level_1": ("x", [0, 1])}) # conflict variable nameNEWLINE with pytest.raises(ValueError):NEWLINE data.merge(other)NEWLINENEWLINE def test_setitem_original_non_unique_index(self):NEWLINE # regression test for GH943NEWLINE original = Dataset({"data": ("x", np.arange(5))}, coords={"x": [0, 1, 2, 0, 1]})NEWLINE expected = Dataset({"data": ("x", np.arange(5))}, {"x": range(5)})NEWLINENEWLINE actual = original.copy()NEWLINE actual["x"] = list(range(5))NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = original.copy()NEWLINE actual["x"] = ("x", list(range(5)))NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = original.copy()NEWLINE actual.coords["x"] = list(range(5))NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_setitem_both_non_unique_index(self):NEWLINE # regression test for GH956NEWLINE names = ["joaquin", "manolo", "joaquin"]NEWLINE values = np.random.randint(0, 256, (3, 4, 4))NEWLINE array = DataArray(NEWLINE values, dims=["name", "row", "column"], coords=[names, range(4), range(4)]NEWLINE )NEWLINE expected = Dataset({"first": array, "second": array})NEWLINE actual = array.rename("first").to_dataset()NEWLINE actual["second"] = arrayNEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_setitem_multiindex_level(self):NEWLINE data = create_test_multiindex()NEWLINE with raises_regex(ValueError, "conflicting MultiIndex"):NEWLINE data["level_1"] = range(4)NEWLINENEWLINE def test_delitem(self):NEWLINE data = create_test_data()NEWLINE all_items = set(data.variables)NEWLINE assert set(data.variables) == all_itemsNEWLINE del data["var1"]NEWLINE assert set(data.variables) == all_items - {"var1"}NEWLINE del data["numbers"]NEWLINE assert set(data.variables) == all_items - {"var1", "numbers"}NEWLINE assert "numbers" not in data.coordsNEWLINENEWLINE expected = Dataset()NEWLINE actual = Dataset({"y": ("x", [1, 2])})NEWLINE del actual["y"]NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_squeeze(self):NEWLINE data = Dataset({"foo": (["x", "y", "z"], [[[1], [2]]])})NEWLINE for args in [[], [["x"]], [["x", "z"]]]:NEWLINENEWLINE def get_args(v):NEWLINE return [set(args[0]) & set(v.dims)] if args else []NEWLINENEWLINE expected = Dataset(NEWLINE {k: v.squeeze(*get_args(v)) for k, v in data.variables.items()}NEWLINE )NEWLINE expected = expected.set_coords(data.coords)NEWLINE assert_identical(expected, data.squeeze(*args))NEWLINE # invalid squeezeNEWLINE with raises_regex(ValueError, "cannot select a dimension"):NEWLINE data.squeeze("y")NEWLINENEWLINE def test_squeeze_drop(self):NEWLINE data = Dataset({"foo": ("x", [1])}, {"x": [0]})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.squeeze(drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE expected = Dataset({"foo": 1}, {"x": 0})NEWLINE selected = data.squeeze(drop=False)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE data = Dataset({"foo": (("x", "y"), [[1]])}, {"x": [0], "y": [0]})NEWLINE expected = Dataset({"foo": 1})NEWLINE selected = data.squeeze(drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE expected = Dataset({"foo": ("x", [1])}, {"x": [0]})NEWLINE selected = data.squeeze(dim="y", drop=True)NEWLINE assert_identical(expected, selected)NEWLINENEWLINE data = Dataset({"foo": (("x",), [])}, {"x": []})NEWLINE selected = data.squeeze(drop=True)NEWLINE assert_identical(data, selected)NEWLINENEWLINE def test_groupby(self):NEWLINE data = Dataset(NEWLINE {"z": (["x", "y"], np.random.randn(3, 5))},NEWLINE {"x": ("x", list("abc")), "c": ("x", [0, 1, 0]), "y": range(5)},NEWLINE )NEWLINE groupby = data.groupby("x")NEWLINE assert len(groupby) == 3NEWLINE expected_groups = {"a": 0, "b": 1, "c": 2}NEWLINE assert groupby.groups == expected_groupsNEWLINE expected_items = [NEWLINE ("a", data.isel(x=0)),NEWLINE ("b", data.isel(x=1)),NEWLINE ("c", data.isel(x=2)),NEWLINE ]NEWLINE for actual, expected in zip(groupby, expected_items):NEWLINE assert actual[0] == expected[0]NEWLINE assert_equal(actual[1], expected[1])NEWLINENEWLINE def identity(x):NEWLINE return xNEWLINENEWLINE for k in ["x", "c", "y"]:NEWLINE actual = data.groupby(k, squeeze=False).map(identity)NEWLINE assert_equal(data, actual)NEWLINENEWLINE def test_groupby_returns_new_type(self):NEWLINE data = Dataset({"z": (["x", "y"], np.random.randn(3, 5))})NEWLINENEWLINE actual = data.groupby("x").map(lambda ds: ds["z"])NEWLINE expected = data["z"]NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = data["z"].groupby("x").map(lambda x: x.to_dataset())NEWLINE expected = dataNEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_groupby_iter(self):NEWLINE data = create_test_data()NEWLINE for n, (t, sub) in enumerate(list(data.groupby("dim1"))[:3]):NEWLINE assert data["dim1"][n] == tNEWLINE assert_equal(data["var1"][n], sub["var1"])NEWLINE assert_equal(data["var2"][n], sub["var2"])NEWLINE assert_equal(data["var3"][:, n], sub["var3"])NEWLINENEWLINE def test_groupby_errors(self):NEWLINE data = create_test_data()NEWLINE with raises_regex(TypeError, "`group` must be"):NEWLINE data.groupby(np.arange(10))NEWLINE with raises_regex(ValueError, "length does not match"):NEWLINE data.groupby(data["dim1"][:3])NEWLINE with raises_regex(TypeError, "`group` must be"):NEWLINE data.groupby(data.coords["dim1"].to_index())NEWLINENEWLINE def test_groupby_reduce(self):NEWLINE data = Dataset(NEWLINE {NEWLINE "xy": (["x", "y"], np.random.randn(3, 4)),NEWLINE "xonly": ("x", np.random.randn(3)),NEWLINE "yonly": ("y", np.random.randn(4)),NEWLINE "letters": ("y", ["a", "a", "b", "b"]),NEWLINE }NEWLINE )NEWLINENEWLINE expected = data.mean("y")NEWLINE expected["yonly"] = expected["yonly"].variable.set_dims({"x": 3})NEWLINE actual = data.groupby("x").mean(...)NEWLINE assert_allclose(expected, actual)NEWLINENEWLINE actual = data.groupby("x").mean("y")NEWLINE assert_allclose(expected, actual)NEWLINENEWLINE letters = data["letters"]NEWLINE expected = Dataset(NEWLINE {NEWLINE "xy": data["xy"].groupby(letters).mean(...),NEWLINE "xonly": (data["xonly"].mean().variable.set_dims({"letters": 2})),NEWLINE "yonly": data["yonly"].groupby(letters).mean(),NEWLINE }NEWLINE )NEWLINE actual = data.groupby("letters").mean(...)NEWLINE assert_allclose(expected, actual)NEWLINENEWLINE def test_groupby_math(self):NEWLINE def reorder_dims(x):NEWLINE return x.transpose("dim1", "dim2", "dim3", "time")NEWLINENEWLINE ds = create_test_data()NEWLINE ds["dim1"] = ds["dim1"]NEWLINE for squeeze in [True, False]:NEWLINE grouped = ds.groupby("dim1", squeeze=squeeze)NEWLINENEWLINE expected = reorder_dims(ds + ds.coords["dim1"])NEWLINE actual = grouped + ds.coords["dim1"]NEWLINE assert_identical(expected, reorder_dims(actual))NEWLINENEWLINE actual = ds.coords["dim1"] + groupedNEWLINE assert_identical(expected, reorder_dims(actual))NEWLINENEWLINE ds2 = 2 * dsNEWLINE expected = reorder_dims(ds + ds2)NEWLINE actual = grouped + ds2NEWLINE assert_identical(expected, reorder_dims(actual))NEWLINENEWLINE actual = ds2 + groupedNEWLINE assert_identical(expected, reorder_dims(actual))NEWLINENEWLINE grouped = ds.groupby("numbers")NEWLINE zeros = DataArray([0, 0, 0, 0], [("numbers", range(4))])NEWLINE expected = (ds + Variable("dim3", np.zeros(10))).transpose(NEWLINE "dim3", "dim1", "dim2", "time"NEWLINE )NEWLINE actual = grouped + zerosNEWLINE assert_equal(expected, actual)NEWLINENEWLINE actual = zeros + groupedNEWLINE assert_equal(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "incompat.* grouped binary"):NEWLINE grouped + dsNEWLINE with raises_regex(ValueError, "incompat.* grouped binary"):NEWLINE ds + groupedNEWLINE with raises_regex(TypeError, "only support binary ops"):NEWLINE grouped + 1NEWLINE with raises_regex(TypeError, "only support binary ops"):NEWLINE grouped + groupedNEWLINE with raises_regex(TypeError, "in-place operations"):NEWLINE ds += groupedNEWLINENEWLINE ds = Dataset(NEWLINE {NEWLINE "x": ("time", np.arange(100)),NEWLINE "time": pd.date_range("2000-01-01", periods=100),NEWLINE }NEWLINE )NEWLINE with raises_regex(ValueError, "incompat.* grouped binary"):NEWLINE ds + ds.groupby("time.month")NEWLINENEWLINE def test_groupby_math_virtual(self):NEWLINE ds = Dataset(NEWLINE {"x": ("t", [1, 2, 3])}, {"t": pd.date_range("20100101", periods=3)}NEWLINE )NEWLINE grouped = ds.groupby("t.day")NEWLINE actual = grouped - grouped.mean(...)NEWLINE expected = Dataset({"x": ("t", [0, 0, 0])}, ds[["t", "t.day"]])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_groupby_nan(self):NEWLINE # nan should be excluded from groupbyNEWLINE ds = Dataset({"foo": ("x", [1, 2, 3, 4])}, {"bar": ("x", [1, 1, 2, np.nan])})NEWLINE actual = ds.groupby("bar").mean(...)NEWLINE expected = Dataset({"foo": ("bar", [1.5, 3]), "bar": [1, 2]})NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_groupby_order(self):NEWLINE # groupby should preserve variables orderNEWLINE ds = Dataset()NEWLINE for vn in ["a", "b", "c"]:NEWLINE ds[vn] = DataArray(np.arange(10), dims=["t"])NEWLINE data_vars_ref = list(ds.data_vars.keys())NEWLINE ds = ds.groupby("t").mean(...)NEWLINE data_vars = list(ds.data_vars.keys())NEWLINE assert data_vars == data_vars_refNEWLINE # coords are now at the end of the list, so the test below failsNEWLINE # all_vars = list(ds.variables.keys())NEWLINE # all_vars_ref = list(ds.variables.keys())NEWLINE # self.assertEqual(all_vars, all_vars_ref)NEWLINENEWLINE def test_resample_and_first(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINENEWLINE actual = ds.resample(time="1D").first(keep_attrs=True)NEWLINE expected = ds.isel(time=[0, 4, 8])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # upsamplingNEWLINE expected_time = pd.date_range("2000-01-01", freq="3H", periods=19)NEWLINE expected = ds.reindex(time=expected_time)NEWLINE actual = ds.resample(time="3H")NEWLINE for how in ["mean", "sum", "first", "last"]:NEWLINE method = getattr(actual, how)NEWLINE result = method()NEWLINE assert_equal(expected, result)NEWLINE for method in [np.mean]:NEWLINE result = actual.reduce(method)NEWLINE assert_equal(expected, result)NEWLINENEWLINE def test_resample_min_count(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE # inject nanNEWLINE ds["foo"] = xr.where(ds["foo"] > 2.0, np.nan, ds["foo"])NEWLINENEWLINE actual = ds.resample(time="1D").sum(min_count=1)NEWLINE expected = xr.concat(NEWLINE [NEWLINE ds.isel(time=slice(i * 4, (i + 1) * 4)).sum("time", min_count=1)NEWLINE for i in range(3)NEWLINE ],NEWLINE dim=actual["time"],NEWLINE )NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_resample_by_mean_with_keep_attrs(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE ds.attrs["dsmeta"] = "dsdata"NEWLINENEWLINE resampled_ds = ds.resample(time="1D").mean(keep_attrs=True)NEWLINE actual = resampled_ds["bar"].attrsNEWLINE expected = ds["bar"].attrsNEWLINE assert expected == actualNEWLINENEWLINE actual = resampled_ds.attrsNEWLINE expected = ds.attrsNEWLINE assert expected == actualNEWLINENEWLINE def test_resample_loffset(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE ds.attrs["dsmeta"] = "dsdata"NEWLINENEWLINE actual = ds.resample(time="24H", loffset="-12H").mean("time").timeNEWLINE expected = xr.DataArray(NEWLINE ds.bar.to_series().resample("24H", loffset="-12H").mean()NEWLINE ).timeNEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_resample_by_mean_discarding_attrs(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE ds.attrs["dsmeta"] = "dsdata"NEWLINENEWLINE resampled_ds = ds.resample(time="1D").mean(keep_attrs=False)NEWLINENEWLINE assert resampled_ds["bar"].attrs == {}NEWLINE assert resampled_ds.attrs == {}NEWLINENEWLINE def test_resample_by_last_discarding_attrs(self):NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINE ds.attrs["dsmeta"] = "dsdata"NEWLINENEWLINE resampled_ds = ds.resample(time="1D").last(keep_attrs=False)NEWLINENEWLINE assert resampled_ds["bar"].attrs == {}NEWLINE assert resampled_ds.attrs == {}NEWLINENEWLINE @requires_scipyNEWLINE def test_resample_drop_nondim_coords(self):NEWLINE xs = np.arange(6)NEWLINE ys = np.arange(3)NEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=5)NEWLINE data = np.tile(np.arange(5), (6, 3, 1))NEWLINE xx, yy = np.meshgrid(xs * 5, ys * 2.5)NEWLINE tt = np.arange(len(times), dtype=int)NEWLINE array = DataArray(data, {"time": times, "x": xs, "y": ys}, ("x", "y", "time"))NEWLINE xcoord = DataArray(xx.T, {"x": xs, "y": ys}, ("x", "y"))NEWLINE ycoord = DataArray(yy.T, {"x": xs, "y": ys}, ("x", "y"))NEWLINE tcoord = DataArray(tt, {"time": times}, ("time",))NEWLINE ds = Dataset({"data": array, "xc": xcoord, "yc": ycoord, "tc": tcoord})NEWLINE ds = ds.set_coords(["xc", "yc", "tc"])NEWLINENEWLINE # Re-sampleNEWLINE actual = ds.resample(time="12H").mean("time")NEWLINE assert "tc" not in actual.coordsNEWLINENEWLINE # Up-sample - fillingNEWLINE actual = ds.resample(time="1H").ffill()NEWLINE assert "tc" not in actual.coordsNEWLINENEWLINE # Up-sample - interpolationNEWLINE actual = ds.resample(time="1H").interpolate("linear")NEWLINE assert "tc" not in actual.coordsNEWLINENEWLINE def test_resample_old_api(self):NEWLINENEWLINE times = pd.date_range("2000-01-01", freq="6H", periods=10)NEWLINE ds = Dataset(NEWLINE {NEWLINE "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)),NEWLINE "bar": ("time", np.random.randn(10), {"meta": "data"}),NEWLINE "time": times,NEWLINE }NEWLINE )NEWLINENEWLINE with raises_regex(TypeError, r"resample\(\) no longer supports"):NEWLINE ds.resample("1D", "time")NEWLINENEWLINE with raises_regex(TypeError, r"resample\(\) no longer supports"):NEWLINE ds.resample("1D", dim="time", how="mean")NEWLINENEWLINE with raises_regex(TypeError, r"resample\(\) no longer supports"):NEWLINE ds.resample("1D", dim="time")NEWLINENEWLINE def test_resample_ds_da_are_the_same(self):NEWLINE time = pd.date_range("2000-01-01", freq="6H", periods=365 * 4)NEWLINE ds = xr.Dataset(NEWLINE {NEWLINE "foo": (("time", "x"), np.random.randn(365 * 4, 5)),NEWLINE "time": time,NEWLINE "x": np.arange(5),NEWLINE }NEWLINE )NEWLINE assert_identical(NEWLINE ds.resample(time="M").mean()["foo"], ds.foo.resample(time="M").mean()NEWLINE )NEWLINENEWLINE def test_ds_resample_apply_func_args(self):NEWLINE def func(arg1, arg2, arg3=0.0):NEWLINE return arg1.mean("time") + arg2 + arg3NEWLINENEWLINE times = pd.date_range("2000", freq="D", periods=3)NEWLINE ds = xr.Dataset({"foo": ("time", [1.0, 1.0, 1.0]), "time": times})NEWLINE expected = xr.Dataset({"foo": ("time", [3.0, 3.0, 3.0]), "time": times})NEWLINE actual = ds.resample(time="D").map(func, args=(1.0,), arg3=1.0)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_to_array(self):NEWLINE ds = Dataset(NEWLINE {"a": 1, "b": ("x", [1, 2, 3])},NEWLINE coords={"c": 42},NEWLINE attrs={"Conventions": "None"},NEWLINE )NEWLINE data = [[1, 1, 1], [1, 2, 3]]NEWLINE coords = {"c": 42, "variable": ["a", "b"]}NEWLINE dims = ("variable", "x")NEWLINE expected = DataArray(data, coords, dims, attrs=ds.attrs)NEWLINE actual = ds.to_array()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.to_array("abc", name="foo")NEWLINE expected = expected.rename({"variable": "abc"}).rename("foo")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_to_and_from_dataframe(self):NEWLINE x = np.random.randn(10)NEWLINE y = np.random.randn(10)NEWLINE t = list("abcdefghij")NEWLINE ds = Dataset({"a": ("t", x), "b": ("t", y), "t": ("t", t)})NEWLINE expected = pd.DataFrame(NEWLINE np.array([x, y]).T, columns=["a", "b"], index=pd.Index(t, name="t")NEWLINE )NEWLINE actual = ds.to_dataframe()NEWLINE # use the .equals method to check all DataFrame metadataNEWLINE assert expected.equals(actual), (expected, actual)NEWLINENEWLINE # verify coords are includedNEWLINE actual = ds.set_coords("b").to_dataframe()NEWLINE assert expected.equals(actual), (expected, actual)NEWLINENEWLINE # check roundtripNEWLINE assert_identical(ds, Dataset.from_dataframe(actual))NEWLINENEWLINE # test a case with a MultiIndexNEWLINE w = np.random.randn(2, 3)NEWLINE ds = Dataset({"w": (("x", "y"), w)})NEWLINE ds["y"] = ("y", list("abc"))NEWLINE exp_index = pd.MultiIndex.from_arrays(NEWLINE [[0, 0, 0, 1, 1, 1], ["a", "b", "c", "a", "b", "c"]], names=["x", "y"]NEWLINE )NEWLINE expected = pd.DataFrame(w.reshape(-1), columns=["w"], index=exp_index)NEWLINE actual = ds.to_dataframe()NEWLINE assert expected.equals(actual)NEWLINENEWLINE # check roundtripNEWLINE assert_identical(ds.assign_coords(x=[0, 1]), Dataset.from_dataframe(actual))NEWLINENEWLINE # check pathological casesNEWLINE df = pd.DataFrame([1])NEWLINE actual = Dataset.from_dataframe(df)NEWLINE expected = Dataset({0: ("index", [1])}, {"index": [0]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE df = pd.DataFrame()NEWLINE actual = Dataset.from_dataframe(df)NEWLINE expected = Dataset(coords={"index": []})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # GH697NEWLINE df = pd.DataFrame({"A": []})NEWLINE actual = Dataset.from_dataframe(df)NEWLINE expected = Dataset({"A": DataArray([], dims=("index",))}, {"index": []})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # regression test for GH278NEWLINE # use int64 to ensure consistent results for the pandas .equals methodNEWLINE # on windows (which requires the same dtype)NEWLINE ds = Dataset({"x": pd.Index(["bar"]), "a": ("y", np.array([1], "int64"))}).isel(NEWLINE x=0NEWLINE )NEWLINE # use .loc to ensure consistent results on Python 3NEWLINE actual = ds.to_dataframe().loc[:, ["a", "x"]]NEWLINE expected = pd.DataFrame(NEWLINE [[1, "bar"]], index=pd.Index([0], name="y"), columns=["a", "x"]NEWLINE )NEWLINE assert expected.equals(actual), (expected, actual)NEWLINENEWLINE ds = Dataset({"x": np.array([0], "int64"), "y": np.array([1], "int64")})NEWLINE actual = ds.to_dataframe()NEWLINE idx = pd.MultiIndex.from_arrays([[0], [1]], names=["x", "y"])NEWLINE expected = pd.DataFrame([[]], index=idx)NEWLINE assert expected.equals(actual), (expected, actual)NEWLINENEWLINE @requires_sparseNEWLINE def test_from_dataframe_sparse(self):NEWLINE import sparseNEWLINENEWLINE df_base = pd.DataFrame(NEWLINE {"x": range(10), "y": list("abcdefghij"), "z": np.arange(0, 100, 10)}NEWLINE )NEWLINENEWLINE ds_sparse = Dataset.from_dataframe(df_base.set_index("x"), sparse=True)NEWLINE ds_dense = Dataset.from_dataframe(df_base.set_index("x"), sparse=False)NEWLINE assert isinstance(ds_sparse["y"].data, sparse.COO)NEWLINE assert isinstance(ds_sparse["z"].data, sparse.COO)NEWLINE ds_sparse["y"].data = ds_sparse["y"].data.todense()NEWLINE ds_sparse["z"].data = ds_sparse["z"].data.todense()NEWLINE assert_identical(ds_dense, ds_sparse)NEWLINENEWLINE ds_sparse = Dataset.from_dataframe(df_base.set_index(["x", "y"]), sparse=True)NEWLINE ds_dense = Dataset.from_dataframe(df_base.set_index(["x", "y"]), sparse=False)NEWLINE assert isinstance(ds_sparse["z"].data, sparse.COO)NEWLINE ds_sparse["z"].data = ds_sparse["z"].data.todense()NEWLINE assert_identical(ds_dense, ds_sparse)NEWLINENEWLINE def test_to_and_from_empty_dataframe(self):NEWLINE # GH697NEWLINE expected = pd.DataFrame({"foo": []})NEWLINE ds = Dataset.from_dataframe(expected)NEWLINE assert len(ds["foo"]) == 0NEWLINE actual = ds.to_dataframe()NEWLINE assert len(actual) == 0NEWLINE assert expected.equals(actual)NEWLINENEWLINE def test_from_dataframe_non_unique_columns(self):NEWLINE # regression test for GH449NEWLINE df = pd.DataFrame(np.zeros((2, 2)))NEWLINE df.columns = ["foo", "foo"]NEWLINE with raises_regex(ValueError, "non-unique columns"):NEWLINE Dataset.from_dataframe(df)NEWLINENEWLINE def test_convert_dataframe_with_many_types_and_multiindex(self):NEWLINE # regression test for GH737NEWLINE df = pd.DataFrame(NEWLINE {NEWLINE "a": list("abc"),NEWLINE "b": list(range(1, 4)),NEWLINE "c": np.arange(3, 6).astype("u1"),NEWLINE "d": np.arange(4.0, 7.0, dtype="float64"),NEWLINE "e": [True, False, True],NEWLINE "f": pd.Categorical(list("abc")),NEWLINE "g": pd.date_range("20130101", periods=3),NEWLINE "h": pd.date_range("20130101", periods=3, tz="US/Eastern"),NEWLINE }NEWLINE )NEWLINE df.index = pd.MultiIndex.from_product([["a"], range(3)], names=["one", "two"])NEWLINE roundtripped = Dataset.from_dataframe(df).to_dataframe()NEWLINE # we can't do perfectly, but we should be at least as faithful asNEWLINE # np.asarrayNEWLINE expected = df.apply(np.asarray)NEWLINE assert roundtripped.equals(expected)NEWLINENEWLINE def test_to_and_from_dict(self):NEWLINE # <xarray.Dataset>NEWLINE # Dimensions: (t: 10)NEWLINE # Coordinates:NEWLINE # * t (t) <U1 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'NEWLINE # Data variables:NEWLINE # a (t) float64 0.6916 -1.056 -1.163 0.9792 -0.7865 ...NEWLINE # b (t) float64 1.32 0.1954 1.91 1.39 0.519 -0.2772 ...NEWLINE x = np.random.randn(10)NEWLINE y = np.random.randn(10)NEWLINE t = list("abcdefghij")NEWLINE ds = Dataset({"a": ("t", x), "b": ("t", y), "t": ("t", t)})NEWLINE expected = {NEWLINE "coords": {"t": {"dims": ("t",), "data": t, "attrs": {}}},NEWLINE "attrs": {},NEWLINE "dims": {"t": 10},NEWLINE "data_vars": {NEWLINE "a": {"dims": ("t",), "data": x.tolist(), "attrs": {}},NEWLINE "b": {"dims": ("t",), "data": y.tolist(), "attrs": {}},NEWLINE },NEWLINE }NEWLINENEWLINE actual = ds.to_dict()NEWLINENEWLINE # check that they are identicalNEWLINE assert expected == actualNEWLINENEWLINE # check roundtripNEWLINE assert_identical(ds, Dataset.from_dict(actual))NEWLINENEWLINE # check the data=False optionNEWLINE expected_no_data = expected.copy()NEWLINE del expected_no_data["coords"]["t"]["data"]NEWLINE del expected_no_data["data_vars"]["a"]["data"]NEWLINE del expected_no_data["data_vars"]["b"]["data"]NEWLINE endiantype = "<U1" if sys.byteorder == "little" else ">U1"NEWLINE expected_no_data["coords"]["t"].update({"dtype": endiantype, "shape": (10,)})NEWLINE expected_no_data["data_vars"]["a"].update({"dtype": "float64", "shape": (10,)})NEWLINE expected_no_data["data_vars"]["b"].update({"dtype": "float64", "shape": (10,)})NEWLINE actual_no_data = ds.to_dict(data=False)NEWLINE assert expected_no_data == actual_no_dataNEWLINENEWLINE # verify coords are included roundtripNEWLINE expected_ds = ds.set_coords("b")NEWLINE actual = Dataset.from_dict(expected_ds.to_dict())NEWLINENEWLINE assert_identical(expected_ds, actual)NEWLINENEWLINE # test some incomplete dicts:NEWLINE # this one has no attrs field, the dims are strings, and x, y areNEWLINE # np.arraysNEWLINENEWLINE d = {NEWLINE "coords": {"t": {"dims": "t", "data": t}},NEWLINE "dims": "t",NEWLINE "data_vars": {"a": {"dims": "t", "data": x}, "b": {"dims": "t", "data": y}},NEWLINE }NEWLINE assert_identical(ds, Dataset.from_dict(d))NEWLINENEWLINE # this is kind of a flattened version with no coords, or data_varsNEWLINE d = {NEWLINE "a": {"dims": "t", "data": x},NEWLINE "t": {"data": t, "dims": "t"},NEWLINE "b": {"dims": "t", "data": y},NEWLINE }NEWLINE assert_identical(ds, Dataset.from_dict(d))NEWLINENEWLINE # this one is missing some necessary informationNEWLINE d = {NEWLINE "a": {"data": x},NEWLINE "t": {"data": t, "dims": "t"},NEWLINE "b": {"dims": "t", "data": y},NEWLINE }NEWLINE with raises_regex(ValueError, "cannot convert dict " "without the key 'dims'"):NEWLINE Dataset.from_dict(d)NEWLINENEWLINE def test_to_and_from_dict_with_time_dim(self):NEWLINE x = np.random.randn(10, 3)NEWLINE y = np.random.randn(10, 3)NEWLINE t = pd.date_range("20130101", periods=10)NEWLINE lat = [77.7, 83.2, 76]NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": (["t", "lat"], x),NEWLINE "b": (["t", "lat"], y),NEWLINE "t": ("t", t),NEWLINE "lat": ("lat", lat),NEWLINE }NEWLINE )NEWLINE roundtripped = Dataset.from_dict(ds.to_dict())NEWLINE assert_identical(ds, roundtripped)NEWLINENEWLINE def test_to_and_from_dict_with_nan_nat(self):NEWLINE x = np.random.randn(10, 3)NEWLINE y = np.random.randn(10, 3)NEWLINE y[2] = np.nanNEWLINE t = pd.Series(pd.date_range("20130101", periods=10))NEWLINE t[2] = np.nanNEWLINENEWLINE lat = [77.7, 83.2, 76]NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": (["t", "lat"], x),NEWLINE "b": (["t", "lat"], y),NEWLINE "t": ("t", t),NEWLINE "lat": ("lat", lat),NEWLINE }NEWLINE )NEWLINE roundtripped = Dataset.from_dict(ds.to_dict())NEWLINE assert_identical(ds, roundtripped)NEWLINENEWLINE def test_to_dict_with_numpy_attrs(self):NEWLINE # this doesn't need to roundtripNEWLINE x = np.random.randn(10)NEWLINE y = np.random.randn(10)NEWLINE t = list("abcdefghij")NEWLINE attrs = {NEWLINE "created": np.float64(1998),NEWLINE "coords": np.array([37, -110.1, 100]),NEWLINE "maintainer": "bar",NEWLINE }NEWLINE ds = Dataset({"a": ("t", x, attrs), "b": ("t", y, attrs), "t": ("t", t)})NEWLINE expected_attrs = {NEWLINE "created": attrs["created"].item(),NEWLINE "coords": attrs["coords"].tolist(),NEWLINE "maintainer": "bar",NEWLINE }NEWLINE actual = ds.to_dict()NEWLINENEWLINE # check that they are identicalNEWLINE assert expected_attrs == actual["data_vars"]["a"]["attrs"]NEWLINENEWLINE def test_pickle(self):NEWLINE data = create_test_data()NEWLINE roundtripped = pickle.loads(pickle.dumps(data))NEWLINE assert_identical(data, roundtripped)NEWLINE # regression test for #167:NEWLINE assert data.dims == roundtripped.dimsNEWLINENEWLINE def test_lazy_load(self):NEWLINE store = InaccessibleVariableDataStore()NEWLINE create_test_data().dump_to_store(store)NEWLINENEWLINE for decode_cf in [True, False]:NEWLINE ds = open_dataset(store, decode_cf=decode_cf)NEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE ds.load()NEWLINE with pytest.raises(UnexpectedDataAccess):NEWLINE ds["var1"].valuesNEWLINENEWLINE # these should not raise UnexpectedDataAccess:NEWLINE ds.isel(time=10)NEWLINE ds.isel(time=slice(10), dim1=[0]).isel(dim1=0, dim2=-1)NEWLINENEWLINE def test_dropna(self):NEWLINE x = np.random.randn(4, 4)NEWLINE x[::2, 0] = np.nanNEWLINE y = np.random.randn(4)NEWLINE y[-1] = np.nanNEWLINE ds = Dataset({"foo": (("a", "b"), x), "bar": (("b", y))})NEWLINENEWLINE expected = ds.isel(a=slice(1, None, 2))NEWLINE actual = ds.dropna("a")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE expected = ds.isel(b=slice(1, 3))NEWLINE actual = ds.dropna("b")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("b", subset=["foo", "bar"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE expected = ds.isel(b=slice(1, None))NEWLINE actual = ds.dropna("b", subset=["foo"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE expected = ds.isel(b=slice(3))NEWLINE actual = ds.dropna("b", subset=["bar"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("a", subset=[])NEWLINE assert_identical(actual, ds)NEWLINENEWLINE actual = ds.dropna("a", subset=["bar"])NEWLINE assert_identical(actual, ds)NEWLINENEWLINE actual = ds.dropna("a", how="all")NEWLINE assert_identical(actual, ds)NEWLINENEWLINE actual = ds.dropna("b", how="all", subset=["bar"])NEWLINE expected = ds.isel(b=[0, 1, 2])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("b", thresh=1, subset=["bar"])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("b", thresh=2)NEWLINE assert_identical(actual, ds)NEWLINENEWLINE actual = ds.dropna("b", thresh=4)NEWLINE expected = ds.isel(b=[1, 2, 3])NEWLINE assert_identical(actual, expected)NEWLINENEWLINE actual = ds.dropna("a", thresh=3)NEWLINE expected = ds.isel(a=[1, 3])NEWLINE assert_identical(actual, ds)NEWLINENEWLINE with raises_regex(ValueError, "a single dataset dimension"):NEWLINE ds.dropna("foo")NEWLINE with raises_regex(ValueError, "invalid how"):NEWLINE ds.dropna("a", how="somehow")NEWLINE with raises_regex(TypeError, "must specify how or thresh"):NEWLINE ds.dropna("a", how=None)NEWLINENEWLINE def test_fillna(self):NEWLINE ds = Dataset({"a": ("x", [np.nan, 1, np.nan, 3])}, {"x": [0, 1, 2, 3]})NEWLINENEWLINE # fill with -1NEWLINE actual = ds.fillna(-1)NEWLINE expected = Dataset({"a": ("x", [-1, 1, -1, 3])}, {"x": [0, 1, 2, 3]})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna({"a": -1})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE other = Dataset({"a": -1})NEWLINE actual = ds.fillna(other)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna({"a": other.a})NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # fill with range(4)NEWLINE b = DataArray(range(4), coords=[("x", range(4))])NEWLINE actual = ds.fillna(b)NEWLINE expected = b.rename("a").to_dataset()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna(expected)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna(range(4))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.fillna(b[:3])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # okay to only include some data variablesNEWLINE ds["b"] = np.nanNEWLINE actual = ds.fillna({"a": -1})NEWLINE expected = Dataset(NEWLINE {"a": ("x", [-1, 1, -1, 3]), "b": np.nan}, {"x": [0, 1, 2, 3]}NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # but new data variables is not okayNEWLINE with raises_regex(ValueError, "must be contained"):NEWLINE ds.fillna({"x": 0})NEWLINENEWLINE # empty argument should be OKNEWLINE result = ds.fillna({})NEWLINE assert_identical(ds, result)NEWLINENEWLINE result = ds.fillna(Dataset(coords={"c": 42}))NEWLINE expected = ds.assign_coords(c=42)NEWLINE assert_identical(expected, result)NEWLINENEWLINE # groupbyNEWLINE expected = Dataset({"a": ("x", range(4))}, {"x": [0, 1, 2, 3]})NEWLINE for target in [ds, expected]:NEWLINE target.coords["b"] = ("x", [0, 0, 1, 1])NEWLINE actual = ds.groupby("b").fillna(DataArray([0, 2], dims="b"))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.groupby("b").fillna(Dataset({"a": ("b", [0, 2])}))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # attrs with groupbyNEWLINE ds.attrs["attr"] = "ds"NEWLINE ds.a.attrs["attr"] = "da"NEWLINE actual = ds.groupby("b").fillna(Dataset({"a": ("b", [0, 2])}))NEWLINE assert actual.attrs == ds.attrsNEWLINE assert actual.a.name == "a"NEWLINE assert actual.a.attrs == ds.a.attrsNEWLINENEWLINE da = DataArray(range(5), name="a", attrs={"attr": "da"})NEWLINE actual = da.fillna(1)NEWLINE assert actual.name == "a"NEWLINE assert actual.attrs == da.attrsNEWLINENEWLINE ds = Dataset({"a": da}, attrs={"attr": "ds"})NEWLINE actual = ds.fillna({"a": 1})NEWLINE assert actual.attrs == ds.attrsNEWLINE assert actual.a.name == "a"NEWLINE assert actual.a.attrs == ds.a.attrsNEWLINENEWLINE def test_where(self):NEWLINE ds = Dataset({"a": ("x", range(5))})NEWLINE expected = Dataset({"a": ("x", [np.nan, np.nan, 2, 3, 4])})NEWLINE actual = ds.where(ds > 1)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.where(ds.a > 1)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.where(ds.a.values > 1)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.where(True)NEWLINE assert_identical(ds, actual)NEWLINENEWLINE expected = ds.copy(deep=True)NEWLINE expected["a"].values = [np.nan] * 5NEWLINE actual = ds.where(False)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 2dNEWLINE ds = Dataset({"a": (("x", "y"), [[0, 1], [2, 3]])})NEWLINE expected = Dataset({"a": (("x", "y"), [[np.nan, 1], [2, 3]])})NEWLINE actual = ds.where(ds > 0)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # groupbyNEWLINE ds = Dataset({"a": ("x", range(5))}, {"c": ("x", [0, 0, 1, 1, 1])})NEWLINE cond = Dataset({"a": ("c", [True, False])})NEWLINE expected = ds.copy(deep=True)NEWLINE expected["a"].values = [0, 1] + [np.nan] * 3NEWLINE actual = ds.groupby("c").where(cond)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # attrs with groupbyNEWLINE ds.attrs["attr"] = "ds"NEWLINE ds.a.attrs["attr"] = "da"NEWLINE actual = ds.groupby("c").where(cond)NEWLINE assert actual.attrs == ds.attrsNEWLINE assert actual.a.name == "a"NEWLINE assert actual.a.attrs == ds.a.attrsNEWLINENEWLINE # attrsNEWLINE da = DataArray(range(5), name="a", attrs={"attr": "da"})NEWLINE actual = da.where(da.values > 1)NEWLINE assert actual.name == "a"NEWLINE assert actual.attrs == da.attrsNEWLINENEWLINE ds = Dataset({"a": da}, attrs={"attr": "ds"})NEWLINE actual = ds.where(ds > 0)NEWLINE assert actual.attrs == ds.attrsNEWLINE assert actual.a.name == "a"NEWLINE assert actual.a.attrs == ds.a.attrsNEWLINENEWLINE def test_where_other(self):NEWLINE ds = Dataset({"a": ("x", range(5))}, {"x": range(5)})NEWLINE expected = Dataset({"a": ("x", [-1, -1, 2, 3, 4])}, {"x": range(5)})NEWLINE actual = ds.where(ds > 1, -1)NEWLINE assert_equal(expected, actual)NEWLINE assert actual.a.dtype == intNEWLINENEWLINE with raises_regex(ValueError, "cannot set"):NEWLINE ds.where(ds > 1, other=0, drop=True)NEWLINENEWLINE with raises_regex(ValueError, "indexes .* are not equal"):NEWLINE ds.where(ds > 1, ds.isel(x=slice(3)))NEWLINENEWLINE with raises_regex(ValueError, "exact match required"):NEWLINE ds.where(ds > 1, ds.assign(b=2))NEWLINENEWLINE def test_where_drop(self):NEWLINE # if drop=TrueNEWLINENEWLINE # 1dNEWLINE # data array caseNEWLINE array = DataArray(range(5), coords=[range(5)], dims=["x"])NEWLINE expected = DataArray(range(5)[2:], coords=[range(5)[2:]], dims=["x"])NEWLINE actual = array.where(array > 1, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # dataset caseNEWLINE ds = Dataset({"a": array})NEWLINE expected = Dataset({"a": expected})NEWLINENEWLINE actual = ds.where(ds > 1, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.where(ds.a > 1, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "must be a"):NEWLINE ds.where(np.arange(5) > 1, drop=True)NEWLINENEWLINE # 1d with odd coordinatesNEWLINE array = DataArray(NEWLINE np.array([2, 7, 1, 8, 3]), coords=[np.array([3, 1, 4, 5, 9])], dims=["x"]NEWLINE )NEWLINE expected = DataArray(NEWLINE np.array([7, 8, 3]), coords=[np.array([1, 5, 9])], dims=["x"]NEWLINE )NEWLINE actual = array.where(array > 2, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 1d multiple variablesNEWLINE ds = Dataset({"a": (("x"), [0, 1, 2, 3]), "b": (("x"), [4, 5, 6, 7])})NEWLINE expected = Dataset(NEWLINE {"a": (("x"), [np.nan, 1, 2, 3]), "b": (("x"), [4, 5, 6, np.nan])}NEWLINE )NEWLINE actual = ds.where((ds > 0) & (ds < 7), drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 2dNEWLINE ds = Dataset({"a": (("x", "y"), [[0, 1], [2, 3]])})NEWLINE expected = Dataset({"a": (("x", "y"), [[np.nan, 1], [2, 3]])})NEWLINE actual = ds.where(ds > 0, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 2d with odd coordinatesNEWLINE ds = Dataset(NEWLINE {"a": (("x", "y"), [[0, 1], [2, 3]])},NEWLINE coords={NEWLINE "x": [4, 3],NEWLINE "y": [1, 2],NEWLINE "z": (["x", "y"], [[np.e, np.pi], [np.pi * np.e, np.pi * 3]]),NEWLINE },NEWLINE )NEWLINE expected = Dataset(NEWLINE {"a": (("x", "y"), [[3]])},NEWLINE coords={"x": [3], "y": [2], "z": (["x", "y"], [[np.pi * 3]])},NEWLINE )NEWLINE actual = ds.where(ds > 2, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # 2d multiple variablesNEWLINE ds = Dataset(NEWLINE {"a": (("x", "y"), [[0, 1], [2, 3]]), "b": (("x", "y"), [[4, 5], [6, 7]])}NEWLINE )NEWLINE expected = Dataset(NEWLINE {NEWLINE "a": (("x", "y"), [[np.nan, 1], [2, 3]]),NEWLINE "b": (("x", "y"), [[4, 5], [6, 7]]),NEWLINE }NEWLINE )NEWLINE actual = ds.where(ds > 0, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_where_drop_empty(self):NEWLINE # regression test for GH1341NEWLINE array = DataArray(np.random.rand(100, 10), dims=["nCells", "nVertLevels"])NEWLINE mask = DataArray(np.zeros((100,), dtype="bool"), dims="nCells")NEWLINE actual = array.where(mask, drop=True)NEWLINE expected = DataArray(np.zeros((0, 10)), dims=["nCells", "nVertLevels"])NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_where_drop_no_indexes(self):NEWLINE ds = Dataset({"foo": ("x", [0.0, 1.0])})NEWLINE expected = Dataset({"foo": ("x", [1.0])})NEWLINE actual = ds.where(ds == 1, drop=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce(self):NEWLINE data = create_test_data()NEWLINENEWLINE assert len(data.mean().coords) == 0NEWLINENEWLINE actual = data.max()NEWLINE expected = Dataset({k: v.max() for k, v in data.data_vars.items()})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE assert_equal(data.min(dim=["dim1"]), data.min(dim="dim1"))NEWLINENEWLINE for reduct, expected in [NEWLINE ("dim2", ["dim1", "dim3", "time"]),NEWLINE (["dim2", "time"], ["dim1", "dim3"]),NEWLINE (("dim2", "time"), ["dim1", "dim3"]),NEWLINE ((), ["dim1", "dim2", "dim3", "time"]),NEWLINE ]:NEWLINE actual = list(data.min(dim=reduct).dims)NEWLINE assert actual == expectedNEWLINENEWLINE assert_equal(data.mean(dim=[]), data)NEWLINENEWLINE def test_reduce_coords(self):NEWLINE # regression test for GH1470NEWLINE data = xr.Dataset({"a": ("x", [1, 2, 3])}, coords={"b": 4})NEWLINE expected = xr.Dataset({"a": 2}, coords={"b": 4})NEWLINE actual = data.mean("x")NEWLINE assert_identical(actual, expected)NEWLINENEWLINE # should be consistentNEWLINE actual = data["a"].mean("x").to_dataset()NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_mean_uint_dtype(self):NEWLINE data = xr.Dataset(NEWLINE {NEWLINE "a": (("x", "y"), np.arange(6).reshape(3, 2).astype("uint")),NEWLINE "b": (("x",), np.array([0.1, 0.2, np.nan])),NEWLINE }NEWLINE )NEWLINE actual = data.mean("x", skipna=True)NEWLINE expected = xr.Dataset(NEWLINE {"a": data["a"].mean("x"), "b": data["b"].mean("x", skipna=True)}NEWLINE )NEWLINE assert_identical(actual, expected)NEWLINENEWLINE def test_reduce_bad_dim(self):NEWLINE data = create_test_data()NEWLINE with raises_regex(ValueError, "Dataset does not contain"):NEWLINE data.mean(dim="bad_dim")NEWLINENEWLINE def test_reduce_cumsum(self):NEWLINE data = xr.Dataset(NEWLINE {"a": 1, "b": ("x", [1, 2]), "c": (("x", "y"), [[np.nan, 3], [0, 4]])}NEWLINE )NEWLINE assert_identical(data.fillna(0), data.cumsum("y"))NEWLINENEWLINE expected = xr.Dataset(NEWLINE {"a": 1, "b": ("x", [1, 3]), "c": (("x", "y"), [[0, 3], [0, 7]])}NEWLINE )NEWLINE assert_identical(expected, data.cumsum())NEWLINENEWLINE def test_reduce_cumsum_test_dims(self):NEWLINE data = create_test_data()NEWLINE for cumfunc in ["cumsum", "cumprod"]:NEWLINE with raises_regex(ValueError, "Dataset does not contain"):NEWLINE getattr(data, cumfunc)(dim="bad_dim")NEWLINENEWLINE # ensure dimensions are correctNEWLINE for reduct, expected in [NEWLINE ("dim1", ["dim1", "dim2", "dim3", "time"]),NEWLINE ("dim2", ["dim1", "dim2", "dim3", "time"]),NEWLINE ("dim3", ["dim1", "dim2", "dim3", "time"]),NEWLINE ("time", ["dim1", "dim2", "dim3"]),NEWLINE ]:NEWLINE actual = getattr(data, cumfunc)(dim=reduct).dimsNEWLINE assert list(actual) == expectedNEWLINENEWLINE def test_reduce_non_numeric(self):NEWLINE data1 = create_test_data(seed=44)NEWLINE data2 = create_test_data(seed=44)NEWLINE add_vars = {"var4": ["dim1", "dim2"]}NEWLINE for v, dims in sorted(add_vars.items()):NEWLINE size = tuple(data1.dims[d] for d in dims)NEWLINE data = np.random.randint(0, 100, size=size).astype(np.str_)NEWLINE data1[v] = (dims, data, {"foo": "variable"})NEWLINENEWLINE assert "var4" not in data1.mean()NEWLINE assert_equal(data1.mean(), data2.mean())NEWLINE assert_equal(data1.mean(dim="dim1"), data2.mean(dim="dim1"))NEWLINENEWLINE def test_reduce_strings(self):NEWLINE expected = Dataset({"x": "a"})NEWLINE ds = Dataset({"x": ("y", ["a", "b"])})NEWLINE actual = ds.min()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": "b"})NEWLINE actual = ds.max()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": 0})NEWLINE actual = ds.argmin()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": 1})NEWLINE actual = ds.argmax()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": b"a"})NEWLINE ds = Dataset({"x": ("y", np.array(["a", "b"], "S1"))})NEWLINE actual = ds.min()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": "a"})NEWLINE ds = Dataset({"x": ("y", np.array(["a", "b"], "U1"))})NEWLINE actual = ds.min()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce_dtypes(self):NEWLINE # regression test for GH342NEWLINE expected = Dataset({"x": 1})NEWLINE actual = Dataset({"x": True}).sum()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE # regression test for GH505NEWLINE expected = Dataset({"x": 3})NEWLINE actual = Dataset({"x": ("y", np.array([1, 2], "uint16"))}).sum()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": 1 + 1j})NEWLINE actual = Dataset({"x": ("y", [1, 1j])}).sum()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce_keep_attrs(self):NEWLINE data = create_test_data()NEWLINE _attrs = {"attr1": "value1", "attr2": 2929}NEWLINENEWLINE attrs = dict(_attrs)NEWLINE data.attrs = attrsNEWLINENEWLINE # Test dropped attrsNEWLINE ds = data.mean()NEWLINE assert ds.attrs == {}NEWLINE for v in ds.data_vars.values():NEWLINE assert v.attrs == {}NEWLINENEWLINE # Test kept attrsNEWLINE ds = data.mean(keep_attrs=True)NEWLINE assert ds.attrs == attrsNEWLINE for k, v in ds.data_vars.items():NEWLINE assert v.attrs == data[k].attrsNEWLINENEWLINE def test_reduce_argmin(self):NEWLINE # regression test for #205NEWLINE ds = Dataset({"a": ("x", [0, 1])})NEWLINE expected = Dataset({"a": ([], 0)})NEWLINE actual = ds.argmin()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.argmin("x")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce_scalars(self):NEWLINE ds = Dataset({"x": ("a", [2, 2]), "y": 2, "z": ("b", [2])})NEWLINE expected = Dataset({"x": 0, "y": 0, "z": 0})NEWLINE actual = ds.var()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"x": 0, "y": 0, "z": ("b", [0])})NEWLINE actual = ds.var("a")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_reduce_only_one_axis(self):NEWLINE def mean_only_one_axis(x, axis):NEWLINE if not isinstance(axis, integer_types):NEWLINE raise TypeError("non-integer axis")NEWLINE return x.mean(axis)NEWLINENEWLINE ds = Dataset({"a": (["x", "y"], [[0, 1, 2, 3, 4]])})NEWLINE expected = Dataset({"a": ("x", [2])})NEWLINE actual = ds.reduce(mean_only_one_axis, "y")NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(NEWLINE TypeError, "missing 1 required positional argument: " "'axis'"NEWLINE ):NEWLINE ds.reduce(mean_only_one_axis)NEWLINENEWLINE with raises_regex(TypeError, "non-integer axis"):NEWLINE ds.reduce(mean_only_one_axis, axis=["x", "y"])NEWLINENEWLINE def test_reduce_no_axis(self):NEWLINE def total_sum(x):NEWLINE return np.sum(x.flatten())NEWLINENEWLINE ds = Dataset({"a": (["x", "y"], [[0, 1, 2, 3, 4]])})NEWLINE expected = Dataset({"a": ((), 10)})NEWLINE actual = ds.reduce(total_sum)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(TypeError, "unexpected keyword argument 'axis'"):NEWLINE ds.reduce(total_sum, axis=0)NEWLINENEWLINE with raises_regex(TypeError, "unexpected keyword argument 'axis'"):NEWLINE ds.reduce(total_sum, dim="x")NEWLINENEWLINE def test_reduce_keepdims(self):NEWLINE ds = Dataset(NEWLINE {"a": (["x", "y"], [[0, 1, 2, 3, 4]])},NEWLINE coords={NEWLINE "y": [0, 1, 2, 3, 4],NEWLINE "x": [0],NEWLINE "lat": (["x", "y"], [[0, 1, 2, 3, 4]]),NEWLINE "c": -999.0,NEWLINE },NEWLINE )NEWLINENEWLINE # Shape should match behaviour of numpy reductions with keepdims=TrueNEWLINE # Coordinates involved in the reduction should be removedNEWLINE actual = ds.mean(keepdims=True)NEWLINE expected = Dataset(NEWLINE {"a": (["x", "y"], np.mean(ds.a, keepdims=True))}, coords={"c": ds.c}NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.mean("x", keepdims=True)NEWLINE expected = Dataset(NEWLINE {"a": (["x", "y"], np.mean(ds.a, axis=0, keepdims=True))},NEWLINE coords={"y": ds.y, "c": ds.c},NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_quantile(self):NEWLINENEWLINE ds = create_test_data(seed=123)NEWLINENEWLINE for q in [0.25, [0.50], [0.25, 0.75]]:NEWLINE for dim in [None, "dim1", ["dim1"]]:NEWLINE ds_quantile = ds.quantile(q, dim=dim)NEWLINE assert "quantile" in ds_quantileNEWLINE for var, dar in ds.data_vars.items():NEWLINE assert var in ds_quantileNEWLINE assert_identical(ds_quantile[var], dar.quantile(q, dim=dim))NEWLINE dim = ["dim1", "dim2"]NEWLINE ds_quantile = ds.quantile(q, dim=dim)NEWLINE assert "dim3" in ds_quantile.dimsNEWLINE assert all(d not in ds_quantile.dims for d in dim)NEWLINENEWLINE @requires_bottleneckNEWLINE def test_rank(self):NEWLINE ds = create_test_data(seed=1234)NEWLINE # only ds.var3 depends on dim3NEWLINE z = ds.rank("dim3")NEWLINE assert ["var3"] == list(z.data_vars)NEWLINE # same as dataarray versionNEWLINE x = z.var3NEWLINE y = ds.var3.rank("dim3")NEWLINE assert_equal(x, y)NEWLINE # coordinates stickNEWLINE assert list(z.coords) == list(ds.coords)NEWLINE assert list(x.coords) == list(y.coords)NEWLINE # invalid dimNEWLINE with raises_regex(ValueError, "does not contain"):NEWLINE x.rank("invalid_dim")NEWLINENEWLINE def test_count(self):NEWLINE ds = Dataset({"x": ("a", [np.nan, 1]), "y": 0, "z": np.nan})NEWLINE expected = Dataset({"x": 1, "y": 1, "z": 0})NEWLINE actual = ds.count()NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_map(self):NEWLINE data = create_test_data()NEWLINE data.attrs["foo"] = "bar"NEWLINENEWLINE assert_identical(data.map(np.mean), data.mean())NEWLINENEWLINE expected = data.mean(keep_attrs=True)NEWLINE actual = data.map(lambda x: x.mean(keep_attrs=True), keep_attrs=True)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE assert_identical(data.map(lambda x: x, keep_attrs=True), data.drop_vars("time"))NEWLINENEWLINE def scale(x, multiple=1):NEWLINE return multiple * xNEWLINENEWLINE actual = data.map(scale, multiple=2)NEWLINE assert_equal(actual["var1"], 2 * data["var1"])NEWLINE assert_identical(actual["numbers"], data["numbers"])NEWLINENEWLINE actual = data.map(np.asarray)NEWLINE expected = data.drop_vars("time") # time is not used on a data varNEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_apply_pending_deprecated_map(self):NEWLINE data = create_test_data()NEWLINE data.attrs["foo"] = "bar"NEWLINENEWLINE with pytest.warns(PendingDeprecationWarning):NEWLINE assert_identical(data.apply(np.mean), data.mean())NEWLINENEWLINE def make_example_math_dataset(self):NEWLINE variables = {NEWLINE "bar": ("x", np.arange(100, 400, 100)),NEWLINE "foo": (("x", "y"), 1.0 * np.arange(12).reshape(3, 4)),NEWLINE }NEWLINE coords = {"abc": ("x", ["a", "b", "c"]), "y": 10 * np.arange(4)}NEWLINE ds = Dataset(variables, coords)NEWLINE ds["foo"][0, 0] = np.nanNEWLINE return dsNEWLINENEWLINE def test_dataset_number_math(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE assert_identical(ds, +ds)NEWLINE assert_identical(ds, ds + 0)NEWLINE assert_identical(ds, 0 + ds)NEWLINE assert_identical(ds, ds + np.array(0))NEWLINE assert_identical(ds, np.array(0) + ds)NEWLINENEWLINE actual = ds.copy(deep=True)NEWLINE actual += 0NEWLINE assert_identical(ds, actual)NEWLINENEWLINE def test_unary_ops(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE assert_identical(ds.map(abs), abs(ds))NEWLINE assert_identical(ds.map(lambda x: x + 4), ds + 4)NEWLINENEWLINE for func in [NEWLINE lambda x: x.isnull(),NEWLINE lambda x: x.round(),NEWLINE lambda x: x.astype(int),NEWLINE ]:NEWLINE assert_identical(ds.map(func), func(ds))NEWLINENEWLINE assert_identical(ds.isnull(), ~ds.notnull())NEWLINENEWLINE # don't actually patch these methods inNEWLINE with pytest.raises(AttributeError):NEWLINE ds.itemNEWLINE with pytest.raises(AttributeError):NEWLINE ds.searchsortedNEWLINENEWLINE def test_dataset_array_math(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE expected = ds.map(lambda x: x - ds["foo"])NEWLINE assert_identical(expected, ds - ds["foo"])NEWLINE assert_identical(expected, -ds["foo"] + ds)NEWLINE assert_identical(expected, ds - ds["foo"].variable)NEWLINE assert_identical(expected, -ds["foo"].variable + ds)NEWLINE actual = ds.copy(deep=True)NEWLINE actual -= ds["foo"]NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = ds.map(lambda x: x + ds["bar"])NEWLINE assert_identical(expected, ds + ds["bar"])NEWLINE actual = ds.copy(deep=True)NEWLINE actual += ds["bar"]NEWLINE assert_identical(expected, actual)NEWLINENEWLINE expected = Dataset({"bar": ds["bar"] + np.arange(3)})NEWLINE assert_identical(expected, ds[["bar"]] + np.arange(3))NEWLINE assert_identical(expected, np.arange(3) + ds[["bar"]])NEWLINENEWLINE def test_dataset_dataset_math(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE assert_identical(ds, ds + 0 * ds)NEWLINE assert_identical(ds, ds + {"foo": 0, "bar": 0})NEWLINENEWLINE expected = ds.map(lambda x: 2 * x)NEWLINE assert_identical(expected, 2 * ds)NEWLINE assert_identical(expected, ds + ds)NEWLINE assert_identical(expected, ds + ds.data_vars)NEWLINE assert_identical(expected, ds + dict(ds.data_vars))NEWLINENEWLINE actual = ds.copy(deep=True)NEWLINE expected_id = id(actual)NEWLINE actual += dsNEWLINE assert_identical(expected, actual)NEWLINE assert expected_id == id(actual)NEWLINENEWLINE assert_identical(ds == ds, ds.notnull())NEWLINENEWLINE subsampled = ds.isel(y=slice(2))NEWLINE expected = 2 * subsampledNEWLINE assert_identical(expected, subsampled + ds)NEWLINE assert_identical(expected, ds + subsampled)NEWLINENEWLINE def test_dataset_math_auto_align(self):NEWLINE ds = self.make_example_math_dataset()NEWLINE subset = ds.isel(y=[1, 3])NEWLINE expected = 2 * subsetNEWLINE actual = ds + subsetNEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.isel(y=slice(1)) + ds.isel(y=slice(1, None))NEWLINE expected = 2 * ds.drop_sel(y=ds.y)NEWLINE assert_equal(actual, expected)NEWLINENEWLINE actual = ds + ds[["bar"]]NEWLINE expected = (2 * ds[["bar"]]).merge(ds.coords)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE assert_identical(ds + Dataset(), ds.coords.to_dataset())NEWLINE assert_identical(Dataset() + Dataset(), Dataset())NEWLINENEWLINE ds2 = Dataset(coords={"bar": 42})NEWLINE assert_identical(ds + ds2, ds.coords.merge(ds2))NEWLINENEWLINE # maybe unary arithmetic with empty datasets should raise instead?NEWLINE assert_identical(Dataset() + 1, Dataset())NEWLINENEWLINE actual = ds.copy(deep=True)NEWLINE other = ds.isel(y=slice(2))NEWLINE actual += otherNEWLINE expected = ds + other.reindex_like(ds)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_dataset_math_errors(self):NEWLINE ds = self.make_example_math_dataset()NEWLINENEWLINE with pytest.raises(TypeError):NEWLINE ds["foo"] += dsNEWLINE with pytest.raises(TypeError):NEWLINE ds["foo"].variable += dsNEWLINE with raises_regex(ValueError, "must have the same"):NEWLINE ds += ds[["bar"]]NEWLINENEWLINE # verify we can rollback in-place operations if something goes wrongNEWLINE # nb. inplace datetime64 math actually will work with an integer arrayNEWLINE # but not floats thanks to numpy's inconsistent handlingNEWLINE other = DataArray(np.datetime64("2000-01-01"), coords={"c": 2})NEWLINE actual = ds.copy(deep=True)NEWLINE with pytest.raises(TypeError):NEWLINE actual += otherNEWLINE assert_identical(actual, ds)NEWLINENEWLINE def test_dataset_transpose(self):NEWLINE ds = Dataset(NEWLINE {NEWLINE "a": (("x", "y"), np.random.randn(3, 4)),NEWLINE "b": (("y", "x"), np.random.randn(4, 3)),NEWLINE },NEWLINE coords={NEWLINE "x": range(3),NEWLINE "y": range(4),NEWLINE "xy": (("x", "y"), np.random.randn(3, 4)),NEWLINE },NEWLINE )NEWLINENEWLINE actual = ds.transpose()NEWLINE expected = Dataset(NEWLINE {"a": (("y", "x"), ds.a.values.T), "b": (("x", "y"), ds.b.values.T)},NEWLINE coords={NEWLINE "x": ds.x.values,NEWLINE "y": ds.y.values,NEWLINE "xy": (("y", "x"), ds.xy.values.T),NEWLINE },NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.transpose(...)NEWLINE expected = dsNEWLINE assert_identical(expected, actual)NEWLINENEWLINE actual = ds.transpose("x", "y")NEWLINE expected = ds.map(lambda x: x.transpose("x", "y", transpose_coords=True))NEWLINE assert_identical(expected, actual)NEWLINENEWLINE ds = create_test_data()NEWLINE actual = ds.transpose()NEWLINE for k in ds.variables:NEWLINE assert actual[k].dims[::-1] == ds[k].dimsNEWLINENEWLINE new_order = ("dim2", "dim3", "dim1", "time")NEWLINE actual = ds.transpose(*new_order)NEWLINE for k in ds.variables:NEWLINE expected_dims = tuple(d for d in new_order if d in ds[k].dims)NEWLINE assert actual[k].dims == expected_dimsNEWLINENEWLINE # same as above but with ellipsisNEWLINE new_order = ("dim2", "dim3", "dim1", "time")NEWLINE actual = ds.transpose("dim2", "dim3", ...)NEWLINE for k in ds.variables:NEWLINE expected_dims = tuple(d for d in new_order if d in ds[k].dims)NEWLINE assert actual[k].dims == expected_dimsNEWLINENEWLINE with raises_regex(ValueError, "permuted"):NEWLINE ds.transpose("dim1", "dim2", "dim3")NEWLINE with raises_regex(ValueError, "permuted"):NEWLINE ds.transpose("dim1", "dim2", "dim3", "time", "extra_dim")NEWLINENEWLINE assert "T" not in dir(ds)NEWLINENEWLINE def test_dataset_ellipsis_transpose_different_ordered_vars(self):NEWLINE # https://github.com/pydata/xarray/issues/1081#issuecomment-544350457NEWLINE ds = Dataset(NEWLINE dict(NEWLINE a=(("w", "x", "y", "z"), np.ones((2, 3, 4, 5))),NEWLINE b=(("x", "w", "y", "z"), np.zeros((3, 2, 4, 5))),NEWLINE )NEWLINE )NEWLINE result = ds.transpose(..., "z", "y")NEWLINE assert list(result["a"].dims) == list("wxzy")NEWLINE assert list(result["b"].dims) == list("xwzy")NEWLINENEWLINE def test_dataset_retains_period_index_on_transpose(self):NEWLINENEWLINE ds = create_test_data()NEWLINE ds["time"] = pd.period_range("2000-01-01", periods=20)NEWLINENEWLINE transposed = ds.transpose()NEWLINENEWLINE assert isinstance(transposed.time.to_index(), pd.PeriodIndex)NEWLINENEWLINE def test_dataset_diff_n1_simple(self):NEWLINE ds = Dataset({"foo": ("x", [5, 5, 6, 6])})NEWLINE actual = ds.diff("x")NEWLINE expected = Dataset({"foo": ("x", [0, 1, 0])})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_dataset_diff_n1_label(self):NEWLINE ds = Dataset({"foo": ("x", [5, 5, 6, 6])}, {"x": [0, 1, 2, 3]})NEWLINE actual = ds.diff("x", label="lower")NEWLINE expected = Dataset({"foo": ("x", [0, 1, 0])}, {"x": [0, 1, 2]})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE actual = ds.diff("x", label="upper")NEWLINE expected = Dataset({"foo": ("x", [0, 1, 0])}, {"x": [1, 2, 3]})NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_dataset_diff_n1(self):NEWLINE ds = create_test_data(seed=1)NEWLINE actual = ds.diff("dim2")NEWLINE expected = {}NEWLINE expected["var1"] = DataArray(NEWLINE np.diff(ds["var1"].values, axis=1),NEWLINE {"dim2": ds["dim2"].values[1:]},NEWLINE ["dim1", "dim2"],NEWLINE )NEWLINE expected["var2"] = DataArray(NEWLINE np.diff(ds["var2"].values, axis=1),NEWLINE {"dim2": ds["dim2"].values[1:]},NEWLINE ["dim1", "dim2"],NEWLINE )NEWLINE expected["var3"] = ds["var3"]NEWLINE expected = Dataset(expected, coords={"time": ds["time"].values})NEWLINE expected.coords["numbers"] = ("dim3", ds["numbers"].values)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_dataset_diff_n2(self):NEWLINE ds = create_test_data(seed=1)NEWLINE actual = ds.diff("dim2", n=2)NEWLINE expected = {}NEWLINE expected["var1"] = DataArray(NEWLINE np.diff(ds["var1"].values, axis=1, n=2),NEWLINE {"dim2": ds["dim2"].values[2:]},NEWLINE ["dim1", "dim2"],NEWLINE )NEWLINE expected["var2"] = DataArray(NEWLINE np.diff(ds["var2"].values, axis=1, n=2),NEWLINE {"dim2": ds["dim2"].values[2:]},NEWLINE ["dim1", "dim2"],NEWLINE )NEWLINE expected["var3"] = ds["var3"]NEWLINE expected = Dataset(expected, coords={"time": ds["time"].values})NEWLINE expected.coords["numbers"] = ("dim3", ds["numbers"].values)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE def test_dataset_diff_exception_n_neg(self):NEWLINE ds = create_test_data(seed=1)NEWLINE with raises_regex(ValueError, "must be non-negative"):NEWLINE ds.diff("dim2", n=-1)NEWLINENEWLINE def test_dataset_diff_exception_label_str(self):NEWLINE ds = create_test_data(seed=1)NEWLINE with raises_regex(ValueError, "'label' argument has to"):NEWLINE ds.diff("dim2", label="raise_me")NEWLINENEWLINE @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0])NEWLINE def test_shift(self, fill_value):NEWLINE coords = {"bar": ("x", list("abc")), "x": [-4, 3, 2]}NEWLINE attrs = {"meta": "data"}NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, coords, attrs)NEWLINE actual = ds.shift(x=1, fill_value=fill_value)NEWLINE if fill_value == dtypes.NA:NEWLINE # if we supply the default, we expect the missing value for aNEWLINE # float arrayNEWLINE fill_value = np.nanNEWLINE expected = Dataset({"foo": ("x", [fill_value, 1, 2])}, coords, attrs)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "dimensions"):NEWLINE ds.shift(foo=123)NEWLINENEWLINE def test_roll_coords(self):NEWLINE coords = {"bar": ("x", list("abc")), "x": [-4, 3, 2]}NEWLINE attrs = {"meta": "data"}NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, coords, attrs)NEWLINE actual = ds.roll(x=1, roll_coords=True)NEWLINENEWLINE ex_coords = {"bar": ("x", list("cab")), "x": [2, -4, 3]}NEWLINE expected = Dataset({"foo": ("x", [3, 1, 2])}, ex_coords, attrs)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "dimensions"):NEWLINE ds.roll(foo=123, roll_coords=True)NEWLINENEWLINE def test_roll_no_coords(self):NEWLINE coords = {"bar": ("x", list("abc")), "x": [-4, 3, 2]}NEWLINE attrs = {"meta": "data"}NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, coords, attrs)NEWLINE actual = ds.roll(x=1, roll_coords=False)NEWLINENEWLINE expected = Dataset({"foo": ("x", [3, 1, 2])}, coords, attrs)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE with raises_regex(ValueError, "dimensions"):NEWLINE ds.roll(abc=321, roll_coords=False)NEWLINENEWLINE def test_roll_coords_none(self):NEWLINE coords = {"bar": ("x", list("abc")), "x": [-4, 3, 2]}NEWLINE attrs = {"meta": "data"}NEWLINE ds = Dataset({"foo": ("x", [1, 2, 3])}, coords, attrs)NEWLINENEWLINE with pytest.warns(FutureWarning):NEWLINE actual = ds.roll(x=1, roll_coords=None)NEWLINENEWLINE ex_coords = {"bar": ("x", list("cab")), "x": [2, -4, 3]}NEWLINE expected = Dataset({"foo": ("x", [3, 1, 2])}, ex_coords, attrs)NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_roll_multidim(self):NEWLINE # regression test for 2445NEWLINE arr = xr.DataArray(NEWLINE [[1, 2, 3], [4, 5, 6]],NEWLINE coords={"x": range(3), "y": range(2)},NEWLINE dims=("y", "x"),NEWLINE )NEWLINE actual = arr.roll(x=1, roll_coords=True)NEWLINE expected = xr.DataArray(NEWLINE [[3, 1, 2], [6, 4, 5]], coords=[("y", [0, 1]), ("x", [2, 0, 1])]NEWLINE )NEWLINE assert_identical(expected, actual)NEWLINENEWLINE def test_real_and_imag(self):NEWLINE attrs = {"foo": "bar"}NEWLINE ds = Dataset({"x": ((), 1 + 2j, attrs)}, attrs=attrs)NEWLINENEWLINE expected_re = Dataset({"x": ((), 1, attrs)}, attrs=attrs)NEWLINE assert_identical(ds.real, expected_re)NEWLINENEWLINE expected_im = Dataset({"x": ((), 2, attrs)}, attrs=attrs)NEWLINE assert_identical(ds.imag, expected_im)NEWLINENEWLINE def test_setattr_raises(self):NEWLINE ds = Dataset({}, coords={"scalar": 1}, attrs={"foo": "bar"})NEWLINE with raises_regex(AttributeError, "cannot set attr"):NEWLINE ds.scalar = 2NEWLINE with raises_regex(AttributeError, "cannot set attr"):NEWLINE ds.foo = 2NEWLINE with raises_regex(AttributeError, "cannot set attr"):NEWLINE ds.other = 2NEWLINENEWLINE def test_filter_by_attrs(self):NEWLINE precip = dict(standard_name="convective_precipitation_flux")NEWLINE temp0 = dict(standard_name="air_potential_temperature", height="0 m")NEWLINE temp10 = dict(standard_name="air_potential_temperature", height="10 m")NEWLINE ds = Dataset(NEWLINE {NEWLINE "temperature_0": (["t"], [0], temp0),NEWLINE "temperature_10": (["t"], [0], temp10),NEWLINE "precipitation": (["t"], [0], precip),NEWLINE },NEWLINE coords={"time": (["t"], [0], dict(axis="T", long_name="time_in_seconds"))},NEWLINE )NEWLINENEWLINE # Test return empty Dataset.NEWLINE ds.filter_by_attrs(standard_name="invalid_standard_name")NEWLINE new_ds = ds.filter_by_attrs(standard_name="invalid_standard_name")NEWLINE assert not bool(new_ds.data_vars)NEWLINENEWLINE # Test return one DataArray.NEWLINE new_ds = ds.filter_by_attrs(standard_name="convective_precipitation_flux")NEWLINE assert new_ds["precipitation"].standard_name == "convective_precipitation_flux"NEWLINENEWLINE assert_equal(new_ds["precipitation"], ds["precipitation"])NEWLINENEWLINE # Test filter coordinatesNEWLINE new_ds = ds.filter_by_attrs(long_name="time_in_seconds")NEWLINE assert new_ds["time"].long_name == "time_in_seconds"NEWLINE assert not bool(new_ds.data_vars)NEWLINENEWLINE # Test return more than one DataArray.NEWLINE new_ds = ds.filter_by_attrs(standard_name="air_potential_temperature")NEWLINE assert len(new_ds.data_vars) == 2NEWLINE for var in new_ds.data_vars:NEWLINE assert new_ds[var].standard_name == "air_potential_temperature"NEWLINENEWLINE # Test callable.NEWLINE new_ds = ds.filter_by_attrs(height=lambda v: v is not None)NEWLINE assert len(new_ds.data_vars) == 2NEWLINE for var in new_ds.data_vars:NEWLINE assert new_ds[var].standard_name == "air_potential_temperature"NEWLINENEWLINE new_ds = ds.filter_by_attrs(height="10 m")NEWLINE assert len(new_ds.data_vars) == 1NEWLINE for var in new_ds.data_vars:NEWLINE assert new_ds[var].height == "10 m"NEWLINENEWLINE # Test return empty Dataset due to conflicting filtersNEWLINE new_ds = ds.filter_by_attrs(NEWLINE standard_name="convective_precipitation_flux", height="0 m"NEWLINE )NEWLINE assert not bool(new_ds.data_vars)NEWLINENEWLINE # Test return one DataArray with two filter conditionsNEWLINE new_ds = ds.filter_by_attrs(NEWLINE standard_name="air_potential_temperature", height="0 m"NEWLINE )NEWLINE for var in new_ds.data_vars:NEWLINE assert new_ds[var].standard_name == "air_potential_temperature"NEWLINE assert new_ds[var].height == "0 m"NEWLINE assert new_ds[var].height != "10 m"NEWLINENEWLINE # Test return empty Dataset due to conflicting callablesNEWLINE new_ds = ds.filter_by_attrs(NEWLINE standard_name=lambda v: False, height=lambda v: TrueNEWLINE )NEWLINE assert not bool(new_ds.data_vars)NEWLINENEWLINE def test_binary_op_propagate_indexes(self):NEWLINE ds = Dataset(NEWLINE {"d1": DataArray([1, 2, 3], dims=["x"], coords={"x": [10, 20, 30]})}NEWLINE )NEWLINE expected = ds.indexes["x"]NEWLINE actual = (ds * 2).indexes["x"]NEWLINE assert expected is actualNEWLINENEWLINE def test_binary_op_join_setting(self):NEWLINE # arithmetic_join applies to data array coordinatesNEWLINE missing_2 = xr.Dataset({"x": [0, 1]})NEWLINE missing_0 = xr.Dataset({"x": [1, 2]})NEWLINE with xr.set_options(arithmetic_join="outer"):NEWLINE actual = missing_2 + missing_0NEWLINE expected = xr.Dataset({"x": [0, 1, 2]})NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # arithmetic join also applies to data_varsNEWLINE ds1 = xr.Dataset({"foo": 1, "bar": 2})NEWLINE ds2 = xr.Dataset({"bar": 2, "baz": 3})NEWLINE expected = xr.Dataset({"bar": 4}) # default is inner joiningNEWLINE actual = ds1 + ds2NEWLINE assert_equal(actual, expected)NEWLINENEWLINE with xr.set_options(arithmetic_join="outer"):NEWLINE expected = xr.Dataset({"foo": np.nan, "bar": 4, "baz": np.nan})NEWLINE actual = ds1 + ds2NEWLINE assert_equal(actual, expected)NEWLINENEWLINE with xr.set_options(arithmetic_join="left"):NEWLINE expected = xr.Dataset({"foo": np.nan, "bar": 4})NEWLINE actual = ds1 + ds2NEWLINE assert_equal(actual, expected)NEWLINENEWLINE with xr.set_options(arithmetic_join="right"):NEWLINE expected = xr.Dataset({"bar": 4, "baz": np.nan})NEWLINE actual = ds1 + ds2NEWLINE assert_equal(actual, expected)NEWLINENEWLINE def test_full_like(self):NEWLINE # For more thorough tests, see test_variable.pyNEWLINE # Note: testing data_vars with mismatched dtypesNEWLINE ds = Dataset(NEWLINE {NEWLINE "d1": DataArray([1, 2, 3], dims=["x"], coords={"x": [10, 20, 30]}),NEWLINE "d2": DataArray([1.1, 2.2, 3.3], dims=["y"]),NEWLINE },NEWLINE attrs={"foo": "bar"},NEWLINE )NEWLINE actual = full_like(ds, 2)NEWLINENEWLINE expect = ds.copy(deep=True)NEWLINE expect["d1"].values = [2, 2, 2]NEWLINE expect["d2"].values = [2.0, 2.0, 2.0]NEWLINE assert expect["d1"].dtype == intNEWLINE assert expect["d2"].dtype == floatNEWLINE assert_identical(expect, actual)NEWLINENEWLINE # override dtypeNEWLINE actual = full_like(ds, fill_value=True, dtype=bool)NEWLINE expect = ds.copy(deep=True)NEWLINE expect["d1"].values = [True, True, True]NEWLINE expect["d2"].values = [True, True, True]NEWLINE assert expect["d1"].dtype == boolNEWLINE assert expect["d2"].dtype == boolNEWLINE assert_identical(expect, actual)NEWLINENEWLINE def test_combine_first(self):NEWLINE dsx0 = DataArray([0, 0], [("x", ["a", "b"])]).to_dataset(name="dsx0")NEWLINE dsx1 = DataArray([1, 1], [("x", ["b", "c"])]).to_dataset(name="dsx1")NEWLINENEWLINE actual = dsx0.combine_first(dsx1)NEWLINE expected = Dataset(NEWLINE {"dsx0": ("x", [0, 0, np.nan]), "dsx1": ("x", [np.nan, 1, 1])},NEWLINE coords={"x": ["a", "b", "c"]},NEWLINE )NEWLINE assert_equal(actual, expected)NEWLINE assert_equal(actual, xr.merge([dsx0, dsx1]))NEWLINENEWLINE # works just like xr.merge([self, other])NEWLINE dsy2 = DataArray([2, 2, 2], [("x", ["b", "c", "d"])]).to_dataset(name="dsy2")NEWLINE actual = dsx0.combine_first(dsy2)NEWLINE expected = xr.merge([dsy2, dsx0])NEWLINE assert_equal(actual, expected)NEWLINENEWLINE def test_sortby(self):NEWLINE ds = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[1, 2], [3, 4], [5, 6]], [("x", ["c", "b", "a"]), ("y", [1, 0])]NEWLINE ),NEWLINE "B": DataArray([[5, 6], [7, 8], [9, 10]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINENEWLINE sorted1d = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[5, 6], [3, 4], [1, 2]], [("x", ["a", "b", "c"]), ("y", [1, 0])]NEWLINE ),NEWLINE "B": DataArray([[9, 10], [7, 8], [5, 6]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINENEWLINE sorted2d = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[6, 5], [4, 3], [2, 1]], [("x", ["a", "b", "c"]), ("y", [0, 1])]NEWLINE ),NEWLINE "B": DataArray([[10, 9], [8, 7], [6, 5]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINENEWLINE expected = sorted1dNEWLINE dax = DataArray([100, 99, 98], [("x", ["c", "b", "a"])])NEWLINE actual = ds.sortby(dax)NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test descending order sortNEWLINE actual = ds.sortby(dax, ascending=False)NEWLINE assert_equal(actual, ds)NEWLINENEWLINE # test alignment (fills in nan for 'c')NEWLINE dax_short = DataArray([98, 97], [("x", ["b", "a"])])NEWLINE actual = ds.sortby(dax_short)NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test 1-D lexsortNEWLINE # dax0 is sorted first to give indices of [1, 2, 0]NEWLINE # and then dax1 would be used to move index 2 ahead of 1NEWLINE dax0 = DataArray([100, 95, 95], [("x", ["c", "b", "a"])])NEWLINE dax1 = DataArray([0, 1, 0], [("x", ["c", "b", "a"])])NEWLINE actual = ds.sortby([dax0, dax1]) # lexsort underneath gives [2, 1, 0]NEWLINE assert_equal(actual, expected)NEWLINENEWLINE expected = sorted2dNEWLINE # test multi-dim sort by 1D dataarray valuesNEWLINE day = DataArray([90, 80], [("y", [1, 0])])NEWLINE actual = ds.sortby([day, dax])NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test exception-raisingNEWLINE with pytest.raises(KeyError) as excinfo:NEWLINE actual = ds.sortby("z")NEWLINENEWLINE with pytest.raises(ValueError) as excinfo:NEWLINE actual = ds.sortby(ds["A"])NEWLINE assert "DataArray is not 1-D" in str(excinfo.value)NEWLINENEWLINE expected = sorted1dNEWLINE actual = ds.sortby("x")NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test pandas.MultiIndexNEWLINE indices = (("b", 1), ("b", 0), ("a", 1), ("a", 0))NEWLINE midx = pd.MultiIndex.from_tuples(indices, names=["one", "two"])NEWLINE ds_midx = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[1, 2], [3, 4], [5, 6], [7, 8]], [("x", midx), ("y", [1, 0])]NEWLINE ),NEWLINE "B": DataArray([[5, 6], [7, 8], [9, 10], [11, 12]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINE actual = ds_midx.sortby("x")NEWLINE midx_reversed = pd.MultiIndex.from_tuples(NEWLINE tuple(reversed(indices)), names=["one", "two"]NEWLINE )NEWLINE expected = Dataset(NEWLINE {NEWLINE "A": DataArray(NEWLINE [[7, 8], [5, 6], [3, 4], [1, 2]],NEWLINE [("x", midx_reversed), ("y", [1, 0])],NEWLINE ),NEWLINE "B": DataArray([[11, 12], [9, 10], [7, 8], [5, 6]], dims=["x", "y"]),NEWLINE }NEWLINE )NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # multi-dim sort by coordinate objectsNEWLINE expected = sorted2dNEWLINE actual = ds.sortby(["x", "y"])NEWLINE assert_equal(actual, expected)NEWLINENEWLINE # test descending order sortNEWLINE actual = ds.sortby(["x", "y"], ascending=False)NEWLINE assert_equal(actual, ds)NEWLINENEWLINE def test_attribute_access(self):NEWLINE ds = create_test_data(seed=1)NEWLINE for key in ["var1", "var2", "var3", "time", "dim1", "dim2", "dim3", "numbers"]:NEWLINE assert_equal(ds[key], getattr(ds, key))NEWLINE assert key in dir(ds)NEWLINENEWLINE for key in ["dim3", "dim1", "numbers"]:NEWLINE assert_equal(ds["var3"][key], getattr(ds.var3, key))NEWLINE assert key in dir(ds["var3"])NEWLINE # attrsNEWLINE assert ds["var3"].attrs["foo"] == ds.var3.fooNEWLINE assert "foo" in dir(ds["var3"])NEWLINENEWLINE def test_ipython_key_completion(self):NEWLINE ds = create_test_data(seed=1)NEWLINE actual = ds._ipython_key_completions_()NEWLINE expected = ["var1", "var2", "var3", "time", "dim1", "dim2", "dim3", "numbers"]NEWLINE for item in actual:NEWLINE ds[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE # for dataarrayNEWLINE actual = ds["var3"]._ipython_key_completions_()NEWLINE expected = ["dim3", "dim1", "numbers"]NEWLINE for item in actual:NEWLINE ds["var3"][item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE # MultiIndexNEWLINE ds_midx = ds.stack(dim12=["dim1", "dim2"])NEWLINE actual = ds_midx._ipython_key_completions_()NEWLINE expected = [NEWLINE "var1",NEWLINE "var2",NEWLINE "var3",NEWLINE "time",NEWLINE "dim1",NEWLINE "dim2",NEWLINE "dim3",NEWLINE "numbers",NEWLINE "dim12",NEWLINE ]NEWLINE for item in actual:NEWLINE ds_midx[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE # coordsNEWLINE actual = ds.coords._ipython_key_completions_()NEWLINE expected = ["time", "dim1", "dim2", "dim3", "numbers"]NEWLINE for item in actual:NEWLINE ds.coords[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE actual = ds["var3"].coords._ipython_key_completions_()NEWLINE expected = ["dim1", "dim3", "numbers"]NEWLINE for item in actual:NEWLINE ds["var3"].coords[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINE # data_varsNEWLINE actual = ds.data_vars._ipython_key_completions_()NEWLINE expected = ["var1", "var2", "var3", "dim1"]NEWLINE for item in actual:NEWLINE ds.data_vars[item] # should not raiseNEWLINE assert sorted(actual) == sorted(expected)NEWLINENEWLINENEWLINE# Py.test [email protected](params=[None])NEWLINEdef data_set(request):NEWLINE return create_test_data(request.param)[email protected]("test_elements", ([1, 2], np.array([1, 2]), DataArray([1, 2])))NEWLINEdef test_isin(test_elements):NEWLINE expected = Dataset(NEWLINE data_vars={NEWLINE "var1": (("dim1",), [0, 1]),NEWLINE "var2": (("dim1",), [1, 1]),NEWLINE "var3": (("dim1",), [0, 1]),NEWLINE }NEWLINE ).astype("bool")NEWLINENEWLINE result = Dataset(NEWLINE data_vars={NEWLINE "var1": (("dim1",), [0, 1]),NEWLINE "var2": (("dim1",), [1, 2]),NEWLINE "var3": (("dim1",), [0, 1]),NEWLINE }NEWLINE ).isin(test_elements)NEWLINENEWLINE assert_equal(result, expected)[email protected](not has_dask, reason="requires dask")[email protected]("test_elements", ([1, 2], np.array([1, 2]), DataArray([1, 2])))NEWLINEdef test_isin_dask(test_elements):NEWLINE expected = Dataset(NEWLINE data_vars={NEWLINE "var1": (("dim1",), [0, 1]),NEWLINE "var2": (("dim1",), [1, 1]),NEWLINE "var3": (("dim1",), [0, 1]),NEWLINE }NEWLINE ).astype("bool")NEWLINENEWLINE result = (NEWLINE Dataset(NEWLINE data_vars={NEWLINE "var1": (("dim1",), [0, 1]),NEWLINE "var2": (("dim1",), [1, 2]),NEWLINE "var3": (("dim1",), [0, 1]),NEWLINE }NEWLINE )NEWLINE .chunk(1)NEWLINE .isin(test_elements)NEWLINE .compute()NEWLINE )NEWLINENEWLINE assert_equal(result, expected)NEWLINENEWLINENEWLINEdef test_isin_dataset():NEWLINE ds = Dataset({"x": [1, 2]})NEWLINE with pytest.raises(TypeError):NEWLINE ds.isin(ds)[email protected](NEWLINE "unaligned_coords",NEWLINE (NEWLINE {"x": [2, 1, 0]},NEWLINE {"x": (["x"], np.asarray([2, 1, 0]))},NEWLINE {"x": (["x"], np.asarray([1, 2, 0]))},NEWLINE {"x": pd.Index([2, 1, 0])},NEWLINE {"x": Variable(dims="x", data=[0, 2, 1])},NEWLINE {"x": IndexVariable(dims="x", data=[0, 1, 2])},NEWLINE {"y": 42},NEWLINE {"y": ("x", [2, 1, 0])},NEWLINE {"y": ("x", np.asarray([2, 1, 0]))},NEWLINE {"y": (["x"], np.asarray([2, 1, 0]))},NEWLINE ),NEWLINE)[email protected]("coords", ({"x": ("x", [0, 1, 2])}, {"x": [0, 1, 2]}))NEWLINEdef test_dataset_constructor_aligns_to_explicit_coords(unaligned_coords, coords):NEWLINENEWLINE a = xr.DataArray([1, 2, 3], dims=["x"], coords=unaligned_coords)NEWLINENEWLINE expected = xr.Dataset(coords=coords)NEWLINE expected["a"] = aNEWLINENEWLINE result = xr.Dataset({"a": a}, coords=coords)NEWLINENEWLINE assert_equal(expected, result)NEWLINENEWLINENEWLINEdef test_error_message_on_set_supplied():NEWLINE with pytest.raises(TypeError, match="has invalid type <class 'set'>"):NEWLINE xr.Dataset(dict(date=[1, 2, 3], sec={4}))[email protected]("unaligned_coords", ({"y": ("b", np.asarray([2, 1, 0]))},))NEWLINEdef test_constructor_raises_with_invalid_coords(unaligned_coords):NEWLINENEWLINE with pytest.raises(ValueError, match="not a subset of the DataArray dimensions"):NEWLINE xr.DataArray([1, 2, 3], dims=["x"], coords=unaligned_coords)NEWLINENEWLINENEWLINEdef test_dir_expected_attrs(data_set):NEWLINENEWLINE some_expected_attrs = {"pipe", "mean", "isnull", "var1", "dim2", "numbers"}NEWLINE result = dir(data_set)NEWLINE assert set(result) >= some_expected_attrsNEWLINENEWLINENEWLINEdef test_dir_non_string(data_set):NEWLINE # add a numbered key to ensure this doesn't break dirNEWLINE data_set[5] = "foo"NEWLINE result = dir(data_set)NEWLINE assert 5 not in resultNEWLINENEWLINE # GH2172NEWLINE sample_data = np.random.uniform(size=[2, 2000, 10000])NEWLINE x = xr.Dataset({"sample_data": (sample_data.shape, sample_data)})NEWLINE x2 = x["sample_data"]NEWLINE dir(x2)NEWLINENEWLINENEWLINEdef test_dir_unicode(data_set):NEWLINE data_set["unicode"] = "uni"NEWLINE result = dir(data_set)NEWLINE assert "unicode" in [email protected](params=[1])NEWLINEdef ds(request):NEWLINE if request.param == 1:NEWLINE return Dataset(NEWLINE {NEWLINE "z1": (["y", "x"], np.random.randn(2, 8)),NEWLINE "z2": (["time", "y"], np.random.randn(10, 2)),NEWLINE },NEWLINE {NEWLINE "x": ("x", np.linspace(0, 1.0, 8)),NEWLINE "time": ("time", np.linspace(0, 1.0, 10)),NEWLINE "c": ("y", ["a", "b"]),NEWLINE "y": range(2),NEWLINE },NEWLINE )NEWLINENEWLINE if request.param == 2:NEWLINE return Dataset(NEWLINE {NEWLINE "z1": (["time", "y"], np.random.randn(10, 2)),NEWLINE "z2": (["time"], np.random.randn(10)),NEWLINE "z3": (["x", "time"], np.random.randn(8, 10)),NEWLINE },NEWLINE {NEWLINE "x": ("x", np.linspace(0, 1.0, 8)),NEWLINE "time": ("time", np.linspace(0, 1.0, 10)),NEWLINE "c": ("y", ["a", "b"]),NEWLINE "y": range(2),NEWLINE },NEWLINE )[email protected]("dask", [True, False])[email protected](("boundary", "side"), [("trim", "left"), ("pad", "right")])NEWLINEdef test_coarsen(ds, dask, boundary, side):NEWLINE if dask and has_dask:NEWLINE ds = ds.chunk({"x": 4})NEWLINENEWLINE actual = ds.coarsen(time=2, x=3, boundary=boundary, side=side).max()NEWLINE assert_equal(NEWLINE actual["z1"], ds["z1"].coarsen(time=2, x=3, boundary=boundary, side=side).max()NEWLINE )NEWLINE # coordinate should be mean by defaultNEWLINE assert_equal(NEWLINE actual["time"],NEWLINE ds["time"].coarsen(time=2, x=3, boundary=boundary, side=side).mean(),NEWLINE )[email protected]("dask", [True, False])NEWLINEdef test_coarsen_coords(ds, dask):NEWLINE if dask and has_dask:NEWLINE ds = ds.chunk({"x": 4})NEWLINENEWLINE # check if coord_func worksNEWLINE actual = ds.coarsen(time=2, x=3, boundary="trim", coord_func={"time": "max"}).max()NEWLINE assert_equal(actual["z1"], ds["z1"].coarsen(time=2, x=3, boundary="trim").max())NEWLINE assert_equal(actual["time"], ds["time"].coarsen(time=2, x=3, boundary="trim").max())NEWLINENEWLINE # raise if exactNEWLINE with pytest.raises(ValueError):NEWLINE ds.coarsen(x=3).mean()NEWLINE # should be no errorNEWLINE ds.isel(x=slice(0, 3 * (len(ds["x"]) // 3))).coarsen(x=3).mean()NEWLINENEWLINE # working test with pd.timeNEWLINE da = xr.DataArray(NEWLINE np.linspace(0, 365, num=364),NEWLINE dims="time",NEWLINE coords={"time": pd.date_range("15/12/1999", periods=364)},NEWLINE )NEWLINE actual = da.coarsen(time=2).mean()NEWLINENEWLINENEWLINE@requires_cftimeNEWLINEdef test_coarsen_coords_cftime():NEWLINE times = xr.cftime_range("2000", periods=6)NEWLINE da = xr.DataArray(range(6), [("time", times)])NEWLINE actual = da.coarsen(time=3).mean()NEWLINE expected_times = xr.cftime_range("2000-01-02", freq="3D", periods=2)NEWLINE np.testing.assert_array_equal(actual.time, expected_times)NEWLINENEWLINENEWLINEdef test_rolling_properties(ds):NEWLINE # catching invalid argsNEWLINE with pytest.raises(ValueError, match="exactly one dim/window should"):NEWLINE ds.rolling(time=7, x=2)NEWLINE with pytest.raises(ValueError, match="window must be > 0"):NEWLINE ds.rolling(time=-2)NEWLINE with pytest.raises(ValueError, match="min_periods must be greater than zero"):NEWLINE ds.rolling(time=2, min_periods=0)NEWLINE with pytest.raises(KeyError, match="time2"):NEWLINE ds.rolling(time2=2)[email protected]("name", ("sum", "mean", "std", "var", "min", "max", "median"))[email protected]("center", (True, False, None))[email protected]("min_periods", (1, None))[email protected]("key", ("z1", "z2"))NEWLINEdef test_rolling_wrapped_bottleneck(ds, name, center, min_periods, key):NEWLINE bn = pytest.importorskip("bottleneck", minversion="1.1")NEWLINENEWLINE # Test all bottleneck functionsNEWLINE rolling_obj = ds.rolling(time=7, min_periods=min_periods)NEWLINENEWLINE func_name = f"move_{name}"NEWLINE actual = getattr(rolling_obj, name)()NEWLINE if key == "z1": # z1 does not depend on 'Time' axis. Stored as it is.NEWLINE expected = ds[key]NEWLINE elif key == "z2":NEWLINE expected = getattr(bn, func_name)(NEWLINE ds[key].values, window=7, axis=0, min_count=min_periodsNEWLINE )NEWLINE assert_array_equal(actual[key].values, expected)NEWLINENEWLINE # Test centerNEWLINE rolling_obj = ds.rolling(time=7, center=center)NEWLINE actual = getattr(rolling_obj, name)()["time"]NEWLINE assert_equal(actual, ds["time"])NEWLINENEWLINENEWLINE@requires_numbaggNEWLINEdef test_rolling_exp(ds):NEWLINENEWLINE result = ds.rolling_exp(time=10, window_type="span").mean()NEWLINE assert isinstance(result, Dataset)[email protected]("center", (True, False))[email protected]("min_periods", (None, 1, 2, 3))[email protected]("window", (1, 2, 3, 4))NEWLINEdef test_rolling_pandas_compat(center, window, min_periods):NEWLINE df = pd.DataFrame(NEWLINE {NEWLINE "x": np.random.randn(20),NEWLINE "y": np.random.randn(20),NEWLINE "time": np.linspace(0, 1, 20),NEWLINE }NEWLINE )NEWLINE ds = Dataset.from_dataframe(df)NEWLINENEWLINE if min_periods is not None and window < min_periods:NEWLINE min_periods = windowNEWLINENEWLINE df_rolling = df.rolling(window, center=center, min_periods=min_periods).mean()NEWLINE ds_rolling = ds.rolling(index=window, center=center, min_periods=min_periods).mean()NEWLINENEWLINE np.testing.assert_allclose(df_rolling["x"].values, ds_rolling["x"].values)NEWLINE np.testing.assert_allclose(df_rolling.index, ds_rolling["index"])[email protected]("center", (True, False))[email protected]("window", (1, 2, 3, 4))NEWLINEdef test_rolling_construct(center, window):NEWLINE df = pd.DataFrame(NEWLINE {NEWLINE "x": np.random.randn(20),NEWLINE "y": np.random.randn(20),NEWLINE "time": np.linspace(0, 1, 20),NEWLINE }NEWLINE )NEWLINENEWLINE ds = Dataset.from_dataframe(df)NEWLINE df_rolling = df.rolling(window, center=center, min_periods=1).mean()NEWLINE ds_rolling = ds.rolling(index=window, center=center)NEWLINENEWLINE ds_rolling_mean = ds_rolling.construct("window").mean("window")NEWLINE np.testing.assert_allclose(df_rolling["x"].values, ds_rolling_mean["x"].values)NEWLINE np.testing.assert_allclose(df_rolling.index, ds_rolling_mean["index"])NEWLINENEWLINE # with strideNEWLINE ds_rolling_mean = ds_rolling.construct("window", stride=2).mean("window")NEWLINE np.testing.assert_allclose(df_rolling["x"][::2].values, ds_rolling_mean["x"].values)NEWLINE np.testing.assert_allclose(df_rolling.index[::2], ds_rolling_mean["index"])NEWLINE # with fill_valueNEWLINE ds_rolling_mean = ds_rolling.construct("window", stride=2, fill_value=0.0).mean(NEWLINE "window"NEWLINE )NEWLINE assert (ds_rolling_mean.isnull().sum() == 0).to_array(dim="vars").all()NEWLINE assert (ds_rolling_mean["x"] == 0.0).sum() >= [email protected]@pytest.mark.parametrize("ds", (1, 2), indirect=True)[email protected]("center", (True, False))[email protected]("min_periods", (None, 1, 2, 3))[email protected]("window", (1, 2, 3, 4))[email protected]("name", ("sum", "mean", "std", "var", "min", "max", "median"))NEWLINEdef test_rolling_reduce(ds, center, min_periods, window, name):NEWLINENEWLINE if min_periods is not None and window < min_periods:NEWLINE min_periods = windowNEWLINENEWLINE if name == "std" and window == 1:NEWLINE pytest.skip("std with window == 1 is unstable in bottleneck")NEWLINENEWLINE rolling_obj = ds.rolling(time=window, center=center, min_periods=min_periods)NEWLINENEWLINE # add nan prefix to numpy methods to get similar behavior as bottleneckNEWLINE actual = rolling_obj.reduce(getattr(np, "nan%s" % name))NEWLINE expected = getattr(rolling_obj, name)()NEWLINE assert_allclose(actual, expected)NEWLINE assert ds.dims == actual.dimsNEWLINE # make sure the order of data_var are not changed.NEWLINE assert list(ds.data_vars.keys()) == list(actual.data_vars.keys())NEWLINENEWLINE # Make sure the dimension order is restoredNEWLINE for key, src_var in ds.data_vars.items():NEWLINE assert src_var.dims == actual[key].dimsNEWLINENEWLINENEWLINEdef test_raise_no_warning_for_nan_in_binary_ops():NEWLINE with pytest.warns(None) as record:NEWLINE Dataset(data_vars={"x": ("y", [1, 2, np.NaN])}) > 0NEWLINE assert len(record) == [email protected]("dask", [True, False])[email protected]("edge_order", [1, 2])NEWLINEdef test_differentiate(dask, edge_order):NEWLINE rs = np.random.RandomState(42)NEWLINE coord = [0.2, 0.35, 0.4, 0.6, 0.7, 0.75, 0.76, 0.8]NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE dims=["x", "y"],NEWLINE coords={"x": coord, "z": 3, "x2d": (("x", "y"), rs.randn(8, 6))},NEWLINE )NEWLINE if dask and has_dask:NEWLINE da = da.chunk({"x": 4})NEWLINENEWLINE ds = xr.Dataset({"var": da})NEWLINENEWLINE # along xNEWLINE actual = da.differentiate("x", edge_order)NEWLINE expected_x = xr.DataArray(NEWLINE np.gradient(da, da["x"], axis=0, edge_order=edge_order),NEWLINE dims=da.dims,NEWLINE coords=da.coords,NEWLINE )NEWLINE assert_equal(expected_x, actual)NEWLINE assert_equal(NEWLINE ds["var"].differentiate("x", edge_order=edge_order),NEWLINE ds.differentiate("x", edge_order=edge_order)["var"],NEWLINE )NEWLINE # coordinate should not changeNEWLINE assert_equal(da["x"], actual["x"])NEWLINENEWLINE # along yNEWLINE actual = da.differentiate("y", edge_order)NEWLINE expected_y = xr.DataArray(NEWLINE np.gradient(da, da["y"], axis=1, edge_order=edge_order),NEWLINE dims=da.dims,NEWLINE coords=da.coords,NEWLINE )NEWLINE assert_equal(expected_y, actual)NEWLINE assert_equal(actual, ds.differentiate("y", edge_order=edge_order)["var"])NEWLINE assert_equal(NEWLINE ds["var"].differentiate("y", edge_order=edge_order),NEWLINE ds.differentiate("y", edge_order=edge_order)["var"],NEWLINE )NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE da.differentiate("x2d")[email protected]("dask", [True, False])NEWLINEdef test_differentiate_datetime(dask):NEWLINE rs = np.random.RandomState(42)NEWLINE coord = np.array(NEWLINE [NEWLINE "2004-07-13",NEWLINE "2006-01-13",NEWLINE "2010-08-13",NEWLINE "2010-09-13",NEWLINE "2010-10-11",NEWLINE "2010-12-13",NEWLINE "2011-02-13",NEWLINE "2012-08-13",NEWLINE ],NEWLINE dtype="datetime64",NEWLINE )NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE dims=["x", "y"],NEWLINE coords={"x": coord, "z": 3, "x2d": (("x", "y"), rs.randn(8, 6))},NEWLINE )NEWLINE if dask and has_dask:NEWLINE da = da.chunk({"x": 4})NEWLINENEWLINE # along xNEWLINE actual = da.differentiate("x", edge_order=1, datetime_unit="D")NEWLINE expected_x = xr.DataArray(NEWLINE np.gradient(NEWLINE da, da["x"].variable._to_numeric(datetime_unit="D"), axis=0, edge_order=1NEWLINE ),NEWLINE dims=da.dims,NEWLINE coords=da.coords,NEWLINE )NEWLINE assert_equal(expected_x, actual)NEWLINENEWLINE actual2 = da.differentiate("x", edge_order=1, datetime_unit="h")NEWLINE assert np.allclose(actual, actual2 * 24)NEWLINENEWLINE # for datetime variableNEWLINE actual = da["x"].differentiate("x", edge_order=1, datetime_unit="D")NEWLINE assert np.allclose(actual, 1.0)NEWLINENEWLINE # with different date unitNEWLINE da = xr.DataArray(coord.astype("datetime64[ms]"), dims=["x"], coords={"x": coord})NEWLINE actual = da.differentiate("x", edge_order=1)NEWLINE assert np.allclose(actual, 1.0)[email protected](not has_cftime, reason="Test requires cftime.")[email protected]("dask", [True, False])NEWLINEdef test_differentiate_cftime(dask):NEWLINE rs = np.random.RandomState(42)NEWLINE coord = xr.cftime_range("2000", periods=8, freq="2M")NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE coords={"time": coord, "z": 3, "t2d": (("time", "y"), rs.randn(8, 6))},NEWLINE dims=["time", "y"],NEWLINE )NEWLINENEWLINE if dask and has_dask:NEWLINE da = da.chunk({"time": 4})NEWLINENEWLINE actual = da.differentiate("time", edge_order=1, datetime_unit="D")NEWLINE expected_data = np.gradient(NEWLINE da, da["time"].variable._to_numeric(datetime_unit="D"), axis=0, edge_order=1NEWLINE )NEWLINE expected = xr.DataArray(expected_data, coords=da.coords, dims=da.dims)NEWLINE assert_equal(expected, actual)NEWLINENEWLINE actual2 = da.differentiate("time", edge_order=1, datetime_unit="h")NEWLINE assert_allclose(actual, actual2 * 24)NEWLINENEWLINE # Test the differentiation of datetimes themselvesNEWLINE actual = da["time"].differentiate("time", edge_order=1, datetime_unit="D")NEWLINE assert_allclose(actual, xr.ones_like(da["time"]).astype(float))[email protected]("dask", [True, False])NEWLINEdef test_integrate(dask):NEWLINE rs = np.random.RandomState(42)NEWLINE coord = [0.2, 0.35, 0.4, 0.6, 0.7, 0.75, 0.76, 0.8]NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE dims=["x", "y"],NEWLINE coords={NEWLINE "x": coord,NEWLINE "x2": (("x",), rs.randn(8)),NEWLINE "z": 3,NEWLINE "x2d": (("x", "y"), rs.randn(8, 6)),NEWLINE },NEWLINE )NEWLINE if dask and has_dask:NEWLINE da = da.chunk({"x": 4})NEWLINENEWLINE ds = xr.Dataset({"var": da})NEWLINENEWLINE # along xNEWLINE actual = da.integrate("x")NEWLINE # coordinate that contains x should be dropped.NEWLINE expected_x = xr.DataArray(NEWLINE np.trapz(da, da["x"], axis=0),NEWLINE dims=["y"],NEWLINE coords={k: v for k, v in da.coords.items() if "x" not in v.dims},NEWLINE )NEWLINE assert_allclose(expected_x, actual.compute())NEWLINE assert_equal(ds["var"].integrate("x"), ds.integrate("x")["var"])NEWLINENEWLINE # make sure result is also a dask array (if the source is dask array)NEWLINE assert isinstance(actual.data, type(da.data))NEWLINENEWLINE # along yNEWLINE actual = da.integrate("y")NEWLINE expected_y = xr.DataArray(NEWLINE np.trapz(da, da["y"], axis=1),NEWLINE dims=["x"],NEWLINE coords={k: v for k, v in da.coords.items() if "y" not in v.dims},NEWLINE )NEWLINE assert_allclose(expected_y, actual.compute())NEWLINE assert_equal(actual, ds.integrate("y")["var"])NEWLINE assert_equal(ds["var"].integrate("y"), ds.integrate("y")["var"])NEWLINENEWLINE # along x and yNEWLINE actual = da.integrate(("y", "x"))NEWLINE assert actual.ndim == 0NEWLINENEWLINE with pytest.raises(ValueError):NEWLINE da.integrate("x2d")[email protected]("dask", [True, False])[email protected]("which_datetime", ["np", "cftime"])NEWLINEdef test_trapz_datetime(dask, which_datetime):NEWLINE rs = np.random.RandomState(42)NEWLINE if which_datetime == "np":NEWLINE coord = np.array(NEWLINE [NEWLINE "2004-07-13",NEWLINE "2006-01-13",NEWLINE "2010-08-13",NEWLINE "2010-09-13",NEWLINE "2010-10-11",NEWLINE "2010-12-13",NEWLINE "2011-02-13",NEWLINE "2012-08-13",NEWLINE ],NEWLINE dtype="datetime64",NEWLINE )NEWLINE else:NEWLINE if not has_cftime:NEWLINE pytest.skip("Test requires cftime.")NEWLINE coord = xr.cftime_range("2000", periods=8, freq="2D")NEWLINENEWLINE da = xr.DataArray(NEWLINE rs.randn(8, 6),NEWLINE coords={"time": coord, "z": 3, "t2d": (("time", "y"), rs.randn(8, 6))},NEWLINE dims=["time", "y"],NEWLINE )NEWLINENEWLINE if dask and has_dask:NEWLINE da = da.chunk({"time": 4})NEWLINENEWLINE actual = da.integrate("time", datetime_unit="D")NEWLINE expected_data = np.trapz(NEWLINE da, duck_array_ops.datetime_to_numeric(da["time"], datetime_unit="D"), axis=0NEWLINE )NEWLINE expected = xr.DataArray(NEWLINE expected_data,NEWLINE dims=["y"],NEWLINE coords={k: v for k, v in da.coords.items() if "time" not in v.dims},NEWLINE )NEWLINE assert_allclose(expected, actual.compute())NEWLINENEWLINE # make sure result is also a dask array (if the source is dask array)NEWLINE assert isinstance(actual.data, type(da.data))NEWLINENEWLINE actual2 = da.integrate("time", datetime_unit="h")NEWLINE assert_allclose(actual, actual2 / 24.0)NEWLINENEWLINENEWLINEdef test_no_dict():NEWLINE d = Dataset()NEWLINE with pytest.raises(AttributeError):NEWLINE d.__dict__NEWLINENEWLINENEWLINEdef test_subclass_slots():NEWLINE """Test that Dataset subclasses must explicitly define ``__slots__``.NEWLINENEWLINE .. note::NEWLINE As of 0.13.0, this is actually mitigated into a FutureWarning for any classNEWLINE defined outside of the xarray package.NEWLINE """NEWLINE with pytest.raises(AttributeError) as e:NEWLINENEWLINE class MyDS(Dataset):NEWLINE passNEWLINENEWLINE assert str(e.value) == "MyDS must explicitly define __slots__"NEWLINENEWLINENEWLINEdef test_weakref():NEWLINE """Classes with __slots__ are incompatible with the weakref module unless theyNEWLINE explicitly state __weakref__ among their slotsNEWLINE """NEWLINE from weakref import refNEWLINENEWLINE ds = Dataset()NEWLINE r = ref(ds)NEWLINE assert r() is dsNEWLINE |
import osNEWLINEimport reNEWLINEimport timeNEWLINENEWLINEimport pytestNEWLINEfrom helpers.cluster import ClickHouseClusterNEWLINEfrom helpers.test_tools import assert_eq_with_retry, TSVNEWLINENEWLINEcluster = ClickHouseCluster(__file__)NEWLINEnode = cluster.add_instance('node', main_configs=["configs/config.d/remote_servers.xml"],NEWLINE user_configs=["configs/users.d/row_policy.xml", "configs/users.d/another_user.xml",NEWLINE "configs/users.d/any_join_distinct_right_table_keys.xml"],NEWLINE with_zookeeper=True)NEWLINEnode2 = cluster.add_instance('node2', main_configs=["configs/config.d/remote_servers.xml"],NEWLINE user_configs=["configs/users.d/row_policy.xml", "configs/users.d/another_user.xml",NEWLINE "configs/users.d/any_join_distinct_right_table_keys.xml"],NEWLINE with_zookeeper=True)NEWLINEnodes = [node, node2]NEWLINENEWLINENEWLINEdef copy_policy_xml(local_file_name, reload_immediately=True):NEWLINE script_dir = os.path.dirname(os.path.realpath(__file__))NEWLINE for current_node in nodes:NEWLINE current_node.copy_file_to_container(os.path.join(script_dir, local_file_name),NEWLINE '/etc/clickhouse-server/users.d/row_policy.xml')NEWLINE if reload_immediately:NEWLINE current_node.query("SYSTEM RELOAD CONFIG")[email protected](scope="module", autouse=True)NEWLINEdef started_cluster():NEWLINE try:NEWLINE cluster.start()NEWLINENEWLINE for current_node in nodes:NEWLINE current_node.query('''NEWLINE CREATE DATABASE mydb;NEWLINENEWLINE CREATE TABLE mydb.filtered_table1 (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.filtered_table1 values (0, 0), (0, 1), (1, 0), (1, 1);NEWLINENEWLINE CREATE TABLE mydb.table (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.table values (0, 0), (0, 1), (1, 0), (1, 1);NEWLINENEWLINE CREATE TABLE mydb.filtered_table2 (a UInt8, b UInt8, c UInt8, d UInt8) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.filtered_table2 values (0, 0, 0, 0), (1, 2, 3, 4), (4, 3, 2, 1), (0, 0, 6, 0);NEWLINENEWLINE CREATE TABLE mydb.filtered_table3 (a UInt8, b UInt8, c UInt16 ALIAS a + b) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.filtered_table3 values (0, 0), (0, 1), (1, 0), (1, 1);NEWLINENEWLINE CREATE TABLE mydb.`.filtered_table4` (a UInt8, b UInt8, c UInt16 ALIAS a + b) ENGINE MergeTree ORDER BY a;NEWLINE INSERT INTO mydb.`.filtered_table4` values (0, 0), (0, 1), (1, 0), (1, 1);NEWLINENEWLINE CREATE TABLE mydb.local (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a;NEWLINE ''')NEWLINENEWLINE node.query("INSERT INTO mydb.local values (2, 0), (2, 1), (1, 0), (1, 1)")NEWLINE node2.query("INSERT INTO mydb.local values (3, 0), (3, 1), (1, 0), (1, 1)")NEWLINENEWLINE yield clusterNEWLINENEWLINE finally:NEWLINE cluster.shutdown()[email protected](autouse=True)NEWLINEdef reset_policies():NEWLINE try:NEWLINE yieldNEWLINE finally:NEWLINE copy_policy_xml('normal_filters.xml')NEWLINE for current_node in nodes:NEWLINE current_node.query("DROP POLICY IF EXISTS pA, pB ON mydb.filtered_table1")NEWLINENEWLINENEWLINEdef test_smoke():NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE assert node.query("SELECT a FROM mydb.filtered_table1") == TSV([[1], [1]])NEWLINE assert node.query("SELECT b FROM mydb.filtered_table1") == TSV([[0], [1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table1 WHERE a = 1") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table1 WHERE a IN (1)") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a = 1 FROM mydb.filtered_table1") == TSV([[1], [1]])NEWLINENEWLINE assert node.query("SELECT a FROM mydb.filtered_table3") == TSV([[0], [1]])NEWLINE assert node.query("SELECT b FROM mydb.filtered_table3") == TSV([[1], [0]])NEWLINE assert node.query("SELECT c FROM mydb.filtered_table3") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a + b FROM mydb.filtered_table3") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table3 WHERE c = 1") == TSV([[0], [1]])NEWLINE assert node.query("SELECT c = 1 FROM mydb.filtered_table3") == TSV([[1], [1]])NEWLINE assert node.query("SELECT a + b = 1 FROM mydb.filtered_table3") == TSV([[1], [1]])NEWLINENEWLINENEWLINEdef test_join():NEWLINE assert node.query(NEWLINE "SELECT * FROM mydb.filtered_table1 as t1 ANY LEFT JOIN mydb.filtered_table1 as t2 ON t1.a = t2.b") == TSV(NEWLINE [[1, 0, 1, 1], [1, 1, 1, 1]])NEWLINE assert node.query(NEWLINE "SELECT * FROM mydb.filtered_table1 as t2 ANY RIGHT JOIN mydb.filtered_table1 as t1 ON t2.b = t1.a") == TSV(NEWLINE [[1, 1, 1, 0]])NEWLINENEWLINENEWLINEdef test_cannot_trick_row_policy_with_keyword_with():NEWLINE assert node.query("WITH 0 AS a SELECT a FROM mydb.filtered_table1") == TSV([[0], [0]])NEWLINE assert node.query("WITH 0 AS a SELECT b FROM mydb.filtered_table1") == TSV([[0], [1]])NEWLINENEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1 WHERE a >= 0 AND b >= 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1 PREWHERE a >= 0 AND b >= 0") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1 PREWHERE a >= 0 WHERE b >= 0") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT * FROM mydb.filtered_table1 PREWHERE b >= 0 WHERE a >= 0") == TSV([[1, 0], [1, 1]])NEWLINENEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1 WHERE a >= 0 AND b >= 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1 PREWHERE a >= 0 AND b >= 0") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1 PREWHERE a >= 0 WHERE b >= 0") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("WITH 0 AS a SELECT a, b FROM mydb.filtered_table1 PREWHERE b >= 0 WHERE a >= 0") == TSV([[0, 0], [0, 1]])NEWLINENEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3 WHERE c >= 0 AND a >= 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([[0, 1], [1, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3 PREWHERE c >= 0 AND a >= 0") == TSV([[0, 1], [1, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3 PREWHERE c >= 0 WHERE a >= 0") == TSV([[0, 1], [1, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT * FROM mydb.filtered_table3 PREWHERE a >= 0 WHERE c >= 0") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3 WHERE c >= 0 AND a >= 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3 PREWHERE c >= 0 AND a >= 0") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3 PREWHERE c >= 0 WHERE a >= 0") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINE assert node.query("WITH 0 AS c SELECT a, b, c FROM mydb.filtered_table3 PREWHERE a >= 0 WHERE c >= 0") == TSV([[0, 1, 0], [1, 0, 0]])NEWLINENEWLINENEWLINEdef test_policy_from_users_xml_affects_only_user_assigned():NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user="another") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2", user="another") == TSV(NEWLINE [[0, 0, 0, 0], [0, 0, 6, 0], [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINENEWLINE assert node.query("SELECT * FROM mydb.local") == TSV([[1, 0], [1, 1], [2, 0], [2, 1]])NEWLINE assert node.query("SELECT * FROM mydb.local", user="another") == TSV([[1, 0], [1, 1]])NEWLINENEWLINENEWLINEdef test_with_prewhere():NEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[4, 3, 2, 1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[4]])NEWLINE assert node.query("SELECT a, b FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[4, 3]])NEWLINE assert node.query("SELECT b, c FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[3, 2]])NEWLINE assert node.query("SELECT d FROM mydb.filtered_table2 WHERE a > 1 SETTINGS optimize_move_to_prewhere = 0") == TSV([[1]])NEWLINENEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[4, 3, 2, 1]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[4]])NEWLINE assert node.query("SELECT a, b FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[4, 3]])NEWLINE assert node.query("SELECT b, c FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[3, 2]])NEWLINE assert node.query("SELECT d FROM mydb.filtered_table2 PREWHERE a > 1") == TSV([[1]])NEWLINENEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[1, 2, 3, 4]])NEWLINE assert node.query("SELECT a FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[1]])NEWLINE assert node.query("SELECT b FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[2]])NEWLINE assert node.query("SELECT a, b FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[1, 2]])NEWLINE assert node.query("SELECT a, c FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[1, 3]])NEWLINE assert node.query("SELECT b, d FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[2, 4]])NEWLINE assert node.query("SELECT c, d FROM mydb.filtered_table2 PREWHERE a < 4 WHERE b < 10") == TSV([[3, 4]])NEWLINENEWLINENEWLINEdef test_throwif_error_in_where_with_same_condition_as_filter():NEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert 'expected' in node.query_and_get_error("SELECT * FROM mydb.filtered_table2 WHERE throwIf(a > 0, 'expected') = 0 SETTINGS optimize_move_to_prewhere = 0")NEWLINENEWLINENEWLINEdef test_throwif_error_in_prewhere_with_same_condition_as_filter():NEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert 'expected' in node.query_and_get_error("SELECT * FROM mydb.filtered_table2 PREWHERE throwIf(a > 0, 'expected') = 0")NEWLINENEWLINENEWLINEdef test_throwif_in_where_doesnt_expose_restricted_data():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert 'expected' in node.query_and_get_error("SELECT * FROM mydb.filtered_table2 WHERE throwIf(a = 0, 'expected') = 0 SETTINGS optimize_move_to_prewhere = 0")NEWLINENEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 WHERE throwIf(a = 0, 'pwned') = 0 SETTINGS optimize_move_to_prewhere = 0") == TSV([NEWLINE [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINENEWLINENEWLINEdef test_throwif_in_prewhere_doesnt_expose_restricted_data():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert 'expected' in node.query_and_get_error("SELECT * FROM mydb.filtered_table2 PREWHERE throwIf(a = 0, 'expected') = 0")NEWLINENEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2 PREWHERE throwIf(a = 0, 'pwned') = 0") == TSV([NEWLINE [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINENEWLINENEWLINEdef test_change_of_users_xml_changes_row_policies():NEWLINE copy_policy_xml('normal_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE copy_policy_xml('all_rows.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV(NEWLINE [[0, 0, 0, 0], [0, 0, 6, 0], [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE copy_policy_xml('no_rows.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == ""NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == ""NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == ""NEWLINENEWLINE copy_policy_xml('normal_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE copy_policy_xml('normal_filter2_table2.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[1, 2, 3, 4], [4, 3, 2, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV(NEWLINE [[0, 0, 0, 0], [0, 0, 6, 0], [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE copy_policy_xml('normal_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINENEWLINEdef test_reload_users_xml_by_timer():NEWLINE copy_policy_xml('normal_filters.xml')NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 1], [1, 0]])NEWLINENEWLINE time.sleep(1) # The modification time of the 'row_policy.xml' file should be different.NEWLINE copy_policy_xml('all_rows.xml', False)NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table1", [[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table2",NEWLINE [[0, 0, 0, 0], [0, 0, 6, 0], [1, 2, 3, 4], [4, 3, 2, 1]])NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table3", [[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE time.sleep(1) # The modification time of the 'row_policy.xml' file should be different.NEWLINE copy_policy_xml('normal_filters.xml', False)NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table1", [[1, 0], [1, 1]])NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table2", [[0, 0, 0, 0], [0, 0, 6, 0]])NEWLINE assert_eq_with_retry(node, "SELECT * FROM mydb.filtered_table3", [[0, 1], [1, 0]])NEWLINENEWLINENEWLINEdef test_introspection():NEWLINE policies = [NEWLINE ["another ON mydb.filtered_table1", "another", "mydb", "filtered_table1",NEWLINE "6068883a-0e9d-f802-7e22-0144f8e66d3c", "users.xml", "1", "permissive", 0, "['another']", "[]"],NEWLINE ["another ON mydb.filtered_table2", "another", "mydb", "filtered_table2",NEWLINE "c019e957-c60b-d54e-cc52-7c90dac5fb01", "users.xml", "1", "permissive", 0, "['another']", "[]"],NEWLINE ["another ON mydb.filtered_table3", "another", "mydb", "filtered_table3",NEWLINE "4cb080d0-44e8-dbef-6026-346655143628", "users.xml", "1", "permissive", 0, "['another']", "[]"],NEWLINE ["another ON mydb.local", "another", "mydb", "local", "5b23c389-7e18-06bf-a6bc-dd1afbbc0a97", "users.xml",NEWLINE "a = 1", "permissive", 0, "['another']", "[]"],NEWLINE ["default ON mydb.filtered_table1", "default", "mydb", "filtered_table1",NEWLINE "9e8a8f62-4965-2b5e-8599-57c7b99b3549", "users.xml", "a = 1", "permissive", 0, "['default']", "[]"],NEWLINE ["default ON mydb.filtered_table2", "default", "mydb", "filtered_table2",NEWLINE "cffae79d-b9bf-a2ef-b798-019c18470b25", "users.xml", "a + b < 1 or c - d > 5", "permissive", 0, "['default']", "[]"],NEWLINE ["default ON mydb.filtered_table3", "default", "mydb", "filtered_table3",NEWLINE "12fc5cef-e3da-3940-ec79-d8be3911f42b", "users.xml", "c = 1", "permissive", 0, "['default']", "[]"],NEWLINE ["default ON mydb.local", "default", "mydb", "local", "cdacaeb5-1d97-f99d-2bb0-4574f290629c", "users.xml", "1",NEWLINE "permissive", 0, "['default']", "[]"]NEWLINE ]NEWLINE assert node.query("SELECT * from system.row_policies ORDER BY short_name, database, table") == TSV(policies)NEWLINENEWLINENEWLINEdef test_dcl_introspection():NEWLINE assert node.query("SHOW POLICIES") == TSV(NEWLINE ["another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3",NEWLINE "another ON mydb.local", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2",NEWLINE "default ON mydb.filtered_table3", "default ON mydb.local"])NEWLINENEWLINE assert node.query("SHOW POLICIES ON mydb.filtered_table1") == TSV(["another", "default"])NEWLINE assert node.query("SHOW POLICIES ON mydb.local") == TSV(["another", "default"])NEWLINE assert node.query("SHOW POLICIES ON mydb.*") == TSV(NEWLINE ["another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3",NEWLINE "another ON mydb.local", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2",NEWLINE "default ON mydb.filtered_table3", "default ON mydb.local"])NEWLINE assert node.query("SHOW POLICIES default") == TSV(NEWLINE ["default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3",NEWLINE "default ON mydb.local"])NEWLINENEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.local") == "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default\n"NEWLINENEWLINE assert node.query("SHOW CREATE POLICY default") == TSV(NEWLINE ["CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default"])NEWLINE assert node.query("SHOW CREATE POLICIES ON mydb.filtered_table1") == TSV(NEWLINE ["CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default"])NEWLINE assert node.query("SHOW CREATE POLICIES ON mydb.*") == TSV(NEWLINE ["CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default"])NEWLINE assert node.query("SHOW CREATE POLICIES") == TSV(NEWLINE ["CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 AS permissive TO another",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default"])NEWLINENEWLINE expected_access = "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO another\n" \NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 AS permissive TO another\n" \NEWLINE "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 AS permissive TO another\n" \NEWLINE "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 AS permissive TO another\n" \NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 AS permissive TO default\n" \NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) AS permissive TO default\n" \NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 AS permissive TO default\n" \NEWLINE "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 AS permissive TO default\n"NEWLINE assert expected_access in node.query("SHOW ACCESS")NEWLINENEWLINE copy_policy_xml('all_rows.xml')NEWLINE assert node.query("SHOW POLICIES") == TSV(NEWLINE ["another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3",NEWLINE "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3"])NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING 1 AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING 1 AS permissive TO default\n"NEWLINENEWLINE copy_policy_xml('no_rows.xml')NEWLINE assert node.query("SHOW POLICIES") == TSV(NEWLINE ["another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3",NEWLINE "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3"])NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING NULL AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING NULL AS permissive TO default\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING NULL AS permissive TO default\n"NEWLINENEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINENEWLINENEWLINEdef test_dcl_management():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINENEWLINE node.query("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a<b")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == ""NEWLINE assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pA\n"NEWLINENEWLINE node.query("ALTER POLICY pA ON mydb.filtered_table1 TO default")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 1]])NEWLINE assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pA\n"NEWLINENEWLINE node.query("ALTER POLICY pA ON mydb.filtered_table1 FOR SELECT USING a>b")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0]])NEWLINENEWLINE node.query("ALTER POLICY pA ON mydb.filtered_table1 RENAME TO pB")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0]])NEWLINE assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pB\n"NEWLINE assert node.query(NEWLINE "SHOW CREATE POLICY pB ON mydb.filtered_table1") == "CREATE ROW POLICY pB ON mydb.filtered_table1 FOR SELECT USING a > b AS permissive TO default\n"NEWLINENEWLINE node.query("DROP POLICY pB ON mydb.filtered_table1")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINENEWLINENEWLINEdef test_grant_create_row_policy():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINE node.query("CREATE USER X")NEWLINENEWLINE expected_error = "necessary to have grant CREATE ROW POLICY ON mydb.filtered_table1"NEWLINE assert expected_error in node.query_and_get_error("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a<b", user='X')NEWLINE node.query("GRANT CREATE POLICY ON mydb.filtered_table1 TO X")NEWLINE node.query("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a<b", user='X')NEWLINE expected_error = "necessary to have grant CREATE ROW POLICY ON mydb.filtered_table2"NEWLINE assert expected_error in node.query_and_get_error("CREATE POLICY pA ON mydb.filtered_table2 FOR SELECT USING a<b", user='X')NEWLINENEWLINE expected_error = "necessary to have grant ALTER ROW POLICY ON mydb.filtered_table1"NEWLINE assert expected_error in node.query_and_get_error("ALTER POLICY pA ON mydb.filtered_table1 FOR SELECT USING a==b", user='X')NEWLINE node.query("GRANT ALTER POLICY ON mydb.filtered_table1 TO X")NEWLINE node.query("ALTER POLICY pA ON mydb.filtered_table1 FOR SELECT USING a==b", user='X')NEWLINE expected_error = "necessary to have grant ALTER ROW POLICY ON mydb.filtered_table2"NEWLINE assert expected_error in node.query_and_get_error("ALTER POLICY pA ON mydb.filtered_table2 FOR SELECT USING a==b", user='X')NEWLINENEWLINE expected_error = "necessary to have grant DROP ROW POLICY ON mydb.filtered_table1"NEWLINE assert expected_error in node.query_and_get_error("DROP POLICY pA ON mydb.filtered_table1", user='X')NEWLINE node.query("GRANT DROP POLICY ON mydb.filtered_table1 TO X")NEWLINE node.query("DROP POLICY pA ON mydb.filtered_table1", user='X')NEWLINE expected_error = "necessary to have grant DROP ROW POLICY ON mydb.filtered_table2"NEWLINE assert expected_error in node.query_and_get_error("DROP POLICY pA ON mydb.filtered_table2", user='X')NEWLINENEWLINE node.query("REVOKE ALL ON *.* FROM X")NEWLINENEWLINE expected_error = "necessary to have grant CREATE ROW POLICY ON mydb.filtered_table1"NEWLINE assert expected_error in node.query_and_get_error("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a<b", user='X')NEWLINE node.query("GRANT CREATE POLICY ON *.* TO X")NEWLINE node.query("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a<b", user='X')NEWLINE NEWLINE expected_error = "necessary to have grant ALTER ROW POLICY ON mydb.filtered_table1"NEWLINE assert expected_error in node.query_and_get_error("ALTER POLICY pA ON mydb.filtered_table1 FOR SELECT USING a==b", user='X')NEWLINE node.query("GRANT ALTER POLICY ON *.* TO X")NEWLINE node.query("ALTER POLICY pA ON mydb.filtered_table1 FOR SELECT USING a==b", user='X')NEWLINENEWLINE expected_error = "necessary to have grant DROP ROW POLICY ON mydb.filtered_table1"NEWLINE assert expected_error in node.query_and_get_error("DROP POLICY pA ON mydb.filtered_table1", user='X')NEWLINE node.query("GRANT DROP POLICY ON *.* TO X")NEWLINE node.query("DROP POLICY pA ON mydb.filtered_table1", user='X')NEWLINENEWLINE node.query("DROP USER X")NEWLINENEWLINENEWLINEdef test_users_xml_is_readonly():NEWLINE assert re.search("storage is readonly", node.query_and_get_error("DROP POLICY default ON mydb.filtered_table1"))NEWLINENEWLINENEWLINEdef test_some_users_without_policies():NEWLINE copy_policy_xml('no_filters.xml')NEWLINE assert node.query("SHOW POLICIES") == ""NEWLINE node.query("CREATE USER X, Y")NEWLINE node.query("GRANT SELECT ON mydb.filtered_table1 TO X, Y")NEWLINENEWLINE node.query("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a < b AS permissive TO X")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='X') == TSV([[0, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='Y') == ""NEWLINENEWLINE node.query("ALTER POLICY pA ON mydb.filtered_table1 AS restrictive")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='X') == ""NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='Y') == ""NEWLINE node.query("CREATE POLICY pB ON mydb.filtered_table1 FOR SELECT USING 1 AS permissive TO X")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='X') == TSV([[0, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='Y') == ""NEWLINE node.query("ALTER POLICY pB ON mydb.filtered_table1 TO X, Y")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='X') == TSV([[0, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='Y') == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINE node.query("DROP POLICY pB ON mydb.filtered_table1")NEWLINENEWLINE node.query("ALTER POLICY pA ON mydb.filtered_table1 AS simple")NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='X') == TSV([[0, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table1", user='Y') == TSV([[0, 0], [0, 1], [1, 0], [1, 1]])NEWLINENEWLINE node.query("DROP USER X, Y")NEWLINENEWLINENEWLINEdef test_tags_with_db_and_table_names():NEWLINE copy_policy_xml('tags_with_db_and_table_names.xml')NEWLINENEWLINE assert node.query("SELECT * FROM mydb.table") == TSV([[0, 0], [0, 1]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table2") == TSV([[0, 0, 6, 0]])NEWLINE assert node.query("SELECT * FROM mydb.filtered_table3") == TSV([[0, 0]])NEWLINE assert node.query("SELECT * FROM mydb.`.filtered_table4`") == TSV([[1, 1]])NEWLINENEWLINE assert node.query("SHOW CREATE POLICIES default") == TSV(NEWLINE ["CREATE ROW POLICY default ON mydb.`.filtered_table4` FOR SELECT USING c = 2 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING c > (d + 5) AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 0 AS permissive TO default",NEWLINE "CREATE ROW POLICY default ON mydb.table FOR SELECT USING a = 0 AS permissive TO default"])NEWLINENEWLINENEWLINEdef test_miscellaneous_engines():NEWLINE node.query("CREATE ROW POLICY OR REPLACE pC ON mydb.other_table FOR SELECT USING a = 1 TO default")NEWLINE assert node.query("SHOW ROW POLICIES ON mydb.other_table") == "pC\n"NEWLINENEWLINE # ReplicatedMergeTreeNEWLINE node.query("DROP TABLE IF EXISTS mydb.other_table")NEWLINE node.query("CREATE TABLE mydb.other_table (a UInt8, b UInt8) ENGINE ReplicatedMergeTree('/clickhouse/tables/00-00/filtered_table1', 'replica1') ORDER BY a")NEWLINE node.query("INSERT INTO mydb.other_table values (0, 0), (0, 1), (1, 0), (1, 1)")NEWLINE assert node.query("SELECT * FROM mydb.other_table") == TSV([[1, 0], [1, 1]])NEWLINENEWLINE # CollapsingMergeTreeNEWLINE node.query("DROP TABLE mydb.other_table")NEWLINE node.query("CREATE TABLE mydb.other_table (a UInt8, b Int8) ENGINE CollapsingMergeTree(b) ORDER BY a")NEWLINE node.query("INSERT INTO mydb.other_table values (0, 1), (0, 1), (1, 1), (1, 1)")NEWLINE assert node.query("SELECT * FROM mydb.other_table") == TSV([[1, 1], [1, 1]])NEWLINENEWLINE # ReplicatedCollapsingMergeTreeNEWLINE node.query("DROP TABLE mydb.other_table")NEWLINE node.query("CREATE TABLE mydb.other_table (a UInt8, b Int8) ENGINE ReplicatedCollapsingMergeTree('/clickhouse/tables/00-01/filtered_table1', 'replica1', b) ORDER BY a")NEWLINE node.query("INSERT INTO mydb.other_table values (0, 1), (0, 1), (1, 1), (1, 1)")NEWLINE assert node.query("SELECT * FROM mydb.other_table") == TSV([[1, 1], [1, 1]])NEWLINENEWLINE node.query("DROP ROW POLICY pC ON mydb.other_table")NEWLINENEWLINE # DistributedMergeTreeNEWLINE node.query("DROP TABLE IF EXISTS mydb.other_table")NEWLINE node.query("CREATE TABLE mydb.other_table (a UInt8, b UInt8) ENGINE Distributed('test_local_cluster', mydb, local)")NEWLINE assert node.query("SELECT * FROM mydb.other_table", user="another") == TSV([[1, 0], [1, 1], [1, 0], [1, 1]])NEWLINE assert node.query("SELECT sum(a), b FROM mydb.other_table GROUP BY b ORDER BY b", user="another") == TSV([[2, 0], [2, 1]])NEWLINENEWLINENEWLINEdef test_policy_on_distributed_table_via_role():NEWLINE node.query("DROP TABLE IF EXISTS local_tbl")NEWLINE node.query("DROP TABLE IF EXISTS dist_tbl")NEWLINENEWLINE node.query("CREATE TABLE local_tbl engine=MergeTree ORDER BY tuple() as select * FROM numbers(10)")NEWLINE node.query("CREATE TABLE dist_tbl ENGINE=Distributed( 'test_cluster_two_shards_localhost', default, local_tbl) AS local_tbl")NEWLINENEWLINE node.query("CREATE ROLE OR REPLACE 'role1'")NEWLINE node.query("CREATE USER OR REPLACE 'user1' DEFAULT ROLE 'role1'")NEWLINENEWLINE node.query("GRANT SELECT ON dist_tbl TO 'role1'")NEWLINE node.query("GRANT SELECT ON local_tbl TO 'role1'")NEWLINENEWLINE node.query("CREATE ROW POLICY OR REPLACE 'all_data' ON dist_tbl, local_tbl USING 1 TO ALL EXCEPT 'role1'")NEWLINE node.query("CREATE ROW POLICY OR REPLACE 'role1_data' ON dist_tbl, local_tbl USING number % 2 = 0 TO 'role1'")NEWLINENEWLINE assert node.query("SELECT * FROM local_tbl SETTINGS prefer_localhost_replica=0", user="user1") == TSV([[0], [2], [4], [6], [8]])NEWLINE assert node.query("SELECT * FROM dist_tbl SETTINGS prefer_localhost_replica=0", user="user1") == TSV([[0], [2], [4], [6], [8], [0], [2], [4], [6], [8]])NEWLINE |
NEWLINEimport osNEWLINEimport timeNEWLINEimport signalNEWLINEimport socketNEWLINEimport loggingNEWLINEimport unittestNEWLINEimport BaseHTTPServerNEWLINENEWLINEimport redisNEWLINEimport requestsNEWLINENEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINElogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',NEWLINE level=logging.DEBUG)NEWLINENEWLINENEWLINEclass HTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args, **kwargs)NEWLINENEWLINE def do_GET(self):NEWLINE self.send_response(self.server._code)NEWLINE body = self.server._body if self.server._body else 'This is a body'NEWLINE self.send_header('Content-Length', len(body))NEWLINE if self.server._headers:NEWLINE for header in self.server._headers:NEWLINE self.send_header(*header)NEWLINE self.send_header('Connection', 'close')NEWLINE self.end_headers()NEWLINE self.wfile.write(body)NEWLINE self.wfile.flush()NEWLINENEWLINE def do_HEAD(self):NEWLINE return self.do_GET()NEWLINENEWLINENEWLINEclass TestCase(unittest.TestCase):NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE unittest.TestCase.__init__(self, *args, **kwargs)NEWLINE self.redis = redis.StrictRedis(os.getenv('REDIS_ADDRESS', 'localhost'), os.getenv('REDIS_PORT', 6379))NEWLINE self.check_ready()NEWLINE self._httpd_pids = []NEWLINE self._frontends = []NEWLINE self.addCleanup(self.stop_all_httpd)NEWLINE self.addCleanup(self.unregister_all_frontends)NEWLINENEWLINE def check_ready(self):NEWLINE """ Makes sure the activechecker is running """NEWLINE r = NoneNEWLINE try:NEWLINE r = requests.get('http://localhost:1080', headers={'Host': '__ping__'})NEWLINE except Exception:NEWLINE passNEWLINE if r is None or r.status_code != 200:NEWLINE self.fail('Hipache should run on port 1080: \n'NEWLINE '$ hipache -c config/config_test.json')NEWLINENEWLINE def stop_all_httpd(self):NEWLINE if not self._httpd_pids:NEWLINE returnNEWLINE for pid in self._httpd_pids:NEWLINE os.kill(pid, signal.SIGKILL)NEWLINE logger.info('httpd killed. PID: {0}'.format(pid))NEWLINE os.wait()NEWLINENEWLINE def spawn_httpd(self, port, code=200, headers=None, body=None):NEWLINE pid = os.fork()NEWLINE if pid > 0:NEWLINE # In the father, wait for the child to be availableNEWLINE while True:NEWLINE r = self.http_request('localhost', port=port)NEWLINE if r > 0:NEWLINE self._httpd_pids.append(pid)NEWLINE logger.info('httpd spawned on port {0}. PID: {1}'.format(port, pid))NEWLINE return pidNEWLINE time.sleep(0.5)NEWLINE # In the child, spawn the httpdNEWLINE httpd = BaseHTTPServer.HTTPServer(('localhost', port), HTTPHandler)NEWLINE httpd._code = codeNEWLINE httpd._headers = headersNEWLINE httpd._body = bodyNEWLINE httpd.serve_forever()NEWLINENEWLINE def stop_httpd(self, pid):NEWLINE os.kill(pid, signal.SIGKILL)NEWLINE logger.info('httpd stopped. PID: {0}'.format(pid))NEWLINE os.wait()NEWLINE if pid in self._httpd_pids:NEWLINE self._httpd_pids.remove(pid)NEWLINENEWLINE def register_frontend(self, frontend, backends_url):NEWLINE self.redis.rpush('frontend:{0}'.format(frontend), frontend, *backends_url)NEWLINE self._frontends.append(frontend)NEWLINENEWLINE def unregister_frontend(self, frontend):NEWLINE self.redis.delete('frontend:{0}'.format(frontend))NEWLINE self.redis.delete('dead:{0}'.format(frontend))NEWLINE if frontend in self._frontends:NEWLINE self._frontends.remove(frontend)NEWLINENEWLINE def unregister_all_frontends(self):NEWLINE # Copy the list of frontend since we modify the list inside the loopNEWLINE for frontend in list(self._frontends):NEWLINE self.unregister_frontend(frontend)NEWLINENEWLINE def http_request(self, host, port=1080):NEWLINE try:NEWLINE headers = {'Host': host, 'X-Debug': 'true'}NEWLINE r = requests.get('http://localhost:{0}/'.format(port),NEWLINE headers=headers,NEWLINE timeout=1.0)NEWLINE logger.debug('Frontend: {0}; Headers: {1}; Payload: "{2}"'.format(NEWLINE host, r.headers, r.text))NEWLINE return r.status_codeNEWLINE except (requests.ConnectionError, requests.Timeout, socket.timeout):NEWLINE return -1NEWLINE |
from __future__ import print_functionNEWLINE# Copyright (c) 2012 Google Inc. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINENEWLINEimport filecmpNEWLINEimport gyp.commonNEWLINEimport gyp.xcodeproj_fileNEWLINEimport gyp.xcode_ninjaNEWLINEimport errnoNEWLINEimport osNEWLINEimport sysNEWLINEimport posixpathNEWLINEimport reNEWLINEimport shutilNEWLINEimport subprocessNEWLINEimport tempfileNEWLINENEWLINENEWLINE# Project files generated by this module will use _intermediate_var as aNEWLINE# custom Xcode setting whose value is a DerivedSources-like directory that'sNEWLINE# project-specific and configuration-specific. The normal choice,NEWLINE# DERIVED_FILE_DIR, is target-specific, which is thought to be too restrictiveNEWLINE# as it is likely that multiple targets within a single project file will wantNEWLINE# to access the same set of generated files. The other option,NEWLINE# PROJECT_DERIVED_FILE_DIR, is unsuitable because while it is project-specific,NEWLINE# it is not configuration-specific. INTERMEDIATE_DIR is defined asNEWLINE# $(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION).NEWLINE_intermediate_var = 'INTERMEDIATE_DIR'NEWLINENEWLINE# SHARED_INTERMEDIATE_DIR is the same, except that it is shared among allNEWLINE# targets that share the same BUILT_PRODUCTS_DIR.NEWLINE_shared_intermediate_var = 'SHARED_INTERMEDIATE_DIR'NEWLINENEWLINE_library_search_paths_var = 'LIBRARY_SEARCH_PATHS'NEWLINENEWLINEgenerator_default_variables = {NEWLINE 'EXECUTABLE_PREFIX': '',NEWLINE 'EXECUTABLE_SUFFIX': '',NEWLINE 'STATIC_LIB_PREFIX': 'lib',NEWLINE 'SHARED_LIB_PREFIX': 'lib',NEWLINE 'STATIC_LIB_SUFFIX': '.a',NEWLINE 'SHARED_LIB_SUFFIX': '.dylib',NEWLINE # INTERMEDIATE_DIR is a place for targets to build up intermediate products.NEWLINE # It is specific to each build environment. It is only guaranteed to existNEWLINE # and be constant within the context of a project, corresponding to a singleNEWLINE # input file. Some build environments may allow their intermediate directoryNEWLINE # to be shared on a wider scale, but this is not guaranteed.NEWLINE 'INTERMEDIATE_DIR': '$(%s)' % _intermediate_var,NEWLINE 'OS': 'mac',NEWLINE 'PRODUCT_DIR': '$(BUILT_PRODUCTS_DIR)',NEWLINE 'LIB_DIR': '$(BUILT_PRODUCTS_DIR)',NEWLINE 'RULE_INPUT_ROOT': '$(INPUT_FILE_BASE)',NEWLINE 'RULE_INPUT_EXT': '$(INPUT_FILE_SUFFIX)',NEWLINE 'RULE_INPUT_NAME': '$(INPUT_FILE_NAME)',NEWLINE 'RULE_INPUT_PATH': '$(INPUT_FILE_PATH)',NEWLINE 'RULE_INPUT_DIRNAME': '$(INPUT_FILE_DIRNAME)',NEWLINE 'SHARED_INTERMEDIATE_DIR': '$(%s)' % _shared_intermediate_var,NEWLINE 'CONFIGURATION_NAME': '$(CONFIGURATION)',NEWLINE}NEWLINENEWLINE# The Xcode-specific sections that hold paths.NEWLINEgenerator_additional_path_sections = [NEWLINE 'mac_bundle_resources',NEWLINE 'mac_framework_headers',NEWLINE 'mac_framework_private_headers',NEWLINE # 'mac_framework_dirs', input already handles _dirs endings.NEWLINE]NEWLINENEWLINE# The Xcode-specific keys that exist on targets and aren't moved down toNEWLINE# configurations.NEWLINEgenerator_additional_non_configuration_keys = [NEWLINE 'ios_app_extension',NEWLINE 'ios_watch_app',NEWLINE 'ios_watchkit_extension',NEWLINE 'mac_bundle',NEWLINE 'mac_bundle_resources',NEWLINE 'mac_framework_headers',NEWLINE 'mac_framework_private_headers',NEWLINE 'mac_xctest_bundle',NEWLINE 'xcode_create_dependents_test_runner',NEWLINE]NEWLINENEWLINE# We want to let any rules apply to files that are resources also.NEWLINEgenerator_extra_sources_for_rules = [NEWLINE 'mac_bundle_resources',NEWLINE 'mac_framework_headers',NEWLINE 'mac_framework_private_headers',NEWLINE]NEWLINENEWLINEgenerator_filelist_paths = NoneNEWLINENEWLINE# Xcode's standard set of library directories, which don't need to be duplicatedNEWLINE# in LIBRARY_SEARCH_PATHS. This list is not exhaustive, but that's okay.NEWLINExcode_standard_library_dirs = frozenset([NEWLINE '$(SDKROOT)/usr/lib',NEWLINE '$(SDKROOT)/usr/local/lib',NEWLINE])NEWLINENEWLINEdef CreateXCConfigurationList(configuration_names):NEWLINE xccl = gyp.xcodeproj_file.XCConfigurationList({'buildConfigurations': []})NEWLINE if len(configuration_names) == 0:NEWLINE configuration_names = ['Default']NEWLINE for configuration_name in configuration_names:NEWLINE xcbc = gyp.xcodeproj_file.XCBuildConfiguration({NEWLINE 'name': configuration_name})NEWLINE xccl.AppendProperty('buildConfigurations', xcbc)NEWLINE xccl.SetProperty('defaultConfigurationName', configuration_names[0])NEWLINE return xcclNEWLINENEWLINENEWLINEclass XcodeProject(object):NEWLINE def __init__(self, gyp_path, path, build_file_dict):NEWLINE self.gyp_path = gyp_pathNEWLINE self.path = pathNEWLINE self.project = gyp.xcodeproj_file.PBXProject(path=path)NEWLINE projectDirPath = gyp.common.RelativePath(NEWLINE os.path.dirname(os.path.abspath(self.gyp_path)),NEWLINE os.path.dirname(path) or '.')NEWLINE self.project.SetProperty('projectDirPath', projectDirPath)NEWLINE self.project_file = \NEWLINE gyp.xcodeproj_file.XCProjectFile({'rootObject': self.project})NEWLINE self.build_file_dict = build_file_dictNEWLINENEWLINE # TODO(mark): add destructor that cleans up self.path if created_dir isNEWLINE # True and things didn't complete successfully. Or do something evenNEWLINE # better with "try"?NEWLINE self.created_dir = FalseNEWLINE try:NEWLINE os.makedirs(self.path)NEWLINE self.created_dir = TrueNEWLINE except OSError as e:NEWLINE if e.errno != errno.EEXIST:NEWLINE raiseNEWLINENEWLINE def Finalize1(self, xcode_targets, serialize_all_tests):NEWLINE # Collect a list of all of the build configuration names used by theNEWLINE # various targets in the file. It is very heavily advised to keep eachNEWLINE # target in an entire project (even across multiple project files) usingNEWLINE # the same set of configuration names.NEWLINE configurations = []NEWLINE for xct in self.project.GetProperty('targets'):NEWLINE xccl = xct.GetProperty('buildConfigurationList')NEWLINE xcbcs = xccl.GetProperty('buildConfigurations')NEWLINE for xcbc in xcbcs:NEWLINE name = xcbc.GetProperty('name')NEWLINE if name not in configurations:NEWLINE configurations.append(name)NEWLINENEWLINE # Replace the XCConfigurationList attached to the PBXProject object withNEWLINE # a new one specifying all of the configuration names used by the variousNEWLINE # targets.NEWLINE try:NEWLINE xccl = CreateXCConfigurationList(configurations)NEWLINE self.project.SetProperty('buildConfigurationList', xccl)NEWLINE except:NEWLINE sys.stderr.write("Problem with gyp file %s\n" % self.gyp_path)NEWLINE raiseNEWLINENEWLINE # The need for this setting is explained above where _intermediate_var isNEWLINE # defined. The comments below about wanting to avoid project-wide buildNEWLINE # settings apply here too, but this needs to be set on a project-wide basisNEWLINE # so that files relative to the _intermediate_var setting can be displayedNEWLINE # properly in the Xcode UI.NEWLINE #NEWLINE # Note that for configuration-relative files such as anything relative toNEWLINE # _intermediate_var, for the purposes of UI tree view display, Xcode willNEWLINE # only resolve the configuration name once, when the project file isNEWLINE # opened. If the active build configuration is changed, the project fileNEWLINE # must be closed and reopened if it is desired for the tree view to update.NEWLINE # This is filed as Apple radar 6588391.NEWLINE xccl.SetBuildSetting(_intermediate_var,NEWLINE '$(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION)')NEWLINE xccl.SetBuildSetting(_shared_intermediate_var,NEWLINE '$(SYMROOT)/DerivedSources/$(CONFIGURATION)')NEWLINENEWLINE # Set user-specified project-wide build settings and config files. ThisNEWLINE # is intended to be used very sparingly. Really, almost everything shouldNEWLINE # go into target-specific build settings sections. The project-wideNEWLINE # settings are only intended to be used in cases where Xcode attempts toNEWLINE # resolve variable references in a project context as opposed to a targetNEWLINE # context, such as when resolving sourceTree references while building upNEWLINE # the tree tree view for UI display.NEWLINE # Any values set globally are applied to all configurations, then anyNEWLINE # per-configuration values are applied.NEWLINE for xck, xcv in self.build_file_dict.get('xcode_settings', {}).items():NEWLINE xccl.SetBuildSetting(xck, xcv)NEWLINE if 'xcode_config_file' in self.build_file_dict:NEWLINE config_ref = self.project.AddOrGetFileInRootGroup(NEWLINE self.build_file_dict['xcode_config_file'])NEWLINE xccl.SetBaseConfiguration(config_ref)NEWLINE build_file_configurations = self.build_file_dict.get('configurations', {})NEWLINE if build_file_configurations:NEWLINE for config_name in configurations:NEWLINE build_file_configuration_named = \NEWLINE build_file_configurations.get(config_name, {})NEWLINE if build_file_configuration_named:NEWLINE xcc = xccl.ConfigurationNamed(config_name)NEWLINE for xck, xcv in build_file_configuration_named.get('xcode_settings',NEWLINE {}).items():NEWLINE xcc.SetBuildSetting(xck, xcv)NEWLINE if 'xcode_config_file' in build_file_configuration_named:NEWLINE config_ref = self.project.AddOrGetFileInRootGroup(NEWLINE build_file_configurations[config_name]['xcode_config_file'])NEWLINE xcc.SetBaseConfiguration(config_ref)NEWLINENEWLINE # Sort the targets based on how they appeared in the input.NEWLINE # TODO(mark): Like a lot of other things here, this assumes internalNEWLINE # knowledge of PBXProject - in this case, of its "targets" property.NEWLINENEWLINE # ordinary_targets are ordinary targets that are already in the projectNEWLINE # file. run_test_targets are the targets that run unittests and should beNEWLINE # used for the Run All Tests target. support_targets are the action/ruleNEWLINE # targets used by GYP file targets, just kept for the assert check.NEWLINE ordinary_targets = []NEWLINE run_test_targets = []NEWLINE support_targets = []NEWLINENEWLINE # targets is full list of targets in the project.NEWLINE targets = []NEWLINENEWLINE # does the it define it's own "all"?NEWLINE has_custom_all = FalseNEWLINENEWLINE # targets_for_all is the list of ordinary_targets that should be listedNEWLINE # in this project's "All" target. It includes each non_runtest_targetNEWLINE # that does not have suppress_wildcard set.NEWLINE targets_for_all = []NEWLINENEWLINE for target in self.build_file_dict['targets']:NEWLINE target_name = target['target_name']NEWLINE toolset = target['toolset']NEWLINE qualified_target = gyp.common.QualifiedTarget(self.gyp_path, target_name,NEWLINE toolset)NEWLINE xcode_target = xcode_targets[qualified_target]NEWLINE # Make sure that the target being added to the sorted list is already inNEWLINE # the unsorted list.NEWLINE assert xcode_target in self.project._properties['targets']NEWLINE targets.append(xcode_target)NEWLINE ordinary_targets.append(xcode_target)NEWLINE if xcode_target.support_target:NEWLINE support_targets.append(xcode_target.support_target)NEWLINE targets.append(xcode_target.support_target)NEWLINENEWLINE if not int(target.get('suppress_wildcard', False)):NEWLINE targets_for_all.append(xcode_target)NEWLINENEWLINE if target_name.lower() == 'all':NEWLINE has_custom_all = TrueNEWLINENEWLINE # If this target has a 'run_as' attribute, add its target to theNEWLINE # targets, and add it to the test targets.NEWLINE if target.get('run_as'):NEWLINE # Make a target to run something. It should have oneNEWLINE # dependency, the parent xcode target.NEWLINE xccl = CreateXCConfigurationList(configurations)NEWLINE run_target = gyp.xcodeproj_file.PBXAggregateTarget({NEWLINE 'name': 'Run ' + target_name,NEWLINE 'productName': xcode_target.GetProperty('productName'),NEWLINE 'buildConfigurationList': xccl,NEWLINE },NEWLINE parent=self.project)NEWLINE run_target.AddDependency(xcode_target)NEWLINENEWLINE command = target['run_as']NEWLINE script = ''NEWLINE if command.get('working_directory'):NEWLINE script = script + 'cd "%s"\n' % \NEWLINE gyp.xcodeproj_file.ConvertVariablesToShellSyntax(NEWLINE command.get('working_directory'))NEWLINENEWLINE if command.get('environment'):NEWLINE script = script + "\n".join(NEWLINE ['export %s="%s"' %NEWLINE (key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax(val))NEWLINE for (key, val) in command.get('environment').items()]) + "\n"NEWLINENEWLINE # Some test end up using sockets, files on disk, etc. and can getNEWLINE # confused if more then one test runs at a time. The generatorNEWLINE # flag 'xcode_serialize_all_test_runs' controls the forcing of allNEWLINE # tests serially. It defaults to True. To get serial runs thisNEWLINE # little bit of python does the same as the linux flock utility toNEWLINE # make sure only one runs at a time.NEWLINE command_prefix = ''NEWLINE if serialize_all_tests:NEWLINE command_prefix = \NEWLINE"""python -c "import fcntl, subprocess, sysNEWLINEfile = open('$TMPDIR/GYP_serialize_test_runs', 'a')NEWLINEfcntl.flock(file.fileno(), fcntl.LOCK_EX)NEWLINEsys.exit(subprocess.call(sys.argv[1:]))" """NEWLINENEWLINE # If we were unable to exec for some reason, we want to exitNEWLINE # with an error, and fixup variable references to be shellNEWLINE # syntax instead of xcode syntax.NEWLINE script = script + 'exec ' + command_prefix + '%s\nexit 1\n' % \NEWLINE gyp.xcodeproj_file.ConvertVariablesToShellSyntax(NEWLINE gyp.common.EncodePOSIXShellList(command.get('action')))NEWLINENEWLINE ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({NEWLINE 'shellScript': script,NEWLINE 'showEnvVarsInLog': 0,NEWLINE })NEWLINE run_target.AppendProperty('buildPhases', ssbp)NEWLINENEWLINE # Add the run target to the project file.NEWLINE targets.append(run_target)NEWLINE run_test_targets.append(run_target)NEWLINE xcode_target.test_runner = run_targetNEWLINENEWLINENEWLINE # Make sure that the list of targets being replaced is the same length asNEWLINE # the one replacing it, but allow for the added test runner targets.NEWLINE assert len(self.project._properties['targets']) == \NEWLINE len(ordinary_targets) + len(support_targets)NEWLINENEWLINE self.project._properties['targets'] = targetsNEWLINENEWLINE # Get rid of unnecessary levels of depth in groups like the Source group.NEWLINE self.project.RootGroupsTakeOverOnlyChildren(True)NEWLINENEWLINE # Sort the groups nicely. Do this after sorting the targets, because theNEWLINE # Products group is sorted based on the order of the targets.NEWLINE self.project.SortGroups()NEWLINENEWLINE # Create an "All" target if there's more than one target in this projectNEWLINE # file and the project didn't define its own "All" target. Put a generatedNEWLINE # "All" target first so that people opening up the project for the firstNEWLINE # time will build everything by default.NEWLINE if len(targets_for_all) > 1 and not has_custom_all:NEWLINE xccl = CreateXCConfigurationList(configurations)NEWLINE all_target = gyp.xcodeproj_file.PBXAggregateTarget(NEWLINE {NEWLINE 'buildConfigurationList': xccl,NEWLINE 'name': 'All',NEWLINE },NEWLINE parent=self.project)NEWLINENEWLINE for target in targets_for_all:NEWLINE all_target.AddDependency(target)NEWLINENEWLINE # TODO(mark): This is evil because it relies on internal knowledge ofNEWLINE # PBXProject._properties. It's important to get the "All" target first,NEWLINE # though.NEWLINE self.project._properties['targets'].insert(0, all_target)NEWLINENEWLINE # The same, but for run_test_targets.NEWLINE if len(run_test_targets) > 1:NEWLINE xccl = CreateXCConfigurationList(configurations)NEWLINE run_all_tests_target = gyp.xcodeproj_file.PBXAggregateTarget(NEWLINE {NEWLINE 'buildConfigurationList': xccl,NEWLINE 'name': 'Run All Tests',NEWLINE },NEWLINE parent=self.project)NEWLINE for run_test_target in run_test_targets:NEWLINE run_all_tests_target.AddDependency(run_test_target)NEWLINENEWLINE # Insert after the "All" target, which must exist if there is more thanNEWLINE # one run_test_target.NEWLINE self.project._properties['targets'].insert(1, run_all_tests_target)NEWLINENEWLINE def Finalize2(self, xcode_targets, xcode_target_to_target_dict):NEWLINE # Finalize2 needs to happen in a separate step because the process ofNEWLINE # updating references to other projects depends on the ordering of targetsNEWLINE # within remote project files. Finalize1 is responsible for sorting duty,NEWLINE # and once all project files are sorted, Finalize2 can come in and updateNEWLINE # these references.NEWLINENEWLINE # To support making a "test runner" target that will run all the testsNEWLINE # that are direct dependents of any given target, we look forNEWLINE # xcode_create_dependents_test_runner being set on an Aggregate target,NEWLINE # and generate a second target that will run the tests runners found underNEWLINE # the marked target.NEWLINE for bf_tgt in self.build_file_dict['targets']:NEWLINE if int(bf_tgt.get('xcode_create_dependents_test_runner', 0)):NEWLINE tgt_name = bf_tgt['target_name']NEWLINE toolset = bf_tgt['toolset']NEWLINE qualified_target = gyp.common.QualifiedTarget(self.gyp_path,NEWLINE tgt_name, toolset)NEWLINE xcode_target = xcode_targets[qualified_target]NEWLINE if isinstance(xcode_target, gyp.xcodeproj_file.PBXAggregateTarget):NEWLINE # Collect all the run test targets.NEWLINE all_run_tests = []NEWLINE pbxtds = xcode_target.GetProperty('dependencies')NEWLINE for pbxtd in pbxtds:NEWLINE pbxcip = pbxtd.GetProperty('targetProxy')NEWLINE dependency_xct = pbxcip.GetProperty('remoteGlobalIDString')NEWLINE if hasattr(dependency_xct, 'test_runner'):NEWLINE all_run_tests.append(dependency_xct.test_runner)NEWLINENEWLINE # Directly depend on all the runners as they depend on the targetNEWLINE # that builds them.NEWLINE if len(all_run_tests) > 0:NEWLINE run_all_target = gyp.xcodeproj_file.PBXAggregateTarget({NEWLINE 'name': 'Run %s Tests' % tgt_name,NEWLINE 'productName': tgt_name,NEWLINE },NEWLINE parent=self.project)NEWLINE for run_test_target in all_run_tests:NEWLINE run_all_target.AddDependency(run_test_target)NEWLINENEWLINE # Insert the test runner after the related target.NEWLINE idx = self.project._properties['targets'].index(xcode_target)NEWLINE self.project._properties['targets'].insert(idx + 1, run_all_target)NEWLINENEWLINE # Update all references to other projects, to make sure that the lists ofNEWLINE # remote products are complete. Otherwise, Xcode will fill them in whenNEWLINE # it opens the project file, which will result in unnecessary diffs.NEWLINE # TODO(mark): This is evil because it relies on internal knowledge ofNEWLINE # PBXProject._other_pbxprojects.NEWLINE for other_pbxproject in self.project._other_pbxprojects.keys():NEWLINE self.project.AddOrGetProjectReference(other_pbxproject)NEWLINENEWLINE self.project.SortRemoteProductReferences()NEWLINENEWLINE # Give everything an ID.NEWLINE self.project_file.ComputeIDs()NEWLINENEWLINE # Make sure that no two objects in the project file have the same ID. IfNEWLINE # multiple objects wind up with the same ID, upon loading the file, XcodeNEWLINE # will only recognize one object (the last one in the file?) and theNEWLINE # results are unpredictable.NEWLINE self.project_file.EnsureNoIDCollisions()NEWLINENEWLINE def Write(self):NEWLINE # Write the project file to a temporary location first. Xcode watches forNEWLINE # changes to the project file and presents a UI sheet offering to reloadNEWLINE # the project when it does change. However, in some cases, especially whenNEWLINE # multiple projects are open or when Xcode is busy, things don't work soNEWLINE # seamlessly. Sometimes, Xcode is able to detect that a project file hasNEWLINE # changed but can't unload it because something else is referencing it.NEWLINE # To mitigate this problem, and to avoid even having Xcode present the UINEWLINE # sheet when an open project is rewritten for inconsequential changes, theNEWLINE # project file is written to a temporary file in the xcodeproj directoryNEWLINE # first. The new temporary file is then compared to the existing projectNEWLINE # file, if any. If they differ, the new file replaces the old; otherwise,NEWLINE # the new project file is simply deleted. Xcode properly detects a fileNEWLINE # being renamed over an open project file as a change and so it remainsNEWLINE # able to present the "project file changed" sheet under this system.NEWLINE # Writing to a temporary file first also avoids the possible problem ofNEWLINE # Xcode rereading an incomplete project file.NEWLINE (output_fd, new_pbxproj_path) = \NEWLINE tempfile.mkstemp(suffix='.tmp', prefix='project.pbxproj.gyp.',NEWLINE dir=self.path)NEWLINENEWLINE try:NEWLINE output_file = os.fdopen(output_fd, 'wb')NEWLINENEWLINE self.project_file.Print(output_file)NEWLINE output_file.close()NEWLINENEWLINE pbxproj_path = os.path.join(self.path, 'project.pbxproj')NEWLINENEWLINE same = FalseNEWLINE try:NEWLINE same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False)NEWLINE except OSError as e:NEWLINE if e.errno != errno.ENOENT:NEWLINE raiseNEWLINENEWLINE if same:NEWLINE # The new file is identical to the old one, just get rid of the newNEWLINE # one.NEWLINE os.unlink(new_pbxproj_path)NEWLINE else:NEWLINE # The new file is different from the old one, or there is no old one.NEWLINE # Rename the new file to the permanent name.NEWLINE #NEWLINE # tempfile.mkstemp uses an overly restrictive mode, resulting in aNEWLINE # file that can only be read by the owner, regardless of the umask.NEWLINE # There's no reason to not respect the umask here, which means thatNEWLINE # an extra hoop is required to fetch it and reset the new file's mode.NEWLINE #NEWLINE # No way to get the umask without setting a new one? Set a safe oneNEWLINE # and then set it back to the old value.NEWLINE umask = os.umask(0o77)NEWLINE os.umask(umask)NEWLINENEWLINE os.chmod(new_pbxproj_path, 0o666 & ~umask)NEWLINE os.rename(new_pbxproj_path, pbxproj_path)NEWLINENEWLINE except Exception:NEWLINE # Don't leave turds behind. In fact, if this code was responsible forNEWLINE # creating the xcodeproj directory, get rid of that too.NEWLINE os.unlink(new_pbxproj_path)NEWLINE if self.created_dir:NEWLINE shutil.rmtree(self.path, True)NEWLINE raiseNEWLINENEWLINENEWLINEdef AddSourceToTarget(source, type, pbxp, xct):NEWLINE # TODO(mark): Perhaps source_extensions and library_extensions can be made aNEWLINE # little bit fancier.NEWLINE source_extensions = ['c', 'cc', 'cpp', 'cxx', 'm', 'mm', 's', 'swift']NEWLINENEWLINE # .o is conceptually more of a "source" than a "library," but Xcode thinksNEWLINE # of "sources" as things to compile and "libraries" (or "frameworks") asNEWLINE # things to link with. Adding an object file to an Xcode target's frameworksNEWLINE # phase works properly.NEWLINE library_extensions = ['a', 'dylib', 'framework', 'o']NEWLINENEWLINE basename = posixpath.basename(source)NEWLINE (root, ext) = posixpath.splitext(basename)NEWLINE if ext:NEWLINE ext = ext[1:].lower()NEWLINENEWLINE if ext in source_extensions and type != 'none':NEWLINE xct.SourcesPhase().AddFile(source)NEWLINE elif ext in library_extensions and type != 'none':NEWLINE xct.FrameworksPhase().AddFile(source)NEWLINE else:NEWLINE # Files that aren't added to a sources or frameworks build phase can stillNEWLINE # go into the project file, just not as part of a build phase.NEWLINE pbxp.AddOrGetFileInRootGroup(source)NEWLINENEWLINENEWLINEdef AddResourceToTarget(resource, pbxp, xct):NEWLINE # TODO(mark): Combine with AddSourceToTarget above? Or just inline this callNEWLINE # where it's used.NEWLINE xct.ResourcesPhase().AddFile(resource)NEWLINENEWLINENEWLINEdef AddHeaderToTarget(header, pbxp, xct, is_public):NEWLINE # TODO(mark): Combine with AddSourceToTarget above? Or just inline this callNEWLINE # where it's used.NEWLINE settings = '{ATTRIBUTES = (%s, ); }' % ('Private', 'Public')[is_public]NEWLINE xct.HeadersPhase().AddFile(header, settings)NEWLINENEWLINENEWLINE_xcode_variable_re = re.compile(r'(\$\((.*?)\))')NEWLINEdef ExpandXcodeVariables(string, expansions):NEWLINE """Expands Xcode-style $(VARIABLES) in string per the expansions dict.NEWLINENEWLINE In some rare cases, it is appropriate to expand Xcode variables when aNEWLINE project file is generated. For any substring $(VAR) in string, if VAR is aNEWLINE key in the expansions dict, $(VAR) will be replaced with expansions[VAR].NEWLINE Any $(VAR) substring in string for which VAR is not a key in the expansionsNEWLINE dict will remain in the returned string.NEWLINE """NEWLINENEWLINE matches = _xcode_variable_re.findall(string)NEWLINE if matches is None:NEWLINE return stringNEWLINENEWLINE matches.reverse()NEWLINE for match in matches:NEWLINE (to_replace, variable) = matchNEWLINE if not variable in expansions:NEWLINE continueNEWLINENEWLINE replacement = expansions[variable]NEWLINE string = re.sub(re.escape(to_replace), replacement, string)NEWLINENEWLINE return stringNEWLINENEWLINENEWLINE_xcode_define_re = re.compile(r'([\\\"\' ])')NEWLINEdef EscapeXcodeDefine(s):NEWLINE """We must escape the defines that we give to XCode so that it knows not toNEWLINE split on spaces and to respect backslash and quote literals. However, weNEWLINE must not quote the define, or Xcode will incorrectly intepret variablesNEWLINE especially $(inherited)."""NEWLINE return re.sub(_xcode_define_re, r'\\\1', s)NEWLINENEWLINENEWLINEdef PerformBuild(data, configurations, params):NEWLINE options = params['options']NEWLINENEWLINE for build_file, build_file_dict in data.items():NEWLINE (build_file_root, build_file_ext) = os.path.splitext(build_file)NEWLINE if build_file_ext != '.gyp':NEWLINE continueNEWLINE xcodeproj_path = build_file_root + options.suffix + '.xcodeproj'NEWLINE if options.generator_output:NEWLINE xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path)NEWLINENEWLINE for config in configurations:NEWLINE arguments = ['xcodebuild', '-project', xcodeproj_path]NEWLINE arguments += ['-configuration', config]NEWLINE print("Building [%s]: %s" % (config, arguments))NEWLINE subprocess.check_call(arguments)NEWLINENEWLINENEWLINEdef CalculateGeneratorInputInfo(params):NEWLINE toplevel = params['options'].toplevel_dirNEWLINE if params.get('flavor') == 'ninja':NEWLINE generator_dir = os.path.relpath(params['options'].generator_output or '.')NEWLINE output_dir = params.get('generator_flags', {}).get('output_dir', 'out')NEWLINE output_dir = os.path.normpath(os.path.join(generator_dir, output_dir))NEWLINE qualified_out_dir = os.path.normpath(os.path.join(NEWLINE toplevel, output_dir, 'gypfiles-xcode-ninja'))NEWLINE else:NEWLINE output_dir = os.path.normpath(os.path.join(toplevel, 'xcodebuild'))NEWLINE qualified_out_dir = os.path.normpath(os.path.join(NEWLINE toplevel, output_dir, 'gypfiles'))NEWLINENEWLINE global generator_filelist_pathsNEWLINE generator_filelist_paths = {NEWLINE 'toplevel': toplevel,NEWLINE 'qualified_out_dir': qualified_out_dir,NEWLINE }NEWLINENEWLINENEWLINEdef GenerateOutput(target_list, target_dicts, data, params):NEWLINE # Optionally configure each spec to use ninja as the external builder.NEWLINE ninja_wrapper = params.get('flavor') == 'ninja'NEWLINE if ninja_wrapper:NEWLINE (target_list, target_dicts, data) = \NEWLINE gyp.xcode_ninja.CreateWrapper(target_list, target_dicts, data, params)NEWLINENEWLINE options = params['options']NEWLINE generator_flags = params.get('generator_flags', {})NEWLINE parallel_builds = generator_flags.get('xcode_parallel_builds', True)NEWLINE serialize_all_tests = \NEWLINE generator_flags.get('xcode_serialize_all_test_runs', True)NEWLINE upgrade_check_project_version = \NEWLINE generator_flags.get('xcode_upgrade_check_project_version', None)NEWLINENEWLINE # Format upgrade_check_project_version with leading zeros as needed.NEWLINE if upgrade_check_project_version:NEWLINE upgrade_check_project_version = str(upgrade_check_project_version)NEWLINE while len(upgrade_check_project_version) < 4:NEWLINE upgrade_check_project_version = '0' + upgrade_check_project_versionNEWLINENEWLINE skip_excluded_files = \NEWLINE not generator_flags.get('xcode_list_excluded_files', True)NEWLINE xcode_projects = {}NEWLINE for build_file, build_file_dict in data.items():NEWLINE (build_file_root, build_file_ext) = os.path.splitext(build_file)NEWLINE if build_file_ext != '.gyp':NEWLINE continueNEWLINE xcodeproj_path = build_file_root + options.suffix + '.xcodeproj'NEWLINE if options.generator_output:NEWLINE xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path)NEWLINE xcp = XcodeProject(build_file, xcodeproj_path, build_file_dict)NEWLINE xcode_projects[build_file] = xcpNEWLINE pbxp = xcp.projectNEWLINENEWLINE # Set project-level attributes from multiple optionsNEWLINE project_attributes = {}NEWLINE if parallel_builds:NEWLINE project_attributes['BuildIndependentTargetsInParallel'] = 'YES'NEWLINE if upgrade_check_project_version:NEWLINE project_attributes['LastUpgradeCheck'] = upgrade_check_project_versionNEWLINE project_attributes['LastTestingUpgradeCheck'] = \NEWLINE upgrade_check_project_versionNEWLINE project_attributes['LastSwiftUpdateCheck'] = \NEWLINE upgrade_check_project_versionNEWLINE pbxp.SetProperty('attributes', project_attributes)NEWLINENEWLINE # Add gyp/gypi files to projectNEWLINE if not generator_flags.get('standalone'):NEWLINE main_group = pbxp.GetProperty('mainGroup')NEWLINE build_group = gyp.xcodeproj_file.PBXGroup({'name': 'Build'})NEWLINE main_group.AppendChild(build_group)NEWLINE for included_file in build_file_dict['included_files']:NEWLINE build_group.AddOrGetFileByPath(included_file, False)NEWLINENEWLINE xcode_targets = {}NEWLINE xcode_target_to_target_dict = {}NEWLINE for qualified_target in target_list:NEWLINE [build_file, target_name, toolset] = \NEWLINE gyp.common.ParseQualifiedTarget(qualified_target)NEWLINENEWLINE spec = target_dicts[qualified_target]NEWLINE if spec['toolset'] != 'target':NEWLINE raise Exception(NEWLINE 'Multiple toolsets not supported in xcode build (target %s)' %NEWLINE qualified_target)NEWLINE configuration_names = [spec['default_configuration']]NEWLINE for configuration_name in sorted(spec['configurations'].keys()):NEWLINE if configuration_name not in configuration_names:NEWLINE configuration_names.append(configuration_name)NEWLINE xcp = xcode_projects[build_file]NEWLINE pbxp = xcp.projectNEWLINENEWLINE # Set up the configurations for the target according to the list of namesNEWLINE # supplied.NEWLINE xccl = CreateXCConfigurationList(configuration_names)NEWLINENEWLINE # Create an XCTarget subclass object for the target. The type withNEWLINE # "+bundle" appended will be used if the target has "mac_bundle" set.NEWLINE # loadable_modules not in a mac_bundle are mapped toNEWLINE # com.googlecode.gyp.xcode.bundle, a pseudo-type that xcode.py interpretsNEWLINE # to create a single-file mh_bundle.NEWLINE _types = {NEWLINE 'executable': 'com.apple.product-type.tool',NEWLINE 'loadable_module': 'com.googlecode.gyp.xcode.bundle',NEWLINE 'shared_library': 'com.apple.product-type.library.dynamic',NEWLINE 'static_library': 'com.apple.product-type.library.static',NEWLINE 'mac_kernel_extension': 'com.apple.product-type.kernel-extension',NEWLINE 'executable+bundle': 'com.apple.product-type.application',NEWLINE 'loadable_module+bundle': 'com.apple.product-type.bundle',NEWLINE 'loadable_module+xctest': 'com.apple.product-type.bundle.unit-test',NEWLINE 'shared_library+bundle': 'com.apple.product-type.framework',NEWLINE 'executable+extension+bundle': 'com.apple.product-type.app-extension',NEWLINE 'executable+watch+extension+bundle':NEWLINE 'com.apple.product-type.watchkit-extension',NEWLINE 'executable+watch+bundle':NEWLINE 'com.apple.product-type.application.watchapp',NEWLINE 'mac_kernel_extension+bundle': 'com.apple.product-type.kernel-extension',NEWLINE }NEWLINENEWLINE target_properties = {NEWLINE 'buildConfigurationList': xccl,NEWLINE 'name': target_name,NEWLINE }NEWLINENEWLINE type = spec['type']NEWLINE is_xctest = int(spec.get('mac_xctest_bundle', 0))NEWLINE is_bundle = int(spec.get('mac_bundle', 0)) or is_xctestNEWLINE is_app_extension = int(spec.get('ios_app_extension', 0))NEWLINE is_watchkit_extension = int(spec.get('ios_watchkit_extension', 0))NEWLINE is_watch_app = int(spec.get('ios_watch_app', 0))NEWLINE if type != 'none':NEWLINE type_bundle_key = typeNEWLINE if is_xctest:NEWLINE type_bundle_key += '+xctest'NEWLINE assert type == 'loadable_module', (NEWLINE 'mac_xctest_bundle targets must have type loadable_module 'NEWLINE '(target %s)' % target_name)NEWLINE elif is_app_extension:NEWLINE assert is_bundle, ('ios_app_extension flag requires mac_bundle 'NEWLINE '(target %s)' % target_name)NEWLINE type_bundle_key += '+extension+bundle'NEWLINE elif is_watchkit_extension:NEWLINE assert is_bundle, ('ios_watchkit_extension flag requires mac_bundle 'NEWLINE '(target %s)' % target_name)NEWLINE type_bundle_key += '+watch+extension+bundle'NEWLINE elif is_watch_app:NEWLINE assert is_bundle, ('ios_watch_app flag requires mac_bundle 'NEWLINE '(target %s)' % target_name)NEWLINE type_bundle_key += '+watch+bundle'NEWLINE elif is_bundle:NEWLINE type_bundle_key += '+bundle'NEWLINENEWLINE xctarget_type = gyp.xcodeproj_file.PBXNativeTargetNEWLINE try:NEWLINE target_properties['productType'] = _types[type_bundle_key]NEWLINE except KeyError as e:NEWLINE gyp.common.ExceptionAppend(e, "-- unknown product type while "NEWLINE "writing target %s" % target_name)NEWLINE raiseNEWLINE else:NEWLINE xctarget_type = gyp.xcodeproj_file.PBXAggregateTargetNEWLINE assert not is_bundle, (NEWLINE 'mac_bundle targets cannot have type none (target "%s")' %NEWLINE target_name)NEWLINE assert not is_xctest, (NEWLINE 'mac_xctest_bundle targets cannot have type none (target "%s")' %NEWLINE target_name)NEWLINENEWLINE target_product_name = spec.get('product_name')NEWLINE if target_product_name is not None:NEWLINE target_properties['productName'] = target_product_nameNEWLINENEWLINE xct = xctarget_type(target_properties, parent=pbxp,NEWLINE force_outdir=spec.get('product_dir'),NEWLINE force_prefix=spec.get('product_prefix'),NEWLINE force_extension=spec.get('product_extension'))NEWLINE pbxp.AppendProperty('targets', xct)NEWLINE xcode_targets[qualified_target] = xctNEWLINE xcode_target_to_target_dict[xct] = specNEWLINENEWLINE spec_actions = spec.get('actions', [])NEWLINE spec_rules = spec.get('rules', [])NEWLINENEWLINE # Xcode has some "issues" with checking dependencies for the "CompileNEWLINE # sources" step with any source files/headers generated by actions/rules.NEWLINE # To work around this, if a target is building anything directly (notNEWLINE # type "none"), then a second target is used to run the GYP actions/rulesNEWLINE # and is made a dependency of this target. This way the work is doneNEWLINE # before the dependency checks for what should be recompiled.NEWLINE support_xct = NoneNEWLINE # The Xcode "issues" don't affect xcode-ninja builds, since the dependencyNEWLINE # logic all happens in ninja. Don't bother creating the extra targets inNEWLINE # that case.NEWLINE if type != 'none' and (spec_actions or spec_rules) and not ninja_wrapper:NEWLINE support_xccl = CreateXCConfigurationList(configuration_names)NEWLINE support_target_suffix = generator_flags.get(NEWLINE 'support_target_suffix', ' Support')NEWLINE support_target_properties = {NEWLINE 'buildConfigurationList': support_xccl,NEWLINE 'name': target_name + support_target_suffix,NEWLINE }NEWLINE if target_product_name:NEWLINE support_target_properties['productName'] = \NEWLINE target_product_name + ' Support'NEWLINE support_xct = \NEWLINE gyp.xcodeproj_file.PBXAggregateTarget(support_target_properties,NEWLINE parent=pbxp)NEWLINE pbxp.AppendProperty('targets', support_xct)NEWLINE xct.AddDependency(support_xct)NEWLINE # Hang the support target off the main target so it can be tested/foundNEWLINE # by the generator during Finalize.NEWLINE xct.support_target = support_xctNEWLINENEWLINE prebuild_index = 0NEWLINENEWLINE # Add custom shell script phases for "actions" sections.NEWLINE for action in spec_actions:NEWLINE # There's no need to write anything into the script to ensure that theNEWLINE # output directories already exist, because Xcode will look at theNEWLINE # declared outputs and automatically ensure that they exist for us.NEWLINENEWLINE # Do we have a message to print when this action runs?NEWLINE message = action.get('message')NEWLINE if message:NEWLINE message = 'echo note: ' + gyp.common.EncodePOSIXShellArgument(message)NEWLINE else:NEWLINE message = ''NEWLINENEWLINE # Turn the list into a string that can be passed to a shell.NEWLINE action_string = gyp.common.EncodePOSIXShellList(action['action'])NEWLINENEWLINE # Convert Xcode-type variable references to sh-compatible environmentNEWLINE # variable references.NEWLINE message_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(message)NEWLINE action_string_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(NEWLINE action_string)NEWLINENEWLINE script = ''NEWLINE # Include the optional messageNEWLINE if message_sh:NEWLINE script += message_sh + '\n'NEWLINE # Be sure the script runs in exec, and that if exec fails, the scriptNEWLINE # exits signalling an error.NEWLINE script += 'exec ' + action_string_sh + '\nexit 1\n'NEWLINE ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({NEWLINE 'inputPaths': action['inputs'],NEWLINE 'name': 'Action "' + action['action_name'] + '"',NEWLINE 'outputPaths': action['outputs'],NEWLINE 'shellScript': script,NEWLINE 'showEnvVarsInLog': 0,NEWLINE })NEWLINENEWLINE if support_xct:NEWLINE support_xct.AppendProperty('buildPhases', ssbp)NEWLINE else:NEWLINE # TODO(mark): this assumes too much knowledge of the internals ofNEWLINE # xcodeproj_file; some of these smarts should move into xcodeproj_fileNEWLINE # itself.NEWLINE xct._properties['buildPhases'].insert(prebuild_index, ssbp)NEWLINE prebuild_index = prebuild_index + 1NEWLINENEWLINE # TODO(mark): Should verify that at most one of these is specified.NEWLINE if int(action.get('process_outputs_as_sources', False)):NEWLINE for output in action['outputs']:NEWLINE AddSourceToTarget(output, type, pbxp, xct)NEWLINENEWLINE if int(action.get('process_outputs_as_mac_bundle_resources', False)):NEWLINE for output in action['outputs']:NEWLINE AddResourceToTarget(output, pbxp, xct)NEWLINENEWLINE # tgt_mac_bundle_resources holds the list of bundle resources soNEWLINE # the rule processing can check against it.NEWLINE if is_bundle:NEWLINE tgt_mac_bundle_resources = spec.get('mac_bundle_resources', [])NEWLINE else:NEWLINE tgt_mac_bundle_resources = []NEWLINENEWLINE # Add custom shell script phases driving "make" for "rules" sections.NEWLINE #NEWLINE # Xcode's built-in rule support is almost powerful enough to use directly,NEWLINE # but there are a few significant deficiencies that render them unusable.NEWLINE # There are workarounds for some of its inadequacies, but in aggregate,NEWLINE # the workarounds added complexity to the generator, and some workaroundsNEWLINE # actually require input files to be crafted more carefully than I'd like.NEWLINE # Consequently, until Xcode rules are made more capable, "rules" inputNEWLINE # sections will be handled in Xcode output by shell script build phasesNEWLINE # performed prior to the compilation phase.NEWLINE #NEWLINE # The following problems with Xcode rules were found. The numbers areNEWLINE # Apple radar IDs. I hope that these shortcomings are addressed, I reallyNEWLINE # liked having the rules handled directly in Xcode during the period thatNEWLINE # I was prototyping this.NEWLINE #NEWLINE # 6588600 Xcode compiles custom script rule outputs too soon, compilationNEWLINE # fails. This occurs when rule outputs from distinct inputs areNEWLINE # interdependent. The only workaround is to put rules and theirNEWLINE # inputs in a separate target from the one that compiles the ruleNEWLINE # outputs. This requires input file cooperation and it means thatNEWLINE # process_outputs_as_sources is unusable.NEWLINE # 6584932 Need to declare that custom rule outputs should be excluded fromNEWLINE # compilation. A possible workaround is to lie to Xcode about aNEWLINE # rule's output, giving it a dummy file it doesn't know how toNEWLINE # compile. The rule action script would need to touch the dummy.NEWLINE # 6584839 I need a way to declare additional inputs to a custom rule.NEWLINE # A possible workaround is a shell script phase prior toNEWLINE # compilation that touches a rule's primary input files if anyNEWLINE # would-be additional inputs are newer than the output. ModifyingNEWLINE # the source tree - even just modification times - feels dirty.NEWLINE # 6564240 Xcode "custom script" build rules always dump all environmentNEWLINE # variables. This is a low-prioroty problem and is not aNEWLINE # show-stopper.NEWLINE rules_by_ext = {}NEWLINE for rule in spec_rules:NEWLINE rules_by_ext[rule['extension']] = ruleNEWLINENEWLINE # First, some definitions:NEWLINE #NEWLINE # A "rule source" is a file that was listed in a target's "sources"NEWLINE # list and will have a rule applied to it on the basis of matching theNEWLINE # rule's "extensions" attribute. Rule sources are direct inputs toNEWLINE # rules.NEWLINE #NEWLINE # Rule definitions may specify additional inputs in their "inputs"NEWLINE # attribute. These additional inputs are used for dependency trackingNEWLINE # purposes.NEWLINE #NEWLINE # A "concrete output" is a rule output with input-dependent variablesNEWLINE # resolved. For example, given a rule with:NEWLINE # 'extension': 'ext', 'outputs': ['$(INPUT_FILE_BASE).cc'],NEWLINE # if the target's "sources" list contained "one.ext" and "two.ext",NEWLINE # the "concrete output" for rule input "two.ext" would be "two.cc". IfNEWLINE # a rule specifies multiple outputs, each input file that the rule isNEWLINE # applied to will have the same number of concrete outputs.NEWLINE #NEWLINE # If any concrete outputs are outdated or missing relative to theirNEWLINE # corresponding rule_source or to any specified additional input, theNEWLINE # rule action must be performed to generate the concrete outputs.NEWLINENEWLINE # concrete_outputs_by_rule_source will have an item at the same indexNEWLINE # as the rule['rule_sources'] that it corresponds to. Each item is aNEWLINE # list of all of the concrete outputs for the rule_source.NEWLINE concrete_outputs_by_rule_source = []NEWLINENEWLINE # concrete_outputs_all is a flat list of all concrete outputs that thisNEWLINE # rule is able to produce, given the known set of input filesNEWLINE # (rule_sources) that apply to it.NEWLINE concrete_outputs_all = []NEWLINENEWLINE # messages & actions are keyed by the same indices as rule['rule_sources']NEWLINE # and concrete_outputs_by_rule_source. They contain the message andNEWLINE # action to perform after resolving input-dependent variables. TheNEWLINE # message is optional, in which case None is stored for each rule source.NEWLINE messages = []NEWLINE actions = []NEWLINENEWLINE for rule_source in rule.get('rule_sources', []):NEWLINE rule_source_dirname, rule_source_basename = \NEWLINE posixpath.split(rule_source)NEWLINE (rule_source_root, rule_source_ext) = \NEWLINE posixpath.splitext(rule_source_basename)NEWLINENEWLINE # These are the same variable names that Xcode uses for its own nativeNEWLINE # rule support. Because Xcode's rule engine is not being used, theyNEWLINE # need to be expanded as they are written to the makefile.NEWLINE rule_input_dict = {NEWLINE 'INPUT_FILE_BASE': rule_source_root,NEWLINE 'INPUT_FILE_SUFFIX': rule_source_ext,NEWLINE 'INPUT_FILE_NAME': rule_source_basename,NEWLINE 'INPUT_FILE_PATH': rule_source,NEWLINE 'INPUT_FILE_DIRNAME': rule_source_dirname,NEWLINE }NEWLINENEWLINE concrete_outputs_for_this_rule_source = []NEWLINE for output in rule.get('outputs', []):NEWLINE # Fortunately, Xcode and make both use $(VAR) format for theirNEWLINE # variables, so the expansion is the only transformation necessary.NEWLINE # Any remaning $(VAR)-type variables in the string can be givenNEWLINE # directly to make, which will pick up the correct settings fromNEWLINE # what Xcode puts into the environment.NEWLINE concrete_output = ExpandXcodeVariables(output, rule_input_dict)NEWLINE concrete_outputs_for_this_rule_source.append(concrete_output)NEWLINENEWLINE # Add all concrete outputs to the project.NEWLINE pbxp.AddOrGetFileInRootGroup(concrete_output)NEWLINENEWLINE concrete_outputs_by_rule_source.append( \NEWLINE concrete_outputs_for_this_rule_source)NEWLINE concrete_outputs_all.extend(concrete_outputs_for_this_rule_source)NEWLINENEWLINE # TODO(mark): Should verify that at most one of these is specified.NEWLINE if int(rule.get('process_outputs_as_sources', False)):NEWLINE for output in concrete_outputs_for_this_rule_source:NEWLINE AddSourceToTarget(output, type, pbxp, xct)NEWLINENEWLINE # If the file came from the mac_bundle_resources list or if the ruleNEWLINE # is marked to process outputs as bundle resource, do so.NEWLINE was_mac_bundle_resource = rule_source in tgt_mac_bundle_resourcesNEWLINE if was_mac_bundle_resource or \NEWLINE int(rule.get('process_outputs_as_mac_bundle_resources', False)):NEWLINE for output in concrete_outputs_for_this_rule_source:NEWLINE AddResourceToTarget(output, pbxp, xct)NEWLINENEWLINE # Do we have a message to print when this rule runs?NEWLINE message = rule.get('message')NEWLINE if message:NEWLINE message = gyp.common.EncodePOSIXShellArgument(message)NEWLINE message = ExpandXcodeVariables(message, rule_input_dict)NEWLINE messages.append(message)NEWLINENEWLINE # Turn the list into a string that can be passed to a shell.NEWLINE action_string = gyp.common.EncodePOSIXShellList(rule['action'])NEWLINENEWLINE action = ExpandXcodeVariables(action_string, rule_input_dict)NEWLINE actions.append(action)NEWLINENEWLINE if len(concrete_outputs_all) > 0:NEWLINE # TODO(mark): There's a possibility for collision here. ConsiderNEWLINE # target "t" rule "A_r" and target "t_A" rule "r".NEWLINE makefile_name = '%s.make' % re.sub(NEWLINE '[^a-zA-Z0-9_]', '_' , '%s_%s' % (target_name, rule['rule_name']))NEWLINE makefile_path = os.path.join(xcode_projects[build_file].path,NEWLINE makefile_name)NEWLINE # TODO(mark): try/close? Write to a temporary file and swap it onlyNEWLINE # if it's got changes?NEWLINE makefile = open(makefile_path, 'wb')NEWLINENEWLINE # make will build the first target in the makefile by default. ByNEWLINE # convention, it's called "all". List all (or at least one)NEWLINE # concrete output for each rule source as a prerequisite of the "all"NEWLINE # target.NEWLINE makefile.write('all: \\\n')NEWLINE for concrete_output_index in \NEWLINE range(0, len(concrete_outputs_by_rule_source)):NEWLINE # Only list the first (index [0]) concrete output of each inputNEWLINE # in the "all" target. Otherwise, a parallel make (-j > 1) wouldNEWLINE # attempt to process each input multiple times simultaneously.NEWLINE # Otherwise, "all" could just contain the entire list ofNEWLINE # concrete_outputs_all.NEWLINE concrete_output = \NEWLINE concrete_outputs_by_rule_source[concrete_output_index][0]NEWLINE if concrete_output_index == len(concrete_outputs_by_rule_source) - 1:NEWLINE eol = ''NEWLINE else:NEWLINE eol = ' \\'NEWLINE makefile.write(' %s%s\n' % (concrete_output, eol))NEWLINENEWLINE for (rule_source, concrete_outputs, message, action) in \NEWLINE zip(rule['rule_sources'], concrete_outputs_by_rule_source,NEWLINE messages, actions):NEWLINE makefile.write('\n')NEWLINENEWLINE # Add a rule that declares it can build each concrete output of aNEWLINE # rule source. Collect the names of the directories that areNEWLINE # required.NEWLINE concrete_output_dirs = []NEWLINE for concrete_output_index in range(0, len(concrete_outputs)):NEWLINE concrete_output = concrete_outputs[concrete_output_index]NEWLINE if concrete_output_index == 0:NEWLINE bol = ''NEWLINE else:NEWLINE bol = ' 'NEWLINE makefile.write('%s%s \\\n' % (bol, concrete_output))NEWLINENEWLINE concrete_output_dir = posixpath.dirname(concrete_output)NEWLINE if (concrete_output_dir andNEWLINE concrete_output_dir not in concrete_output_dirs):NEWLINE concrete_output_dirs.append(concrete_output_dir)NEWLINENEWLINE makefile.write(' : \\\n')NEWLINENEWLINE # The prerequisites for this rule are the rule source itself andNEWLINE # the set of additional rule inputs, if any.NEWLINE prerequisites = [rule_source]NEWLINE prerequisites.extend(rule.get('inputs', []))NEWLINE for prerequisite_index in range(0, len(prerequisites)):NEWLINE prerequisite = prerequisites[prerequisite_index]NEWLINE if prerequisite_index == len(prerequisites) - 1:NEWLINE eol = ''NEWLINE else:NEWLINE eol = ' \\'NEWLINE makefile.write(' %s%s\n' % (prerequisite, eol))NEWLINENEWLINE # Make sure that output directories exist before executing the ruleNEWLINE # action.NEWLINE if len(concrete_output_dirs) > 0:NEWLINE makefile.write('\t@mkdir -p "%s"\n' %NEWLINE '" "'.join(concrete_output_dirs))NEWLINENEWLINE # The rule message and action have already had the necessary variableNEWLINE # substitutions performed.NEWLINE if message:NEWLINE # Mark it with note: so Xcode picks it up in build output.NEWLINE makefile.write('\t@echo note: %s\n' % message)NEWLINE makefile.write('\t%s\n' % action)NEWLINENEWLINE makefile.close()NEWLINENEWLINE # It might be nice to ensure that needed output directories existNEWLINE # here rather than in each target in the Makefile, but that wouldn'tNEWLINE # work if there ever was a concrete output that had an input-dependentNEWLINE # variable anywhere other than in the leaf position.NEWLINENEWLINE # Don't declare any inputPaths or outputPaths. If they're present,NEWLINE # Xcode will provide a slight optimization by only running the scriptNEWLINE # phase if any output is missing or outdated relative to any input.NEWLINE # Unfortunately, it will also assume that all outputs are touched byNEWLINE # the script, and if the outputs serve as files in a compilationNEWLINE # phase, they will be unconditionally rebuilt. Since make might notNEWLINE # rebuild everything that could be declared here as an output, thisNEWLINE # extra compilation activity is unnecessary. With inputPaths andNEWLINE # outputPaths not supplied, make will always be called, but it knowsNEWLINE # enough to not do anything when everything is up-to-date.NEWLINENEWLINE # To help speed things up, pass -j COUNT to make so it does some workNEWLINE # in parallel. Don't use ncpus because Xcode will build ncpus targetsNEWLINE # in parallel and if each target happens to have a rules step, thereNEWLINE # would be ncpus^2 things going. With a machine that has 2 quad-coreNEWLINE # Xeons, a build can quickly run out of processes based onNEWLINE # scheduling/other tasks, and randomly failing builds are no good.NEWLINE script = \NEWLINE"""JOB_COUNT="$(/usr/sbin/sysctl -n hw.ncpu)"NEWLINEif [ "${JOB_COUNT}" -gt 4 ]; thenNEWLINE JOB_COUNT=4NEWLINEfiNEWLINEexec xcrun make -f "${PROJECT_FILE_PATH}/%s" -j "${JOB_COUNT}"NEWLINEexit 1NEWLINE""" % makefile_nameNEWLINE ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({NEWLINE 'name': 'Rule "' + rule['rule_name'] + '"',NEWLINE 'shellScript': script,NEWLINE 'showEnvVarsInLog': 0,NEWLINE })NEWLINENEWLINE if support_xct:NEWLINE support_xct.AppendProperty('buildPhases', ssbp)NEWLINE else:NEWLINE # TODO(mark): this assumes too much knowledge of the internals ofNEWLINE # xcodeproj_file; some of these smarts should move into xcodeproj_fileNEWLINE # itself.NEWLINE xct._properties['buildPhases'].insert(prebuild_index, ssbp)NEWLINE prebuild_index = prebuild_index + 1NEWLINENEWLINE # Extra rule inputs also go into the project file. Concrete outputs wereNEWLINE # already added when they were computed.NEWLINE groups = ['inputs', 'inputs_excluded']NEWLINE if skip_excluded_files:NEWLINE groups = [x for x in groups if not x.endswith('_excluded')]NEWLINE for group in groups:NEWLINE for item in rule.get(group, []):NEWLINE pbxp.AddOrGetFileInRootGroup(item)NEWLINENEWLINE # Add "sources".NEWLINE for source in spec.get('sources', []):NEWLINE (source_root, source_extension) = posixpath.splitext(source)NEWLINE if source_extension[1:] not in rules_by_ext:NEWLINE # AddSourceToTarget will add the file to a root group if it's notNEWLINE # already there.NEWLINE AddSourceToTarget(source, type, pbxp, xct)NEWLINE else:NEWLINE pbxp.AddOrGetFileInRootGroup(source)NEWLINENEWLINE # Add "mac_bundle_resources" and "mac_framework_private_headers" ifNEWLINE # it's a bundle of any type.NEWLINE if is_bundle:NEWLINE for resource in tgt_mac_bundle_resources:NEWLINE (resource_root, resource_extension) = posixpath.splitext(resource)NEWLINE if resource_extension[1:] not in rules_by_ext:NEWLINE AddResourceToTarget(resource, pbxp, xct)NEWLINE else:NEWLINE pbxp.AddOrGetFileInRootGroup(resource)NEWLINENEWLINE for header in spec.get('mac_framework_private_headers', []):NEWLINE AddHeaderToTarget(header, pbxp, xct, False)NEWLINENEWLINE # Add "mac_framework_headers". These can be valid for both frameworksNEWLINE # and static libraries.NEWLINE if is_bundle or type == 'static_library':NEWLINE for header in spec.get('mac_framework_headers', []):NEWLINE AddHeaderToTarget(header, pbxp, xct, True)NEWLINENEWLINE # Add "copies".NEWLINE pbxcp_dict = {}NEWLINE for copy_group in spec.get('copies', []):NEWLINE dest = copy_group['destination']NEWLINE if dest[0] not in ('/', '$'):NEWLINE # Relative paths are relative to $(SRCROOT).NEWLINE dest = '$(SRCROOT)/' + destNEWLINENEWLINE code_sign = int(copy_group.get('xcode_code_sign', 0))NEWLINE settings = (None, '{ATTRIBUTES = (CodeSignOnCopy, ); }')[code_sign]NEWLINENEWLINE # Coalesce multiple "copies" sections in the same target with the sameNEWLINE # "destination" property into the same PBXCopyFilesBuildPhase, otherwiseNEWLINE # they'll wind up with ID collisions.NEWLINE pbxcp = pbxcp_dict.get(dest, None)NEWLINE if pbxcp is None:NEWLINE pbxcp = gyp.xcodeproj_file.PBXCopyFilesBuildPhase({NEWLINE 'name': 'Copy to ' + copy_group['destination']NEWLINE },NEWLINE parent=xct)NEWLINE pbxcp.SetDestination(dest)NEWLINENEWLINE # TODO(mark): The usual comment about this knowing too much aboutNEWLINE # gyp.xcodeproj_file internals applies.NEWLINE xct._properties['buildPhases'].insert(prebuild_index, pbxcp)NEWLINENEWLINE pbxcp_dict[dest] = pbxcpNEWLINENEWLINE for file in copy_group['files']:NEWLINE pbxcp.AddFile(file, settings)NEWLINENEWLINE # Excluded files can also go into the project file.NEWLINE if not skip_excluded_files:NEWLINE for key in ['sources', 'mac_bundle_resources', 'mac_framework_headers',NEWLINE 'mac_framework_private_headers']:NEWLINE excluded_key = key + '_excluded'NEWLINE for item in spec.get(excluded_key, []):NEWLINE pbxp.AddOrGetFileInRootGroup(item)NEWLINENEWLINE # So can "inputs" and "outputs" sections of "actions" groups.NEWLINE groups = ['inputs', 'inputs_excluded', 'outputs', 'outputs_excluded']NEWLINE if skip_excluded_files:NEWLINE groups = [x for x in groups if not x.endswith('_excluded')]NEWLINE for action in spec.get('actions', []):NEWLINE for group in groups:NEWLINE for item in action.get(group, []):NEWLINE # Exclude anything in BUILT_PRODUCTS_DIR. They're products, notNEWLINE # sources.NEWLINE if not item.startswith('$(BUILT_PRODUCTS_DIR)/'):NEWLINE pbxp.AddOrGetFileInRootGroup(item)NEWLINENEWLINE for postbuild in spec.get('postbuilds', []):NEWLINE action_string_sh = gyp.common.EncodePOSIXShellList(postbuild['action'])NEWLINE script = 'exec ' + action_string_sh + '\nexit 1\n'NEWLINENEWLINE # Make the postbuild step depend on the output of ld or ar from thisNEWLINE # target. Apparently putting the script step after the link step isn'tNEWLINE # sufficient to ensure proper ordering in all cases. With an inputNEWLINE # declared but no outputs, the script step should run every time, asNEWLINE # desired.NEWLINE ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({NEWLINE 'inputPaths': ['$(BUILT_PRODUCTS_DIR)/$(EXECUTABLE_PATH)'],NEWLINE 'name': 'Postbuild "' + postbuild['postbuild_name'] + '"',NEWLINE 'shellScript': script,NEWLINE 'showEnvVarsInLog': 0,NEWLINE })NEWLINE xct.AppendProperty('buildPhases', ssbp)NEWLINENEWLINE # Add dependencies before libraries, because adding a dependency may implyNEWLINE # adding a library. It's preferable to keep dependencies listed firstNEWLINE # during a link phase so that they can override symbols that wouldNEWLINE # otherwise be provided by libraries, which will usually include systemNEWLINE # libraries. On some systems, ld is finicky and even requires theNEWLINE # libraries to be ordered in such a way that unresolved symbols inNEWLINE # earlier-listed libraries may only be resolved by later-listed libraries.NEWLINE # The Mac linker doesn't work that way, but other platforms do, and soNEWLINE # their linker invocations need to be constructed in this way. There'sNEWLINE # no compelling reason for Xcode's linker invocations to differ.NEWLINENEWLINE if 'dependencies' in spec:NEWLINE for dependency in spec['dependencies']:NEWLINE xct.AddDependency(xcode_targets[dependency])NEWLINE # The support project also gets the dependencies (in case they areNEWLINE # needed for the actions/rules to work).NEWLINE if support_xct:NEWLINE support_xct.AddDependency(xcode_targets[dependency])NEWLINENEWLINE if 'libraries' in spec:NEWLINE for library in spec['libraries']:NEWLINE xct.FrameworksPhase().AddFile(library)NEWLINE # Add the library's directory to LIBRARY_SEARCH_PATHS if necessary.NEWLINE # I wish Xcode handled this automatically.NEWLINE library_dir = posixpath.dirname(library)NEWLINE if library_dir not in xcode_standard_library_dirs and (NEWLINE not xct.HasBuildSetting(_library_search_paths_var) orNEWLINE library_dir not in xct.GetBuildSetting(_library_search_paths_var)):NEWLINE xct.AppendBuildSetting(_library_search_paths_var, library_dir)NEWLINENEWLINE for configuration_name in configuration_names:NEWLINE configuration = spec['configurations'][configuration_name]NEWLINE xcbc = xct.ConfigurationNamed(configuration_name)NEWLINE for include_dir in configuration.get('mac_framework_dirs', []):NEWLINE xcbc.AppendBuildSetting('FRAMEWORK_SEARCH_PATHS', include_dir)NEWLINE for include_dir in configuration.get('include_dirs', []):NEWLINE xcbc.AppendBuildSetting('HEADER_SEARCH_PATHS', include_dir)NEWLINE for library_dir in configuration.get('library_dirs', []):NEWLINE if library_dir not in xcode_standard_library_dirs and (NEWLINE not xcbc.HasBuildSetting(_library_search_paths_var) orNEWLINE library_dir not in xcbc.GetBuildSetting(_library_search_paths_var)):NEWLINE xcbc.AppendBuildSetting(_library_search_paths_var, library_dir)NEWLINENEWLINE if 'defines' in configuration:NEWLINE for define in configuration['defines']:NEWLINE set_define = EscapeXcodeDefine(define)NEWLINE xcbc.AppendBuildSetting('GCC_PREPROCESSOR_DEFINITIONS', set_define)NEWLINE if 'xcode_settings' in configuration:NEWLINE for xck, xcv in configuration['xcode_settings'].items():NEWLINE xcbc.SetBuildSetting(xck, xcv)NEWLINE if 'xcode_config_file' in configuration:NEWLINE config_ref = pbxp.AddOrGetFileInRootGroup(NEWLINE configuration['xcode_config_file'])NEWLINE xcbc.SetBaseConfiguration(config_ref)NEWLINENEWLINE build_files = []NEWLINE for build_file, build_file_dict in data.items():NEWLINE if build_file.endswith('.gyp'):NEWLINE build_files.append(build_file)NEWLINENEWLINE for build_file in build_files:NEWLINE xcode_projects[build_file].Finalize1(xcode_targets, serialize_all_tests)NEWLINENEWLINE for build_file in build_files:NEWLINE xcode_projects[build_file].Finalize2(xcode_targets,NEWLINE xcode_target_to_target_dict)NEWLINENEWLINE for build_file in build_files:NEWLINE xcode_projects[build_file].Write()NEWLINE |
import sysNEWLINEimport osNEWLINEimport filecmpNEWLINEimport importlibNEWLINEimport datetimeNEWLINEimport commonNEWLINENEWLINEpath = os.path.abspath('.')NEWLINEsys.path.append(path)NEWLINENEWLINEdomain = 'maaseuduntulevaisuus'NEWLINEurl = 'http://www.maaseuduntulevaisuus.fi/maatalous/eu-s%C3%A4%C3%A4st%C3%A4%C3%A4-suorista-tuista-1-37-prosenttia-kriisien-varalle-1.161757'NEWLINENEWLINEout = 'test/parser_out.txt'NEWLINEmodule = importlib.import_module( 'sites.' + domain )NEWLINEd = module.parse(url)NEWLINENEWLINEclass TestParser:NEWLINENEWLINE @classmethodNEWLINE def setup_class(cls):NEWLINE common.initialise_file( out, d )NEWLINENEWLINE def test_file_exists(self):NEWLINE common.file_exists(out)NEWLINENEWLINE def test_file_not_empty(self):NEWLINE common.file_not_empty(out)NEWLINENEWLINE def test_file_contents_match(self):NEWLINE common.file_contents_match(domain, out)NEWLINENEWLINE def test_dictionary_created(self):NEWLINE common.dictionary_created(d)NEWLINENEWLINE def test_dictionary_contains_right_keys(self):NEWLINE common.dictionary_contains_right_keys(d)NEWLINENEWLINE def test_dictionary_values_correct_type(self):NEWLINE common.dictionary_values_correct_type(d)NEWLINE |
# PyYAML libraryNEWLINE__license__ = 'MIT'NEWLINE__author__ = 'Kirill Simonov'NEWLINE__copyright__ = """NEWLINE Copyright (c) 2017-2020 Ingy döt NetNEWLINE Copyright (c) 2006-2016 Kirill SimonovNEWLINE """NEWLINENEWLINE# For changes regarding this port for Ignition usage, please contact:NEWLINE__maintainer__ = 'Andrew Geiger'NEWLINE__email__ = '[email protected]'NEWLINENEWLINENEWLINE__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']NEWLINENEWLINEclass Mark(object):NEWLINENEWLINE def __init__(self, name, index, line, column, buffer, pointer):NEWLINE self.name = nameNEWLINE self.index = indexNEWLINE self.line = lineNEWLINE self.column = columnNEWLINE self.buffer = bufferNEWLINE self.pointer = pointerNEWLINENEWLINE def get_snippet(self, indent=4, max_length=75):NEWLINE if self.buffer is None:NEWLINE return NoneNEWLINE head = ''NEWLINE start = self.pointerNEWLINE while start > 0 and self.buffer[start-1] not in u'\0\r\n\x85\u2028\u2029':NEWLINE start -= 1NEWLINE if self.pointer-start > max_length/2-1:NEWLINE head = ' ... 'NEWLINE start += 5NEWLINE breakNEWLINE tail = ''NEWLINE end = self.pointerNEWLINE while end < len(self.buffer) and self.buffer[end] not in u'\0\r\n\x85\u2028\u2029':NEWLINE end += 1NEWLINE if end-self.pointer > max_length/2-1:NEWLINE tail = ' ... 'NEWLINE end -= 5NEWLINE breakNEWLINE snippet = self.buffer[start:end].encode('utf-8')NEWLINE return ' '*indent + head + snippet + tail + '\n' \NEWLINE + ' '*(indent+self.pointer-start+len(head)) + '^'NEWLINENEWLINE def __str__(self):NEWLINE snippet = self.get_snippet()NEWLINE where = " in \"%s\", line %d, column %d" \NEWLINE % (self.name, self.line+1, self.column+1)NEWLINE if snippet is not None:NEWLINE where += ":\n"+snippetNEWLINE return whereNEWLINENEWLINEclass YAMLError(Exception):NEWLINE passNEWLINENEWLINEclass MarkedYAMLError(YAMLError):NEWLINENEWLINE def __init__(self, context=None, context_mark=None,NEWLINE problem=None, problem_mark=None, note=None):NEWLINE self.context = contextNEWLINE self.context_mark = context_markNEWLINE self.problem = problemNEWLINE self.problem_mark = problem_markNEWLINE self.note = noteNEWLINENEWLINE def __str__(self):NEWLINE lines = []NEWLINE if self.context is not None:NEWLINE lines.append(self.context)NEWLINE if self.context_mark is not None \NEWLINE and (self.problem is None or self.problem_mark is NoneNEWLINE or self.context_mark.name != self.problem_mark.nameNEWLINE or self.context_mark.line != self.problem_mark.lineNEWLINE or self.context_mark.column != self.problem_mark.column):NEWLINE lines.append(str(self.context_mark))NEWLINE if self.problem is not None:NEWLINE lines.append(self.problem)NEWLINE if self.problem_mark is not None:NEWLINE lines.append(str(self.problem_mark))NEWLINE if self.note is not None:NEWLINE lines.append(self.note)NEWLINE return '\n'.join(lines)NEWLINE |
import requestsNEWLINENEWLINE#sresponse = requests.get() |
from selenium.webdriver.common.keys import KeysNEWLINEimport timeNEWLINEimport randomNEWLINENEWLINEfrom selenium_ui.base_page import BasePageNEWLINEfrom selenium_ui.jira.pages.selectors import UrlManager, LoginPageLocators, DashboardLocators, PopupLocators, \NEWLINE IssueLocators, ProjectLocators, SearchLocators, BoardsListLocators, BoardLocators, LogoutLocatorsNEWLINENEWLINENEWLINEclass PopupManager(BasePage):NEWLINENEWLINE def dismiss_default_popup(self):NEWLINE return self.dismiss_popup(PopupLocators.default_popup, PopupLocators.popup_1, PopupLocators.popup_2)NEWLINENEWLINENEWLINEclass Login(BasePage):NEWLINE page_url = LoginPageLocators.login_urlNEWLINE page_loaded_selector = LoginPageLocators.system_dashboardNEWLINENEWLINE def is_first_login(self):NEWLINE return True if self.get_elements(LoginPageLocators.continue_button) else FalseNEWLINENEWLINE def first_login_setup(self):NEWLINE self.wait_until_visible(LoginPageLocators.continue_button).send_keys(Keys.ESCAPE)NEWLINE self.get_element(LoginPageLocators.continue_button).click()NEWLINE self.wait_until_visible(LoginPageLocators.avatar_page_next_button).click()NEWLINE self.wait_until_visible(LoginPageLocators.explore_current_projects).click()NEWLINE self.go_to_url(DashboardLocators.dashboard_url)NEWLINE self.wait_until_visible(DashboardLocators.dashboard_window)NEWLINENEWLINE def set_credentials(self, username, password):NEWLINE self.get_element(LoginPageLocators.login_field).send_keys(username)NEWLINE self.get_element(LoginPageLocators.password_field).send_keys(password)NEWLINE self.get_element(LoginPageLocators.login_submit_button).click()NEWLINENEWLINENEWLINEclass Logout(BasePage):NEWLINE page_url = LogoutLocators.logout_urlNEWLINENEWLINE def click_logout(self):NEWLINE self.get_element(LogoutLocators.logout_submit_button).click()NEWLINENEWLINE def wait_for_page_loaded(self):NEWLINE self.wait_until_present(LogoutLocators.login_button_link)NEWLINENEWLINENEWLINEclass Dashboard(BasePage):NEWLINE page_url = DashboardLocators.dashboard_urlNEWLINENEWLINE def wait_dashboard_presented(self):NEWLINE self.wait_until_present(DashboardLocators.dashboard_window)NEWLINENEWLINENEWLINEclass Issue(BasePage):NEWLINE page_loaded_selector = IssueLocators.issue_titleNEWLINENEWLINE def __init__(self, driver, issue_key=None, issue_id=None):NEWLINE BasePage.__init__(self, driver)NEWLINE url_manager_modal = UrlManager(issue_key=issue_key)NEWLINE url_manager_edit_page = UrlManager(issue_id=issue_id)NEWLINE self.page_url = url_manager_modal.issue_url()NEWLINE self.page_url_edit_issue = url_manager_edit_page.edit_issue_url()NEWLINE self.page_url_edit_comment = url_manager_edit_page.edit_comments_url()NEWLINENEWLINE def wait_for_issue_title(self):NEWLINE self.wait_until_visible(IssueLocators.issue_title)NEWLINENEWLINE def go_to_edit_issue(self):NEWLINE self.go_to_url(self.page_url_edit_issue)NEWLINE self.wait_until_visible(IssueLocators.edit_issue_page)NEWLINENEWLINE def go_to_edit_comment(self):NEWLINE self.go_to_url(self.page_url_edit_comment)NEWLINE self.wait_until_visible(IssueLocators.edit_comment_add_comment_button)NEWLINENEWLINE def fill_summary_edit(self):NEWLINE text_summary = f"Edit summary form selenium - {self.generate_random_string(10)}"NEWLINE self.get_element(IssueLocators.issue_summary_field).send_keys(text_summary)NEWLINENEWLINE def __fill_rich_editor_textfield(self, text, selector):NEWLINE self.wait_until_available_to_switch(selector)NEWLINE self.get_element(IssueLocators.tinymce_description_field).send_keys(text)NEWLINE self.return_to_parent_frame()NEWLINENEWLINE def edit_issue_submit(self):NEWLINE self.get_element(IssueLocators.edit_issue_submit).click()NEWLINENEWLINE def fill_description_edit(self):NEWLINE text_description = f"Edit description form selenium - {self.generate_random_string(30)}"NEWLINE self.__fill_rich_editor_textfield(text_description, selector=IssueLocators.issue_description_field)NEWLINENEWLINE def open_create_issue_modal(self):NEWLINE self.wait_until_clickable(IssueLocators.create_issue_button).click()NEWLINE self.wait_until_visible(IssueLocators.issue_modal)NEWLINENEWLINE def fill_description_create(self):NEWLINE text_description = f'Description: {self.generate_random_string(100)}'NEWLINE self.__fill_rich_editor_textfield(text_description, selector=IssueLocators.issue_description_field)NEWLINENEWLINE def fill_summary_create(self):NEWLINE summary = f"Issue created date {time.time()}"NEWLINE self.wait_until_clickable(IssueLocators.issue_summary_field).send_keys(summary)NEWLINENEWLINE def assign_to_me(self):NEWLINE assign_to_me_links = self.get_elements(IssueLocators.issue_assign_to_me_link)NEWLINE for link in assign_to_me_links:NEWLINE link.click()NEWLINENEWLINE def set_resolution(self):NEWLINE resolution_field = self.get_elements(IssueLocators.issue_resolution_field)NEWLINE if resolution_field:NEWLINE drop_down_length = len(self.select(resolution_field[0]).options)NEWLINE random_resolution_id = random.randint(1, drop_down_length - 1)NEWLINE self.select(resolution_field[0]).select_by_index(random_resolution_id)NEWLINENEWLINE def set_issue_type(self):NEWLINE def __filer_epic(element):NEWLINE return "epic" not in element.get_attribute("class").lower()NEWLINENEWLINE self.get_element(IssueLocators.issue_type_field).click()NEWLINE issue_dropdown_elements = self.get_elements(IssueLocators.issue_type_dropdown_elements)NEWLINE if issue_dropdown_elements:NEWLINE filtered_issue_elements = list(filter(__filer_epic, issue_dropdown_elements))NEWLINE rnd_issue_type_el = random.choice(filtered_issue_elements)NEWLINE self.action_chains().move_to_element(rnd_issue_type_el).click(rnd_issue_type_el).perform()NEWLINE self.wait_until_invisible(IssueLocators.issue_ready_to_save_spinner)NEWLINENEWLINE def submit_issue(self):NEWLINE self.wait_until_clickable(IssueLocators.issue_submit_button).click()NEWLINE self.wait_until_invisible(IssueLocators.issue_modal)NEWLINENEWLINE def fill_comment_edit(self):NEWLINE text = 'Comment from selenium'NEWLINE self.__fill_rich_editor_textfield(text, selector=IssueLocators.edit_comment_text_field)NEWLINENEWLINE def edit_comment_submit(self):NEWLINE self.get_element(IssueLocators.edit_comment_add_comment_button).click()NEWLINE self.wait_until_visible(IssueLocators.issue_title)NEWLINENEWLINENEWLINEclass Project(BasePage):NEWLINE page_loaded_selector = ProjectLocators.project_summary_property_columnNEWLINENEWLINE def __init__(self, driver, project_key):NEWLINE BasePage.__init__(self, driver)NEWLINE url_manager = UrlManager(project_key=project_key)NEWLINE self.page_url = url_manager.project_summary_url()NEWLINENEWLINENEWLINEclass ProjectsList(BasePage):NEWLINENEWLINE def __init__(self, driver, projects_list_pages):NEWLINE BasePage.__init__(self, driver)NEWLINE self.projects_list_page = random.randint(1, projects_list_pages)NEWLINE url_manager = UrlManager(projects_list_page=self.projects_list_page)NEWLINE self.page_url = url_manager.projects_list_page_url()NEWLINENEWLINE def wait_for_page_loaded(self):NEWLINE self.wait_until_any_ec_presented(NEWLINE selector_names=[ProjectLocators.projects_list, ProjectLocators.projects_not_found])NEWLINENEWLINENEWLINEclass BoardsList(BasePage):NEWLINE page_url = BoardsListLocators.boards_list_urlNEWLINE page_loaded_selector = BoardsListLocators.boards_listNEWLINENEWLINENEWLINEclass Search(BasePage):NEWLINENEWLINE def __init__(self, driver, jql):NEWLINE BasePage.__init__(self, driver)NEWLINE url_manager = UrlManager(jql=jql)NEWLINE self.page_url = url_manager.jql_search_url()NEWLINENEWLINE def wait_for_page_loaded(self):NEWLINE self.wait_until_any_ec_presented(selector_names=[SearchLocators.search_issue_table,NEWLINE SearchLocators.search_issue_content,NEWLINE SearchLocators.search_no_issue_found])NEWLINENEWLINENEWLINEclass Board(BasePage):NEWLINE page_loaded_selector = BoardLocators.board_columnsNEWLINENEWLINE def __init__(self, driver, board_id):NEWLINE BasePage.__init__(self, driver)NEWLINE url_manager = UrlManager(board_id=board_id)NEWLINE self.page_url = url_manager.scrum_board_url()NEWLINE self.backlog_url = url_manager.scrum_board_backlog_url()NEWLINENEWLINE def go_to_backlog(self):NEWLINE self.go_to_url(self.backlog_url)NEWLINENEWLINE def wait_for_scrum_board_backlog(self):NEWLINE self.wait_until_present(BoardLocators.scrum_board_backlog_content)NEWLINE |
"""NEWLINETests for navtagsNEWLINE"""NEWLINENEWLINEimport pytestNEWLINEassert pytestNEWLINENEWLINEfrom django.http import HttpRequestNEWLINENEWLINEfrom hm_web.templatetags import navtagsNEWLINENEWLINENEWLINEdef build_request(path):NEWLINE """NEWLINE Build an HttpRequest object with the given pathNEWLINE """NEWLINE request = HttpRequest()NEWLINE request.path = pathNEWLINE return requestNEWLINENEWLINENEWLINEdef test_home_active():NEWLINE assert navtags.active(build_request('/'), '/') == 'active'NEWLINE assert navtags.active(build_request('/login'), '/') == ''NEWLINENEWLINENEWLINEdef test_login_active():NEWLINE assert navtags.active(build_request('/'), '/login') == ''NEWLINE assert navtags.active(build_request('/login'), '/login') == 'active'NEWLINE |
from IPython import get_ipythonNEWLINEfrom IPython.core.magic import (magics_class, line_magic)NEWLINEfrom IPython.core.magics.osm import OSMagicsNEWLINEfrom johnstarich.ipython.shell import find_varNEWLINEimport keywordNEWLINEimport shutilNEWLINENEWLINENEWLINE@magics_classNEWLINEclass Bashisms(OSMagics):NEWLINE @propertyNEWLINE def _exit_code(self) -> int:NEWLINE return self.shell.user_ns['_exit_code']NEWLINENEWLINE @_exit_code.setterNEWLINE def _exit_code(self, value: int):NEWLINE self.shell.user_ns['_exit_code'] = valueNEWLINENEWLINE @line_magicNEWLINE def echo(self, line: str):NEWLINE "Simply print out its received arguments."NEWLINE print(line.format(**vars(), **globals()))NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE @line_magicNEWLINE def cd(self, parameter_s=''):NEWLINE super(Bashisms, self).cd('-q ' + parameter_s)NEWLINENEWLINE @line_magicNEWLINE def which(self, line):NEWLINE var_location = find_var(self.shell, line)NEWLINE if var_location is not None:NEWLINE print(var_location.get(line))NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE if keyword.iskeyword(line):NEWLINE help(line)NEWLINE self._exit_code = 0NEWLINE returnNEWLINENEWLINE ex = shutil.which(line)NEWLINE if ex is not None:NEWLINE print(ex)NEWLINE self._exit_code = 0NEWLINE returnNEWLINE else:NEWLINE print('"{}" could not be found on $PATH'NEWLINE .format(line))NEWLINE self._exit_code = 1NEWLINE returnNEWLINENEWLINEip = get_ipython()NEWLINEip.register_magics(Bashisms)NEWLINEdel ipNEWLINE |
import numpy as npNEWLINEfrom wacky_rl import layersNEWLINEfrom collections import dequeNEWLINENEWLINEclass AgentCore:NEWLINENEWLINE def __init__(self, obs_seq_lenght = 6):NEWLINE self.approx_contin = FalseNEWLINE self.obs_seq_lenght = obs_seq_lenghtNEWLINE self.obs_mem = deque(maxlen=obs_seq_lenght)NEWLINENEWLINE if not hasattr(self, 'logger'):NEWLINE self.logger = NoneNEWLINENEWLINE if not hasattr(self, 'approx_contin'):NEWLINE self.approx_contin = FalseNEWLINENEWLINE if not hasattr(self, 'env'):NEWLINE self.env = NoneNEWLINENEWLINE def __call__(self, *args, **kwargs):NEWLINE return self.act( *args, **kwargs)NEWLINENEWLINE def act(self, inputs, act_argmax=False):NEWLINE raise NotImplementedError('When subclassing the `AgentCore` class, you should 'NEWLINE 'implement a `act` method.')NEWLINENEWLINE def learn(self, *args, **kwargs):NEWLINE raise NotImplementedError('When subclassing the `AgentCore` class, you should 'NEWLINE 'implement a `train` method.')NEWLINENEWLINE def decode_space(self, gym_space):NEWLINENEWLINE from gym import spacesNEWLINENEWLINE if isinstance(gym_space, spaces.Box):NEWLINE import numpy as npNEWLINE return int(np.squeeze(gym_space.shape))NEWLINENEWLINE elif isinstance(gym_space, spaces.Discrete):NEWLINE return int(gym_space.n)NEWLINENEWLINE else:NEWLINE raise AttributeError('gym_space not understood: {}, use space.Box or space.Discrete'.format(gym_space))NEWLINENEWLINE def space_is_contin(self, gym_space):NEWLINE from gym import spacesNEWLINE return isinstance(gym_space, spaces.Box)NEWLINENEWLINE def space_is_discrete(self, gym_space):NEWLINE from gym import spacesNEWLINE return isinstance(gym_space, spaces.Discrete)NEWLINENEWLINE def make_action_layer(self, env, num_bins=21, num_actions=None, approx_contin=False, *args, **kwargs):NEWLINENEWLINE if num_actions is None:NEWLINE num_actions = int(self.decode_space(env.action_space))NEWLINENEWLINE if self.space_is_discrete(env.action_space):NEWLINE self.out_format = intNEWLINE return layers.DiscreteActionLayer(num_bins=num_actions, *args, **kwargs)NEWLINE elif approx_contin:NEWLINE self.out_format = floatNEWLINE self.approx_contin = TrueNEWLINE return layers.DiscreteActionLayer(num_bins=num_bins, num_actions=num_actions, *args, **kwargs)NEWLINE else:NEWLINE self.out_format = floatNEWLINE return layers.ContinActionLayer(num_actions=num_actions, *args, **kwargs)NEWLINENEWLINE def compare_with_old_policy(self, test_reward):NEWLINE passNEWLINENEWLINE def transform_actions(self, dist, actions, lows=None, highs=None, scale=1.0):NEWLINENEWLINE if self.approx_contin:NEWLINE actions = dist.discrete_to_contin(actions)NEWLINENEWLINE actions = np.squeeze(actions.numpy()) * scaleNEWLINENEWLINE if not lows is None or not highs is None:NEWLINE actions = np.clip(actions, a_min=lows, a_max=highs)NEWLINENEWLINE return actions.astype(self.out_format)NEWLINENEWLINE def take_step(self, obs, save_memories=True, render_env=False, act_argmax=False):NEWLINENEWLINE self.obs_mem.append(obs)NEWLINE # print(np.squeeze(np.array(self.obs_mem)))NEWLINE action = self.act(np.squeeze(np.array(self.obs_mem)), act_argmax=act_argmax, save_memories=save_memories)NEWLINE # action = self.agent.act(np.ravel(np.squeeze(np.array(self.obs_mem))), act_argmax=act_argmax, save_memories=save_memories)NEWLINE new_obs, r, done, _ = self.env.step(np.squeeze(action))NEWLINENEWLINE if save_memories:NEWLINE self.memory({NEWLINE 'obs': np.squeeze(np.array(self.obs_mem))NEWLINE # 'obs': np.ravel(np.squeeze(np.array(self.obs_mem)))NEWLINE }NEWLINE )NEWLINE self.obs_mem.append(new_obs)NEWLINE self.memory({NEWLINE # 'obs': np.array(self.obs_mem),NEWLINE 'new_obs': np.squeeze(np.array(self.obs_mem)),NEWLINE # 'new_obs': np.ravel(np.squeeze(np.array(self.obs_mem))),NEWLINE 'rewards': r,NEWLINE 'dones': float(1 - int(done)),NEWLINE }NEWLINE )NEWLINENEWLINE if render_env:NEWLINE self.env.render()NEWLINENEWLINE return done, new_obs, rNEWLINENEWLINE def sample_warmup(self, num_episodes, render_env=False):NEWLINE for e in range(num_episodes):NEWLINENEWLINE done = FalseNEWLINE obs = self.env.reset()NEWLINENEWLINE while not done:NEWLINE done, obs, _ = self.take_step(obs, save_memories=True, render_env=render_env)NEWLINE self.env.close()NEWLINENEWLINE def episode_train(self, num_episodes, render_env=False):NEWLINE for e in range(num_episodes):NEWLINENEWLINE done = FalseNEWLINE obs = self.env.reset()NEWLINE reward_list = []NEWLINE for i in range(self.obs_seq_lenght):NEWLINE self.obs_mem.append(np.zeros(np.shape(obs)))NEWLINENEWLINE while not done:NEWLINE done, obs, r = self.take_step(obs, save_memories=True, render_env=render_env)NEWLINE # self.env.render()NEWLINE reward_list.append(r)NEWLINENEWLINE if done:NEWLINE a_loss, c_loss = self.learn()NEWLINE if self.logger is None:NEWLINE print()NEWLINE print('# Episode', e)NEWLINE print('# Sum R:', np.round(np.sum(reward_list), 1))NEWLINE print('# Loss A:', np.round(np.mean(a_loss), 4))NEWLINE print('# Loss C:', np.round(np.mean(c_loss), 4))NEWLINE else:NEWLINE self.logger.log_mean('reward', np.round(np.sum(reward_list)))NEWLINE self.logger.print_status(e)NEWLINENEWLINE self.env.close()NEWLINENEWLINE def n_step_train(NEWLINE self,NEWLINE num_steps,NEWLINE n_steps=2048,NEWLINE render_env=False,NEWLINE train_on_test=True,NEWLINE render_test=True,NEWLINE ):NEWLINENEWLINE train_after = n_stepsNEWLINE episode_reward_list = []NEWLINE s = 0NEWLINE while s < num_steps:NEWLINENEWLINE obs = self.env.reset()NEWLINE done = FalseNEWLINE reward_list = []NEWLINE for i in range(self.obs_seq_lenght):NEWLINE self.obs_mem.append(np.zeros(np.shape(obs)))NEWLINENEWLINE while not done:NEWLINE done, obs, r = self.take_step(obs, save_memories=True, render_env=render_env)NEWLINE reward_list.append(r)NEWLINE s += 1NEWLINENEWLINE if done:NEWLINE obs = self.env.reset()NEWLINE episode_reward_list.append(np.sum(reward_list))NEWLINE reward_list = []NEWLINENEWLINE if s >= train_after:NEWLINE train_after += n_stepsNEWLINE a_loss, c_loss = self.learn()NEWLINE if self.logger is None:NEWLINE print()NEWLINE print('# steps', s)NEWLINE print('# Sum R:', np.round(np.sum(episode_reward_list), 1))NEWLINE print('# Loss A:', np.round(np.mean(a_loss), 4))NEWLINE print('# Loss C:', np.round(np.mean(c_loss), 4))NEWLINE else:NEWLINE self.logger.log_mean('sum reward', np.round(np.mean(episode_reward_list)))NEWLINE # print('sum reward:', np.round(np.sum(episode_reward_list), 1))NEWLINE self.logger.print_status(s)NEWLINE episode_reward_list = []NEWLINENEWLINE # Test:NEWLINE if train_on_test or render_test:NEWLINE done = FalseNEWLINE while not done:NEWLINE done, obs, r = self.take_step(obs, save_memories=True, render_env=render_test, act_argmax=True)NEWLINE reward_list.append(r)NEWLINENEWLINE if done:NEWLINE print('test reward:', np.round(sum(reward_list), 1))NEWLINE obs = self.env.reset()NEWLINE reward_list = []NEWLINENEWLINE self.env.close()NEWLINE |
"""NEWLINEModule related to the argument parsingNEWLINENEWLINEThere is a fallback to the deprecated optparse if argparse is not foundNEWLINE"""NEWLINEfrom pathlib import PathNEWLINEfrom argparse import ArgumentParser, SUPPRESSNEWLINENEWLINENEWLINEdef parse_args(CONFIG_PATH: Path):NEWLINE """NEWLINE Parse the arguments from the command lineNEWLINE """NEWLINE parser = ArgumentParser('poezio')NEWLINE parser.add_argument(NEWLINE "-c",NEWLINE "--check-config",NEWLINE dest="check_config",NEWLINE action='store_true',NEWLINE help='Check the config file')NEWLINE parser.add_argument(NEWLINE "-d",NEWLINE "--debug",NEWLINE dest="debug",NEWLINE help="The file where debug will be written",NEWLINE metavar="DEBUG_FILE")NEWLINE parser.add_argument(NEWLINE "-f",NEWLINE "--file",NEWLINE dest="filename",NEWLINE default=CONFIG_PATH / 'poezio.cfg',NEWLINE type=Path,NEWLINE help="The config file you want to use",NEWLINE metavar="CONFIG_FILE")NEWLINE parser.add_argument(NEWLINE "-v",NEWLINE "--version",NEWLINE dest="version",NEWLINE help=SUPPRESS,NEWLINE metavar="VERSION",NEWLINE default="0.13-dev")NEWLINE options = parser.parse_args()NEWLINE return optionsNEWLINE |
#-----------------------------------------------------------------------------NEWLINE# Copyright (c) 2005-2016, PyInstaller Development Team.NEWLINE#NEWLINE# Distributed under the terms of the GNU General Public License with exceptionNEWLINE# for distributing bootloader.NEWLINE#NEWLINE# The full license is in the file COPYING.txt, distributed with this software.NEWLINE#-----------------------------------------------------------------------------NEWLINENEWLINENEWLINE"""NEWLINEUtilities to create data structures for embedding Python modules and additionalNEWLINEfiles into the executable.NEWLINE"""NEWLINENEWLINE# While an Archive is really an abstraction for any "filesystemNEWLINE# within a file", it is tuned for use with imputil.FuncImporter.NEWLINE# This assumes it contains python code objects, indexed by theNEWLINE# the internal name (ie, no '.py').NEWLINE#NEWLINE# See pyi_carchive.py for a more general archive (contains anything)NEWLINE# that can be understood by a C program.NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport structNEWLINEfrom types import CodeTypeNEWLINEimport marshalNEWLINEimport zlibNEWLINENEWLINEfrom PyInstaller.building.utils import get_code_object, strip_paths_in_codeNEWLINEfrom .readers import PYZ_TYPE_MODULE, PYZ_TYPE_PKG, PYZ_TYPE_DATANEWLINEfrom ..compat import BYTECODE_MAGIC, is_py2NEWLINENEWLINENEWLINEclass ArchiveWriter(object):NEWLINE """NEWLINE A base class for a repository of python code objects.NEWLINE The extract method is used by imputil.ArchiveImporterNEWLINE to get code objects by name (fully qualified name), soNEWLINE an enduser "import a.b" would becomeNEWLINE extract('a.__init__')NEWLINE extract('a.b')NEWLINE """NEWLINE MAGIC = b'PYL\0'NEWLINE HDRLEN = 12 # default is MAGIC followed by python's magic, int pos of tocNEWLINE TOCPOS = 8NEWLINENEWLINE def __init__(self, archive_path, logical_toc):NEWLINE """NEWLINE Create an archive file of name 'archive_path'.NEWLINE logical_toc is a 'logical TOC' - a list of (name, path, ...)NEWLINE where name is the internal name, eg 'a'NEWLINE and path is a file to get the object from, eg './a.pyc'.NEWLINE """NEWLINE self.start = 0NEWLINENEWLINE self._start_add_entries(archive_path)NEWLINE self._add_from_table_of_contents(logical_toc)NEWLINE self._finalize()NEWLINENEWLINE def _start_add_entries(self, archive_path):NEWLINE """NEWLINE Open an empty archive for addition of entries.NEWLINE """NEWLINE self.lib = open(archive_path, 'wb')NEWLINE # Reserve space for the header.NEWLINE if self.HDRLEN:NEWLINE self.lib.write(b'\0' * self.HDRLEN)NEWLINE # Create an empty table of contents.NEWLINE # Use a list to support reproducible buildsNEWLINE self.toc = []NEWLINENEWLINE def _add_from_table_of_contents(self, toc):NEWLINE """NEWLINE Add entries from a logical TOC (without absolute positioning info).NEWLINE An entry is an entry in a logical TOC is a tuple,NEWLINE entry[0] is name (under which it will be saved).NEWLINE entry[1] is fullpathname of the file.NEWLINE entry[2] is a flag for it's storage format (True or 1 if compressed)NEWLINE entry[3] is the entry's type code.NEWLINE """NEWLINE for toc_entry in toc:NEWLINE self.add(toc_entry) # The guts of the archive.NEWLINENEWLINE def _finalize(self):NEWLINE """NEWLINE Finalize an archive which has been opened using _start_add_entries(),NEWLINE writing any needed padding and the table of contents.NEWLINE """NEWLINE toc_pos = self.lib.tell()NEWLINE self.save_trailer(toc_pos)NEWLINE if self.HDRLEN:NEWLINE self.update_headers(toc_pos)NEWLINE self.lib.close()NEWLINENEWLINENEWLINE ####### manages keeping the internal TOC and the guts in sync #######NEWLINE def add(self, entry):NEWLINE """NEWLINE Override this to influence the mechanics of the Archive.NEWLINE Assumes entry is a seq beginning with (nm, pth, ...) whereNEWLINE nm is the key by which we'll be asked for the object.NEWLINE pth is the name of where we find the object. Overrides ofNEWLINE get_obj_from can make use of further elements in entry.NEWLINE """NEWLINE nm = entry[0]NEWLINE pth = entry[1]NEWLINE pynm, ext = os.path.splitext(os.path.basename(pth))NEWLINE ispkg = pynm == '__init__'NEWLINE assert ext in ('.pyc', '.pyo')NEWLINE self.toc.append((nm, (ispkg, self.lib.tell())))NEWLINE f = open(entry[1], 'rb')NEWLINE f.seek(8) # skip magic and timestampNEWLINE self.lib.write(f.read())NEWLINENEWLINE def save_trailer(self, tocpos):NEWLINE """NEWLINE Default - toc is a dictNEWLINE Gets marshaled to self.libNEWLINE """NEWLINE try:NEWLINE self.lib.write(marshal.dumps(self.toc))NEWLINE # If the TOC to be marshalled contains an unmarshallable object, PythonNEWLINE # raises a cryptic exception providing no details on why such object isNEWLINE # unmarshallable. Correct this by iteratively inspecting the TOC forNEWLINE # unmarshallable objects.NEWLINE except ValueError as exception:NEWLINE if str(exception) == 'unmarshallable object':NEWLINENEWLINE # List of all marshallable types.NEWLINE MARSHALLABLE_TYPES = set((NEWLINE bool, int, float, complex, str, bytes, bytearray,NEWLINE tuple, list, set, frozenset, dict, CodeType))NEWLINE if sys.version_info[0] == 2:NEWLINE MARSHALLABLE_TYPES.add(long)NEWLINENEWLINE for module_name, module_tuple in self.toc.items():NEWLINE if type(module_name) not in MARSHALLABLE_TYPES:NEWLINE print('Module name "%s" (%s) unmarshallable.' % (module_name, type(module_name)))NEWLINE if type(module_tuple) not in MARSHALLABLE_TYPES:NEWLINE print('Module "%s" tuple "%s" (%s) unmarshallable.' % (module_name, module_tuple, type(module_tuple)))NEWLINE elif type(module_tuple) == tuple:NEWLINE for i in range(len(module_tuple)):NEWLINE if type(module_tuple[i]) not in MARSHALLABLE_TYPES:NEWLINE print('Module "%s" tuple index %s item "%s" (%s) unmarshallable.' % (module_name, i, module_tuple[i], type(module_tuple[i])))NEWLINENEWLINE raiseNEWLINENEWLINE def update_headers(self, tocpos):NEWLINE """NEWLINE Default - MAGIC + Python's magic + tocposNEWLINE """NEWLINE self.lib.seek(self.start)NEWLINE self.lib.write(self.MAGIC)NEWLINE self.lib.write(BYTECODE_MAGIC)NEWLINE self.lib.write(struct.pack('!i', tocpos))NEWLINENEWLINENEWLINEclass ZlibArchiveWriter(ArchiveWriter):NEWLINE """NEWLINE ZlibArchive - an archive with compressed entries. Archive is readNEWLINE from the executable created by PyInstaller.NEWLINENEWLINE This archive is used for bundling python modules inside the executable.NEWLINENEWLINE NOTE: The whole ZlibArchive (PYZ) is compressed so it is not necessaryNEWLINE to compress single modules with zlib.NEWLINE """NEWLINE MAGIC = b'PYZ\0'NEWLINE TOCPOS = 8NEWLINE HDRLEN = ArchiveWriter.HDRLEN + 5NEWLINE COMPRESSION_LEVEL = 6 # Default level of the 'zlib' module from Python.NEWLINENEWLINE def __init__(self, archive_path, logical_toc, code_dict=None, cipher=None):NEWLINE """NEWLINE code_dict dict containing module code objects from ModuleGraph.NEWLINE """NEWLINE # Keep references to module code objects constructed by ModuleGraphNEWLINE # to avoid writting .pyc/pyo files to hdd.NEWLINE self.code_dict = code_dict or {}NEWLINE self.cipher = cipher or NoneNEWLINENEWLINE super(ZlibArchiveWriter, self).__init__(archive_path, logical_toc)NEWLINENEWLINENEWLINE def add(self, entry):NEWLINE name, path, typ = entryNEWLINE if typ == 'PYMODULE':NEWLINE typ = PYZ_TYPE_MODULENEWLINE if path in ('-', None):NEWLINE # This is a NamespacePackage, modulegraph marks themNEWLINE # by using the filename '-'. (But wants to use None,NEWLINE # so check for None, too, to be forward-compatible.)NEWLINE typ = PYZ_TYPE_PKGNEWLINE else:NEWLINE base, ext = os.path.splitext(os.path.basename(path))NEWLINE if base == '__init__':NEWLINE typ = PYZ_TYPE_PKGNEWLINE data = marshal.dumps(self.code_dict[name])NEWLINE else:NEWLINE # Any data files, that might be required by pkg_resources.NEWLINE typ = PYZ_TYPE_DATANEWLINE with open(path, 'rb') as fh:NEWLINE data = fh.read()NEWLINE # No need to use forward slash as path-separator here sinceNEWLINE # pkg_resources on Windows back slash as path-separator.NEWLINENEWLINE obj = zlib.compress(data, self.COMPRESSION_LEVEL)NEWLINENEWLINE # First compress then encrypt.NEWLINE if self.cipher:NEWLINE obj = self.cipher.encrypt(obj)NEWLINENEWLINE self.toc.append((name, (typ, self.lib.tell(), len(obj))))NEWLINE self.lib.write(obj)NEWLINENEWLINE def update_headers(self, tocpos):NEWLINE """NEWLINE add levelNEWLINE """NEWLINE ArchiveWriter.update_headers(self, tocpos)NEWLINE self.lib.write(struct.pack('!B', self.cipher is not None))NEWLINENEWLINENEWLINENEWLINEclass CTOC(object):NEWLINE """NEWLINE A class encapsulating the table of contents of a CArchive.NEWLINENEWLINE When written to disk, it is easily read from C.NEWLINE """NEWLINE ENTRYSTRUCT = '!iiiiBB' # (structlen, dpos, dlen, ulen, flag, typcd) followed by nameNEWLINE ENTRYLEN = struct.calcsize(ENTRYSTRUCT)NEWLINENEWLINE def __init__(self):NEWLINE self.data = []NEWLINENEWLINE def tobinary(self):NEWLINE """NEWLINE Return self as a binary string.NEWLINE """NEWLINE rslt = []NEWLINE for (dpos, dlen, ulen, flag, typcd, nm) in self.data:NEWLINE # Encode all names using UTF-8. This should be save asNEWLINE # standard python modules only contain ascii-charactersNEWLINE # (and standard shared libraries should have the same) andNEWLINE # thus the C-code still can handle this correctly.NEWLINE if is_py2 and isinstance(nm, str):NEWLINE nm = nm.decode(sys.getfilesystemencoding())NEWLINENEWLINE nm = nm.encode('utf-8')NEWLINE nmlen = len(nm) + 1 # add 1 for a '\0'NEWLINE # align to 16 byte boundary so xplatform C can readNEWLINE toclen = nmlen + self.ENTRYLENNEWLINE if toclen % 16 == 0:NEWLINE pad = b'\0'NEWLINE else:NEWLINE padlen = 16 - (toclen % 16)NEWLINE pad = b'\0' * padlenNEWLINE nmlen = nmlen + padlenNEWLINE rslt.append(struct.pack(self.ENTRYSTRUCT + '%is' % nmlen,NEWLINE nmlen + self.ENTRYLEN, dpos, dlen, ulen,NEWLINE flag, ord(typcd), nm + pad))NEWLINENEWLINE return b''.join(rslt)NEWLINENEWLINE def add(self, dpos, dlen, ulen, flag, typcd, nm):NEWLINE """NEWLINE Add an entry to the table of contents.NEWLINENEWLINE DPOS is data position.NEWLINE DLEN is data length.NEWLINE ULEN is the uncompressed data len.NEWLINE FLAG says if the data is compressed.NEWLINE TYPCD is the "type" of the entry (used by the C code)NEWLINE NM is the entry's name.NEWLINENEWLINE This function is used only while creating an executable.NEWLINE """NEWLINE # Ensure forward slashes in paths are on Windows converted to backNEWLINE # slashes '\\' since on Windows the bootloader works only with backNEWLINE # slashes.NEWLINE nm = os.path.normpath(nm)NEWLINE self.data.append((dpos, dlen, ulen, flag, typcd, nm))NEWLINENEWLINENEWLINEclass CArchiveWriter(ArchiveWriter):NEWLINE """NEWLINE An Archive subclass that can hold arbitrary data.NEWLINENEWLINE This class encapsulates all files that are bundled within an executable.NEWLINE It can contain ZlibArchive (Python .pyc files), dlls, Python C extensionsNEWLINE and all other data files that are bundled in --onefile mode.NEWLINENEWLINE Easily handled from C or from Python.NEWLINE """NEWLINE # MAGIC is usefull to verify that conversion of Python data typesNEWLINE # to C structure and back works properly.NEWLINE MAGIC = b'MEI\014\013\012\013\016'NEWLINE HDRLEN = 0NEWLINE LEVEL = 9NEWLINENEWLINE # Cookie - holds some information for the bootloader. C struct formatNEWLINE # definition. '!' at the beginning means network byte order.NEWLINE # C struct looks like:NEWLINE #NEWLINE # typedef struct _cookie {NEWLINE # char magic[8]; /* 'MEI\014\013\012\013\016' */NEWLINE # int len; /* len of entire package */NEWLINE # int TOC; /* pos (rel to start) of TableOfContents */NEWLINE # int TOClen; /* length of TableOfContents */NEWLINE # int pyvers; /* new in v4 */NEWLINE # char pylibname[64]; /* Filename of Python dynamic library. */NEWLINE # } COOKIE;NEWLINE #NEWLINE _cookie_format = '!8siiii64s'NEWLINE _cookie_size = struct.calcsize(_cookie_format)NEWLINENEWLINE def __init__(self, archive_path, logical_toc, pylib_name):NEWLINE """NEWLINE Constructor.NEWLINENEWLINE archive_path path name of file (create empty CArchive if path is None).NEWLINE start is the seekposition within PATH.NEWLINE len is the length of the CArchive (if 0, then read till EOF).NEWLINE pylib_name name of Python DLL which bootloader will use.NEWLINE """NEWLINE self._pylib_name = pylib_nameNEWLINENEWLINE # A CArchive created from scratch starts at 0, no leading bootloader.NEWLINE super(CArchiveWriter, self).__init__(archive_path, logical_toc)NEWLINENEWLINE def _start_add_entries(self, path):NEWLINE """NEWLINE Open an empty archive for addition of entries.NEWLINE """NEWLINE super(CArchiveWriter, self)._start_add_entries(path)NEWLINE # Override parents' toc {} with a class.NEWLINE self.toc = CTOC()NEWLINENEWLINE def add(self, entry):NEWLINE """NEWLINE Add an ENTRY to the CArchive.NEWLINENEWLINE ENTRY must have:NEWLINE entry[0] is name (under which it will be saved).NEWLINE entry[1] is fullpathname of the file.NEWLINE entry[2] is a flag for it's storage format (0==uncompressed,NEWLINE 1==compressed)NEWLINE entry[3] is the entry's type code.NEWLINE Version 5:NEWLINE If the type code is 'o':NEWLINE entry[0] is the runtime optionNEWLINE eg: v (meaning verbose imports)NEWLINE u (menaing unbuffered)NEWLINE W arg (warning option arg)NEWLINE s (meaning do site.py processing.NEWLINE """NEWLINE (nm, pathnm, flag, typcd) = entry[:4]NEWLINE # FIXME Could we make the version 5 the default one?NEWLINE # Version 5 - allow type 'o' = runtime option.NEWLINE code_data = NoneNEWLINE fh = NoneNEWLINE try:NEWLINE if typcd in ('o', 'd'):NEWLINE ulen = 0NEWLINE flag = 0NEWLINE elif typcd == 's':NEWLINE # If it's a source code file, compile it to a code object and marshallNEWLINE # the object so it can be unmarshalled by the bootloader.NEWLINENEWLINE code = get_code_object(nm, pathnm)NEWLINE code = strip_paths_in_code(code)NEWLINENEWLINE code_data = marshal.dumps(code)NEWLINE ulen = len(code_data)NEWLINE else:NEWLINE fh = open(pathnm, 'rb')NEWLINE ulen = os.fstat(fh.fileno()).st_sizeNEWLINE except IOError:NEWLINE print("Cannot find ('%s', '%s', %s, '%s')" % (nm, pathnm, flag, typcd))NEWLINE raiseNEWLINENEWLINE where = self.lib.tell()NEWLINE assert flag in range(3)NEWLINE if not fh and not code_data:NEWLINE # no need to write anythingNEWLINE passNEWLINE elif flag == 1:NEWLINE comprobj = zlib.compressobj(self.LEVEL)NEWLINE if code_data is not None:NEWLINE self.lib.write(comprobj.compress(code_data))NEWLINE else:NEWLINE assert fhNEWLINE while 1:NEWLINE buf = fh.read(16*1024)NEWLINE if not buf:NEWLINE breakNEWLINE self.lib.write(comprobj.compress(buf))NEWLINE self.lib.write(comprobj.flush())NEWLINENEWLINE else:NEWLINE if code_data is not None:NEWLINE self.lib.write(code_data)NEWLINE else:NEWLINE assert fhNEWLINE while 1:NEWLINE buf = fh.read(16*1024)NEWLINE if not buf:NEWLINE breakNEWLINE self.lib.write(buf)NEWLINENEWLINE dlen = self.lib.tell() - whereNEWLINE if typcd == 'm':NEWLINE if pathnm.find('.__init__.py') > -1:NEWLINE typcd = 'M'NEWLINENEWLINE # Record the entry in the CTOCNEWLINE self.toc.add(where, dlen, ulen, flag, typcd, nm)NEWLINENEWLINENEWLINE def save_trailer(self, tocpos):NEWLINE """NEWLINE Save the table of contents and the cookie for the bootlader toNEWLINE disk.NEWLINENEWLINE CArchives can be opened from the end - the cookie pointsNEWLINE back to the start.NEWLINE """NEWLINE tocstr = self.toc.tobinary()NEWLINE self.lib.write(tocstr)NEWLINE toclen = len(tocstr)NEWLINENEWLINE # now save teh cookieNEWLINE total_len = tocpos + toclen + self._cookie_sizeNEWLINE pyvers = sys.version_info[0] * 10 + sys.version_info[1]NEWLINE # Before saving cookie we need to convert it to correspondingNEWLINE # C representation.NEWLINE cookie = struct.pack(self._cookie_format, self.MAGIC, total_len,NEWLINE tocpos, toclen, pyvers,NEWLINE self._pylib_name.encode('ascii'))NEWLINE self.lib.write(cookie)NEWLINE |
"""Given an algorithm object, run the algorithm."""NEWLINEfrom __future__ import division, print_functionNEWLINENEWLINEimport signalNEWLINEimport sysNEWLINEimport multiprocessing as mpNEWLINEimport osNEWLINEimport textwrapNEWLINEimport jsonNEWLINENEWLINEimport requestsNEWLINEimport sixNEWLINEimport codejailNEWLINEfrom codejail.safe_exec import not_safe_execNEWLINEfrom codejail.limits import set_limitNEWLINENEWLINENEWLINE__all__ = ["AlgorithmRunner"]NEWLINENEWLINENEWLINEclass GracefulExit(Exception):NEWLINE """Graceful exit exception class."""NEWLINENEWLINENEWLINEdef sigint_handler(signum, thread):NEWLINE """Handle interrupt signal."""NEWLINE raise GracefulExit()NEWLINENEWLINENEWLINEdef check_environ():NEWLINE """Check that all environment variable exists.NEWLINENEWLINE Note:NEWLINE - Required environment variables are `OPALALGO_SANDBOX_VENV` andNEWLINE `OPALALGO_SANDBOX_USER`.NEWLINENEWLINE """NEWLINE req_environ_vars = ['OPALALGO_SANDBOX_VENV', 'OPALALGO_SANDBOX_USER']NEWLINE for environ_var in req_environ_vars:NEWLINE if environ_var not in os.environ:NEWLINE raise RuntimeError(NEWLINE 'Environment variable {} not set'.format(environ_var))NEWLINENEWLINENEWLINEdef get_jail(python_version=sys.version_info[0]):NEWLINE """Return codejail object.NEWLINENEWLINE Note:NEWLINE - Please set environmental variables `OPALALGO_SANDBOX_VENV`NEWLINE and `OPALALGO_SANDBOX_USER` before calling this function.NEWLINE - `OPALALGO_SANDBOX_VENV` must be set to the path of the sandboxNEWLINE virtual environment.NEWLINE - `OPALALGO_SANDBOX_USER` must be set to the user running theNEWLINE sandboxed algorithms.NEWLINENEWLINE """NEWLINE sandbox_env = os.environ.get('OPALALGO_SANDBOX_VENV')NEWLINE sandbox_user = os.environ.get('OPALALGO_SANDBOX_USER')NEWLINE set_limit("REALTIME", None)NEWLINE set_limit("CPU", 15)NEWLINE codejail.configure(NEWLINE 'python',NEWLINE os.path.join(sandbox_env, 'bin', 'python'),NEWLINE user=sandbox_user)NEWLINE codejail.configure(NEWLINE 'python3',NEWLINE os.path.join(sandbox_env, 'bin', 'python'),NEWLINE user=sandbox_user)NEWLINE if python_version < 3:NEWLINE jail = codejail.get_codejail('python')NEWLINE else:NEWLINE jail = codejail.get_codejail('python3')NEWLINE return jailNEWLINENEWLINENEWLINEdef process_user_csv(params, user_csv_file, algorithm, dev_mode, sandboxing,NEWLINE jail):NEWLINE """Process a single user csv file.NEWLINENEWLINE Args:NEWLINE params (dict): Parameters for the request.NEWLINE user_csv_file (string): Path to user csv file.NEWLINE algorithm (dict): Dictionary with keys `code` and `className`NEWLINE specifying algorithm code and className.NEWLINE dev_mode (bool): Should the algorithm run in development mode orNEWLINE production mode.NEWLINE sandboxing (bool): Should sandboxing be used or not.NEWLINE jail (codejail.Jail): Jail object.NEWLINENEWLINE Returns:NEWLINE Result of the execution.NEWLINENEWLINE Raises:NEWLINE SafeExecException: If the execution wasn't successful.NEWLINENEWLINE """NEWLINE username = os.path.splitext(os.path.basename(user_csv_file))[0]NEWLINE globals_dict = {NEWLINE 'params': params,NEWLINE }NEWLINE user_specific_code = textwrap.dedent(NEWLINE """NEWLINE def run_code():NEWLINE import bandicootNEWLINENEWLINE algorithmobj = {}()NEWLINE bandicoot_user = bandicoot.read_csv(NEWLINE '{}', '', describe={}, warnings={})NEWLINE return algorithmobj.map(params, bandicoot_user)NEWLINE result = run_code()NEWLINE """.format(NEWLINE algorithm['className'], username,NEWLINE str(dev_mode), str(dev_mode)))NEWLINE code = "{}\n{}".format(algorithm['code'], user_specific_code)NEWLINE if sandboxing:NEWLINE jail.safe_exec(NEWLINE code, globals_dict, files=[user_csv_file])NEWLINE else:NEWLINE not_safe_exec(NEWLINE code, globals_dict, files=[user_csv_file])NEWLINE result = globals_dict['result']NEWLINE return resultNEWLINENEWLINENEWLINEdef mapper(writing_queue, params, file_queue, algorithm,NEWLINE dev_mode=False, sandboxing=True, python_version=2):NEWLINE """Call the map function and insert result into the queue if valid.NEWLINENEWLINE Args:NEWLINE writing_queue (mp.manager.Queue): Queue for inserting results.NEWLINE params (dict): Parameters to be used by each map of the algorithm.NEWLINE users_csv_files (list): List of paths of csv files of users.NEWLINE algorithm (dict): Dictionary with keys `code` and `className`NEWLINE specifying algorithm code and className.NEWLINE dev_mode (bool): Should the algorithm run in development mode orNEWLINE production mode.NEWLINE sandboxing (bool): Should sandboxing be used or not.NEWLINE python_version (int): Python version being used for sandboxing.NEWLINENEWLINE """NEWLINE jail = get_jail(python_version)NEWLINE while not file_queue.empty():NEWLINE filepath = NoneNEWLINE scaler = NoneNEWLINE try:NEWLINE result = file_queue.get(timeout=1)NEWLINE filepath, scaler = resultNEWLINE except Exception as exc:NEWLINE print(exc)NEWLINE breakNEWLINE result = process_user_csv(NEWLINE params, filepath, algorithm, dev_mode,NEWLINE sandboxing, jail)NEWLINE if result and is_valid_result(result):NEWLINE writing_queue.put((result, scaler))NEWLINE elif result and dev_mode:NEWLINE print("Error in result {}".format(result))NEWLINENEWLINENEWLINEdef scale_result(result, scaler):NEWLINE """Return scaled result.NEWLINENEWLINE Args:NEWLINE result (dict): Result.NEWLINE scaler (number): Factor by which results need to be scaled.NEWLINENEWLINE Returns:NEWLINE dict: Scaled result.NEWLINENEWLINE """NEWLINE scaled_result = {}NEWLINE for key, val in six.iteritems(result):NEWLINE scaled_result[key] = scaler * valNEWLINE return scaled_resultNEWLINENEWLINENEWLINEdef collector(writing_queue, params, dev_mode=False):NEWLINE """Collect the results in writing queue and post to aggregator.NEWLINENEWLINE Args:NEWLINE writing_queue (mp.manager.Queue): Queue from which collect results.NEWLINE results_csv_path (str): CSV where we have to save results.NEWLINE dev_mode (bool): Whether to run algorithm in development mode.NEWLINENEWLINE Returns:NEWLINE bool: True on successful exit if `dev_mode` is set to False.NEWLINENEWLINE Note:NEWLINE If `dev_mode` is set to true, then collector will just return all theNEWLINE results in a list format.NEWLINENEWLINE """NEWLINE result_processor = ResultProcessor(params, dev_mode)NEWLINE while True:NEWLINE # wait for result to appear in the queueNEWLINE processed_result = writing_queue.get()NEWLINE # if got signal 'kill' exit the loopNEWLINE if processed_result == 'kill':NEWLINE breakNEWLINE result, scaler = processed_resultNEWLINE result_processor(result, scaler=scaler)NEWLINE return result_processor.get_result()NEWLINENEWLINENEWLINEdef is_valid_result(result):NEWLINE """Check if result is valid.NEWLINENEWLINE Args:NEWLINE result: Output of the algorithm.NEWLINENEWLINE Note:NEWLINE Result is valid if it is a dict. All keys of the dict must beNEWLINE be a string. All values must be numbers. These results are sent toNEWLINE reducer which will sum, count, mean, median, mode of the valuesNEWLINE belonging to same key.NEWLINENEWLINE Example:NEWLINE - {"alpha1": 1, "ant199": 1, ..}NEWLINENEWLINE Returns:NEWLINE bool: Specifying if the result is valid or not.NEWLINENEWLINE Todo:NEWLINE * Define what is valid with privacy and other concernsNEWLINENEWLINE """NEWLINE # check result must be a dictNEWLINE if not isinstance(result, dict):NEWLINE return FalseNEWLINE # check each value must be an integer or floatNEWLINE if not (all([isinstance(x, six.integer_types) or isinstance(x, float)NEWLINE for x in six.itervalues(result)])):NEWLINE return FalseNEWLINE # check each key must be a string.NEWLINE if not (all([isinstance(x, six.string_types)NEWLINE for x in six.iterkeys(result)])):NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINENEWLINEclass ResultProcessor(object):NEWLINE """Process results.NEWLINENEWLINE Args:NEWLINE params (dict): Dictionary of parameters.NEWLINE dev_mode (bool): Specify if dev_mode is on.NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, params, dev_mode):NEWLINE """Initialize result processor."""NEWLINE self.params = paramsNEWLINE self.dev_mode = dev_modeNEWLINE self.result_list = []NEWLINENEWLINE def __call__(self, result, scaler=1):NEWLINE """Process the result.NEWLINENEWLINE If dev_mode is set to true, it appends the result to a list.NEWLINE Else it send the post request to `aggregationServiceUrl`.NEWLINENEWLINE Args:NEWLINE result (dict): Result of the processed algorithm.NEWLINE scaler (int): Scale results by what value.NEWLINENEWLINE """NEWLINE result = scale_result(result, scaler)NEWLINE if self.dev_mode:NEWLINE self.result_list.append(result)NEWLINE else:NEWLINE self._send_request(result)NEWLINENEWLINE def _send_request(self, result):NEWLINE """Send request to aggregationServiceUrl.NEWLINENEWLINE Args:NEWLINE result (dict): Result to be sent as an update.NEWLINENEWLINE """NEWLINE response = requests.post(NEWLINE self.params['aggregationServiceUrl'], json={'update': result})NEWLINE if response.status_code != 200:NEWLINE raise RuntimeError(NEWLINE 'Aggregation service returned {}'.format(NEWLINE response.status_code))NEWLINENEWLINE def get_result(self):NEWLINE """Return the result after processing.NEWLINENEWLINE Returns:NEWLINE dict: if dev_mode is set to true else returns `True`NEWLINENEWLINE """NEWLINE if self.dev_mode:NEWLINE return self.result_listNEWLINE return TrueNEWLINENEWLINENEWLINEclass AlgorithmRunner(object):NEWLINE """Algorithm runner.NEWLINENEWLINE Args:NEWLINE algorithm (dict): Dictionary containing `code` and `className`.NEWLINE dev_mode (bool): Development mode switchNEWLINE multiprocess (bool): Use multiprocessing or single process forNEWLINE complete execution.NEWLINE sandboxing (bool): Use sandboxing for execution or execute in unsafeNEWLINE environment.NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, algorithm, dev_mode=False, multiprocess=True,NEWLINE sandboxing=True):NEWLINE """Initialize class."""NEWLINE self.algorithm = algorithmNEWLINE self.dev_mode = dev_modeNEWLINE self.multiprocess = multiprocessNEWLINE self.sandboxing = sandboxingNEWLINENEWLINE def __call__(self, params, data_dir, num_threads, weights_file=None):NEWLINE """Run algorithm.NEWLINENEWLINE Selects the csv files from the data directory. Divides the csv filesNEWLINE into chunks of equal size across the `num_threads` threads. Each threadNEWLINE performs calls map function of the csv file and processes the result.NEWLINE The collector thread, waits for results before posting it to aggregatorNEWLINE service.NEWLINENEWLINE Args:NEWLINE params (dict): Dictionary containing all the parameters for theNEWLINE algorithmNEWLINE data_dir (str): Data directory with csv files.NEWLINE num_threads (int): Number of threadsNEWLINE weights_file (str): Path to the json file containing weights.NEWLINENEWLINE Returns:NEWLINE int: Amount of time required for computation in microseconds.NEWLINENEWLINE """NEWLINE check_environ()NEWLINE csv_files = [os.path.join(NEWLINE os.path.abspath(data_dir), f) for f in os.listdir(data_dir)NEWLINE if f.endswith('.csv')]NEWLINE csv2weights = self._get_weights(csv_files, weights_file)NEWLINE if self.multiprocess:NEWLINE return self._multiprocess(NEWLINE params, num_threads, csv_files, csv2weights)NEWLINE return self._singleprocess(params, csv_files, csv2weights)NEWLINENEWLINE def _get_weights(self, csv_files, weights_file):NEWLINE """Return weights for each user if available, else return 1."""NEWLINE weights = NoneNEWLINE if weights_file:NEWLINE with open(weights_file) as file_path:NEWLINE weights = json.load(file_path)NEWLINE csv2weights = {}NEWLINE for file_path in csv_files:NEWLINE csv_weight = 1 # default weightNEWLINE user = os.path.splitext(os.path.basename(file_path))[0]NEWLINE if weights and user in weights:NEWLINE csv_weight = weights[user]NEWLINE csv2weights[file_path] = csv_weightNEWLINE return csv2weightsNEWLINENEWLINE def _multiprocess(self, params, num_threads, csv_files, csv2weights):NEWLINE # set up parallel processingNEWLINE manager = mp.Manager()NEWLINE writing_queue = manager.Queue()NEWLINE file_queue = manager.Queue()NEWLINE for fpath in csv_files:NEWLINE file_queue.put((fpath, csv2weights[fpath]))NEWLINE jobs = []NEWLINENEWLINE # additional 1 process for writerNEWLINE signal.signal(signal.SIGINT, signal.SIG_IGN)NEWLINE pool = mp.Pool(processes=num_threads + 1)NEWLINE signal.signal(signal.SIGINT, sigint_handler)NEWLINE try:NEWLINE collector_job = pool.apply_async(NEWLINE collector, (writing_queue, params, self.dev_mode))NEWLINENEWLINE # Compute the densityNEWLINE for _ in range(num_threads):NEWLINE jobs.append(pool.apply_async(mapper, (NEWLINE writing_queue, params, file_queue, self.algorithm,NEWLINE self.dev_mode, self.sandboxing)))NEWLINENEWLINE # Clean up parallel processing (close pool, wait for processes toNEWLINE # finish, kill writing_queue, wait for queue to be killed)NEWLINE pool.close()NEWLINE for job in jobs:NEWLINE job.get()NEWLINE writing_queue.put('kill') # stop collectionNEWLINE result = collector_job.get()NEWLINE pool.join()NEWLINE return resultNEWLINE except GracefulExit:NEWLINE pool.terminate()NEWLINE print("Exiting")NEWLINE pool.join()NEWLINE raise RuntimeError("Received interrupt signal, exiting. Bye.")NEWLINENEWLINE def _singleprocess(self, params, csv_files, csv2weights):NEWLINE result_processor = ResultProcessor(params, self.dev_mode)NEWLINE jail = get_jail(python_version=2)NEWLINE for fpath in csv_files:NEWLINE scaler = csv2weights[fpath]NEWLINE result = process_user_csv(NEWLINE params, fpath, self.algorithm, self.dev_mode, self.sandboxing, jail)NEWLINE result_processor(result, scaler=scaler)NEWLINE return result_processor.get_result()NEWLINE |
import jsonNEWLINEfrom controller.client import ClientNEWLINENEWLINENEWLINEdef offerview(user, offer, taking):NEWLINE isvalid = _offer(user, offer, taking)NEWLINE if isvalid:NEWLINE print('A troca foi anunciada')NEWLINE return isvalidNEWLINE else:NEWLINE print('Lamentamos, mas não alguma coisa não está correta (quantidade insuficente ou ID incorreto)')NEWLINE return NoneNEWLINENEWLINENEWLINEdef _offer(user, offer, taking):NEWLINE client = Client()NEWLINE response = client.createTrade(idUser=user.idUser, offer=offer, taking=taking)NEWLINE isvalid = response.responseNEWLINENEWLINE return isvalidNEWLINE |
"""Resnet v1 model variants.NEWLINECode branched out from slim/nets/resnet_v1.py, and please refer to it forNEWLINEmore details.NEWLINEThe original version ResNets-v1 were proposed by:NEWLINE[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian SunNEWLINE Deep Residual Learning for Image Recognition. arXiv:1512.03385NEWLINE"""NEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport functoolsNEWLINEimport tensorflow as tfNEWLINENEWLINEfrom models import resnet_utilsNEWLINEfrom utils.metrics import *NEWLINEfrom utils.loss import *NEWLINEimport warningsNEWLINEwarnings.filterwarnings('ignore')NEWLINEfrom tensorflow.contrib import layersNEWLINEfrom tensorflow.contrib.framework.python.ops import add_arg_scopeNEWLINEfrom tensorflow.contrib.framework.python.ops import arg_scopeNEWLINEfrom tensorflow.contrib.layers.python.layers import utilsNEWLINEfrom tensorflow.contrib.layers.python.layers import regularizersNEWLINENEWLINE_DEFAULT_MULTI_GRID = [1, 1, 1]NEWLINENEWLINEdef update_argparser(parser):NEWLINE parser.set_defaults(NEWLINE train_steps=40000,NEWLINE learning_rate=((20000,30000), (0.0001, 0.00001,0.000001)),NEWLINE save_checkpoints_steps=200,NEWLINE )NEWLINENEWLINENEWLINE@add_arg_scopeNEWLINEdef bottleneck(inputs,NEWLINE depth,NEWLINE depth_bottleneck,NEWLINE stride,NEWLINE unit_rate=1,NEWLINE rate=1,NEWLINE outputs_collections=None,NEWLINE scope=None):NEWLINE """Bottleneck residual unit variant with BN after convolutions.NEWLINE This is the original residual unit proposed in [1]. See Fig. 1(a) of [2] forNEWLINE its definition. Note that we use here the bottleneck variant which has anNEWLINE extra bottleneck layer.NEWLINE When putting together two consecutive ResNet blocks that use this unit, oneNEWLINE should use stride = 2 in the last unit of the first block.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height, width, channels].NEWLINE depth: The depth of the ResNet unit output.NEWLINE depth_bottleneck: The depth of the bottleneck layers.NEWLINE stride: The ResNet unit's stride. Determines the amount of downsampling ofNEWLINE the units output compared to its input.NEWLINE unit_rate: An integer, unit rate for atrous convolution.NEWLINE rate: An integer, rate for atrous convolution.NEWLINE outputs_collections: Collection to add the ResNet unit output.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE The ResNet unit's output.NEWLINE """NEWLINE with tf.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc:NEWLINE depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4)NEWLINE if depth == depth_in:NEWLINE shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')NEWLINE else:NEWLINE shortcut = layers.conv2d(NEWLINE inputs,NEWLINE depth,NEWLINE [1, 1],NEWLINE stride=stride,NEWLINE activation_fn=None,NEWLINE scope='shortcut')NEWLINENEWLINE residual = layers.conv2d(inputs, depth_bottleneck, [1, 1], stride=1,NEWLINE scope='conv1')NEWLINE residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride,NEWLINE rate=rate*unit_rate, scope='conv2')NEWLINE residual = layers.conv2d(residual, depth, [1, 1], stride=1,NEWLINE activation_fn=None, scope='conv3')NEWLINE output = tf.nn.relu(shortcut + residual)NEWLINENEWLINE return utils.collect_named_outputs(outputs_collections,NEWLINE sc.name,NEWLINE output)NEWLINENEWLINENEWLINEdef root_block_fn_for_beta_variant(net):NEWLINE """Gets root_block_fn for beta variant.NEWLINE ResNet-v1 beta variant modifies the first original 7x7 convolution to threeNEWLINE 3x3 convolutions.NEWLINE Args:NEWLINE net: A tensor of size [batch, height, width, channels], input to the model.NEWLINE Returns:NEWLINE A tensor after three 3x3 convolutions.NEWLINE """NEWLINE net = resnet_utils.conv2d_same(net, 64, 3, stride=2, scope='conv1_1')NEWLINE net = resnet_utils.conv2d_same(net, 64, 3, stride=1, scope='conv1_2')NEWLINE net = resnet_utils.conv2d_same(net, 128, 3, stride=1, scope='conv1_3')NEWLINENEWLINE return netNEWLINENEWLINENEWLINEdef resnet_v1_beta(inputs,NEWLINE blocks,NEWLINE num_classes=None,NEWLINE is_training=None,NEWLINE global_pool=True,NEWLINE output_stride=None,NEWLINE root_block_fn=None,NEWLINE scope=None):NEWLINE """Generator for v1 ResNet models (beta variant).NEWLINE This function generates a family of modified ResNet v1 models. In particular,NEWLINE the first original 7x7 convolution is replaced with three 3x3 convolutions.NEWLINE See the resnet_v1_*() methods for specific model instantiations, obtained byNEWLINE selecting different block instantiations that produce ResNets of variousNEWLINE depths.NEWLINE The code is modified from slim/nets/resnet_v1.py, and please refer to it forNEWLINE more details.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height_in, width_in, channels].NEWLINE blocks: A list of length equal to the number of ResNet blocks. Each elementNEWLINE is a resnet_utils.Block object describing the units in the block.NEWLINE num_classes: Number of predicted classes for classification tasks. If NoneNEWLINE we return the features before the logit layer.NEWLINE is_training: Enable/disable is_training for batch normalization.NEWLINE global_pool: If True, we perform global average pooling before computing theNEWLINE logits. Set to True for image classification, False for dense prediction.NEWLINE output_stride: If None, then the output will be computed at the nominalNEWLINE network stride. If output_stride is not None, it specifies the requestedNEWLINE ratio of input to output spatial resolution.NEWLINE root_block_fn: The function consisting of convolution operations applied toNEWLINE the root input. If root_block_fn is None, use the original setting ofNEWLINE RseNet-v1, which is simply one convolution with 7x7 kernel and stride=2.NEWLINE reuse: whether or not the network and its variables should be reused. To beNEWLINE able to reuse 'scope' must be given.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].NEWLINE If global_pool is False, then height_out and width_out are reduced by aNEWLINE factor of output_stride compared to the respective height_in and width_in,NEWLINE else both height_out and width_out equal one. If num_classes is None, thenNEWLINE net is the output of the last ResNet block, potentially after globalNEWLINE average pooling. If num_classes is not None, net contains the pre-softmaxNEWLINE activations.NEWLINE end_points: A dictionary from components of the network to the correspondingNEWLINE activation.NEWLINE Raises:NEWLINE ValueError: If the target output_stride is not valid.NEWLINE """NEWLINE if root_block_fn is None:NEWLINE root_block_fn = functools.partial(resnet_utils.conv2d_same,NEWLINE num_outputs=64,NEWLINE kernel_size=7,NEWLINE stride=2,NEWLINE scope='conv1')NEWLINE with tf.variable_scope(scope, 'resnet_v1', [inputs]) as sc:NEWLINE end_points_collection = sc.original_name_scope + '_end_points'NEWLINE with arg_scope([layers.conv2d, bottleneck,NEWLINE resnet_utils.stack_blocks_dense],NEWLINE outputs_collections=end_points_collection):NEWLINE if is_training is not None:NEWLINE arg_sc = arg_scope([layers.batch_norm], is_training=is_training)NEWLINE else:NEWLINE arg_sc = arg_scope([])NEWLINE with arg_sc:NEWLINE net = inputsNEWLINE if output_stride is not None:NEWLINE if output_stride % 4 != 0:NEWLINE raise ValueError('The output_stride needs to be a multiple of 4.')NEWLINE output_stride /= 4NEWLINE print(str(output_stride) + 'Before resnet blocks')NEWLINE net = root_block_fn(net)NEWLINE net = layers.max_pool2d(net, 3, stride=2, padding='SAME', scope='pool1')NEWLINE net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)NEWLINENEWLINE if global_pool:NEWLINE # Global average pooling.NEWLINE net = tf.reduce_mean(net, [1, 2], name='pool5', keepdims=True)NEWLINE if num_classes is not None:NEWLINE net = layers.conv2d(net, num_classes, [1, 1], activation_fn=None,NEWLINE normalizer_fn=None, scope='logit')NEWLINE # Convert end_points_collection into a dictionary of end_points.NEWLINE end_points = utils.convert_collection_to_dict(end_points_collection)NEWLINE if num_classes is not None:NEWLINE end_points['predictions'] = layers.softmax(net, scope='predictions')NEWLINE return net, end_pointsNEWLINENEWLINENEWLINEdef resnet_v1_beta_block(scope, base_depth, num_units, stride):NEWLINE """Helper function for creating a resnet_v1 beta variant bottleneck block.NEWLINE Args:NEWLINE scope: The scope of the block.NEWLINE base_depth: The depth of the bottleneck layer for each unit.NEWLINE num_units: The number of units in the block.NEWLINE stride: The stride of the block, implemented as a stride in the last unit.NEWLINE All other units have stride=1.NEWLINE Returns:NEWLINE A resnet_v1 bottleneck block.NEWLINE """NEWLINE return resnet_utils.Block(scope, bottleneck, [{NEWLINE 'depth': base_depth * 4,NEWLINE 'depth_bottleneck': base_depth,NEWLINE 'stride': 1,NEWLINE 'unit_rate': 1NEWLINE }] * (num_units - 1) + [{NEWLINE 'depth': base_depth * 4,NEWLINE 'depth_bottleneck': base_depth,NEWLINE 'stride': stride,NEWLINE 'unit_rate': 1NEWLINE }])NEWLINENEWLINEdef resnet_v1_101_beta(inputs,NEWLINE num_classes=None,NEWLINE is_training=None,NEWLINE global_pool=False,NEWLINE output_stride=None,NEWLINE multi_grid=None,NEWLINE scope='resnet_v1_101'):NEWLINE """Resnet v1 101 beta variant.NEWLINE This variant modifies the first convolution layer of ResNet-v1-101. InNEWLINE particular, it changes the original one 7x7 convolution to three 3x3NEWLINE convolutions.NEWLINE Args:NEWLINE inputs: A tensor of size [batch, height_in, width_in, channels].NEWLINE num_classes: Number of predicted classes for classification tasks. If NoneNEWLINE we return the features before the logit layer.NEWLINE is_training: Enable/disable is_training for batch normalization.NEWLINE global_pool: If True, we perform global average pooling before computing theNEWLINE logits. Set to True for image classification, False for dense prediction.NEWLINE output_stride: If None, then the output will be computed at the nominalNEWLINE network stride. If output_stride is not None, it specifies the requestedNEWLINE ratio of input to output spatial resolution.NEWLINE multi_grid: Employ a hierarchy of different atrous rates within network.NEWLINE reuse: whether or not the network and its variables should be reused. To beNEWLINE able to reuse 'scope' must be given.NEWLINE scope: Optional variable_scope.NEWLINE Returns:NEWLINE net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].NEWLINE If global_pool is False, then height_out and width_out are reduced by aNEWLINE factor of output_stride compared to the respective height_in and width_in,NEWLINE else both height_out and width_out equal one. If num_classes is None, thenNEWLINE net is the output of the last ResNet block, potentially after globalNEWLINE average pooling. If num_classes is not None, net contains the pre-softmaxNEWLINE activations.NEWLINE end_points: A dictionary from components of the network to the correspondingNEWLINE activation.NEWLINE Raises:NEWLINE ValueError: if multi_grid is not None and does not have length = 3.NEWLINE """NEWLINE if multi_grid is None:NEWLINE multi_grid = _DEFAULT_MULTI_GRIDNEWLINE else:NEWLINE if len(multi_grid) != 3:NEWLINE raise ValueError('Expect multi_grid to have length 3.')NEWLINENEWLINE blocks = [NEWLINE resnet_v1_beta_block(NEWLINE 'block1', base_depth=64, num_units=3, stride=2),NEWLINE resnet_v1_beta_block(NEWLINE 'block2', base_depth=128, num_units=4, stride=2),NEWLINE resnet_v1_beta_block(NEWLINE 'block3', base_depth=256, num_units=23, stride=2),NEWLINE resnet_utils.Block('block4', bottleneck, [NEWLINE {'depth': 2048,NEWLINE 'depth_bottleneck': 512,NEWLINE 'stride': 1,NEWLINE 'unit_rate': rate} for rate in multi_grid]),NEWLINE ]NEWLINE return resnet_v1_beta(NEWLINE inputs,NEWLINE blocks=blocks,NEWLINE num_classes=num_classes,NEWLINE is_training=is_training,NEWLINE global_pool=global_pool,NEWLINE output_stride=output_stride,NEWLINE root_block_fn=functools.partial(root_block_fn_for_beta_variant),NEWLINE scope=scope)NEWLINENEWLINEdef atrous_spatial_pyramid_pooling(net, scope, output_stride, is_training, weight_decay, depth=256):NEWLINE """NEWLINE ASPP consists of (a) one 1×1 convolution and three 3×3 convolutions with rates = (6, 12, 18) when output stride = 16NEWLINE when output stride = 8, rates are doubledNEWLINE (all with 256 filters and batch normalization), and (b) the image-level features as described in https://arxiv.org/abs/1706.05587NEWLINE :param net: tensor of shape [BATCH_SIZE, WIDTH, HEIGHT, DEPTH]NEWLINE :param scope: scope name of the aspp layerNEWLINE :return: network layer with aspp applyed to it.NEWLINE """NEWLINE if output_stride == 16:NEWLINE rates = [6,12,18]NEWLINE elif output_stride == 8:NEWLINE rates = [12,24,36]NEWLINENEWLINE with tf.variable_scope(scope):NEWLINE batch_norm_params = {NEWLINE 'is_training': is_training,NEWLINE 'decay': 0.9997,NEWLINE 'epsilon': 1e-5,NEWLINE 'scale': True,NEWLINE }NEWLINENEWLINE with arg_scope(NEWLINE [layers.conv2d],NEWLINE # comment next line of code if multiple gpus are usedNEWLINE weights_regularizer=regularizers.l2_regularizer(weight_decay),NEWLINE activation_fn=tf.nn.relu,NEWLINE normalizer_fn=layers.batch_norm,NEWLINE normalizer_params=batch_norm_params):NEWLINE NEWLINE with arg_scope([layers.batch_norm], **batch_norm_params):NEWLINENEWLINE feature_map_size = tf.shape(net)NEWLINE # apply global average poolingNEWLINE image_level_features = tf.reduce_mean(net, [1, 2], name='image_level_global_pool', keepdims=True)NEWLINE image_level_features = layers.conv2d(image_level_features, depth, [1, 1], scope="image_level_conv_1x1",NEWLINE activation_fn=None)NEWLINE image_level_features = tf.image.resize_bilinear(image_level_features, (feature_map_size[1], feature_map_size[2]))NEWLINENEWLINE at_pool1x1 = layers.conv2d(net, depth, [1, 1], scope="conv_1x1_0", activation_fn=None)NEWLINENEWLINE at_pool3x3_1 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_1", rate=rates[0], activation_fn=None)NEWLINENEWLINE at_pool3x3_2 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_2", rate=rates[1], activation_fn=None)NEWLINENEWLINE at_pool3x3_3 = layers.conv2d(net, depth, [3, 3], scope="conv_3x3_3", rate=rates[2], activation_fn=None)NEWLINENEWLINE net = tf.concat((image_level_features, at_pool1x1, at_pool3x3_1, at_pool3x3_2, at_pool3x3_3), axis=3,NEWLINE name="concat")NEWLINE net = layers.conv2d(net, depth, [1, 1], scope="conv_1x1_output", activation_fn=None)NEWLINE net = layers.dropout(net, keep_prob=0.9, is_training=is_training, scope="dropout")NEWLINE return netNEWLINENEWLINE#用@add_arg_scope修饰目标函数NEWLINE#用with arg_scope(...) 设置默认参数.NEWLINEdef deeplab_v3(inputs, args, is_training, output_stride):NEWLINENEWLINE # inputs has shape - Original: [batch, 513, 513, 3]NEWLINE with arg_scope(resnet_utils.resnet_arg_scope(args.l2_regularizer, is_training)):NEWLINE _, end_points = resnet_v1_101_beta(inputs,NEWLINE args.num_classes,NEWLINE is_training=is_training,NEWLINE global_pool=False,NEWLINE output_stride=output_stride,NEWLINE multi_grid=args.multi_grid)NEWLINENEWLINE with tf.variable_scope("DeepLab_v3"):NEWLINENEWLINE # get block 4 feature outputsNEWLINE net = end_points[args.resnet_model + '/block4']NEWLINENEWLINE net = atrous_spatial_pyramid_pooling(net, "ASPP_layer", output_stride, is_training, args.l2_regularizer, depth=256)NEWLINENEWLINE net = layers.conv2d(net, args.num_classes, [1, 1], activation_fn=None,NEWLINE normalizer_fn=None, scope='logits')NEWLINENEWLINE size = tf.shape(inputs)[1:3]NEWLINE # resize the output logits to match the labels dimensionsNEWLINE net = tf.image.resize_bilinear(net, size)NEWLINE return netNEWLINENEWLINEdef model_fn(features, labels, mode, params):NEWLINE ''' Model function'''NEWLINENEWLINE output_stride = NoneNEWLINENEWLINE if mode == tf.estimator.ModeKeys.TRAIN:NEWLINE train = TrueNEWLINE output_stride = params.train_output_strideNEWLINE else:NEWLINE train = FalseNEWLINE output_stride = params.eval_output_strideNEWLINE NEWLINE img_input = tf.reshape(features, [-1, params.crop_size, params.crop_size, 3])NEWLINENEWLINE # Create networkNEWLINE raw_output = deeplab_v3(img_input, params, train, output_stride)NEWLINENEWLINE predictions = tf.argmax(raw_output, axis=-1)NEWLINENEWLINE # Setup the estimator according to the phase (Train, eval)NEWLINE reduced_loss = NoneNEWLINE train_op = NoneNEWLINE eval_metric_ops = {}NEWLINENEWLINE # compute loss(train and eval)NEWLINE loss = softmax_sparse_crossentropy_ignoring_last_label(labels,raw_output)NEWLINENEWLINE # L2 regularizationNEWLINE l2_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)NEWLINENEWLINE # Trainable VariablesNEWLINE #all_trainable = tf.trainable_variables()NEWLINE # L2 regularizationNEWLINE #l2_losses = [params.l2_regularizer * tf.nn.l2_loss(v) for v in all_trainable if 'weights' in v.name]NEWLINENEWLINE # Loss functionNEWLINE reduced_loss = tf.reduce_mean(loss) + tf.add_n(l2_losses)NEWLINENEWLINENEWLINE # evaluation metricNEWLINE miou, update_op = mIOU(raw_output,labels,params.num_classes,img_input)NEWLINENEWLINENEWLINE # configure trainingNEWLINE if mode == tf.estimator.ModeKeys.TRAIN:NEWLINE # piecewise learning rate schedulerNEWLINE global_step = tf.train.get_or_create_global_step()NEWLINE learning_rate = tf.train.piecewise_constant(global_step, params.learning_rate[0], params.learning_rate[1])NEWLINENEWLINE '''NEWLINE # learning rate schedulerNEWLINE global_step = tf.train.get_or_create_global_step()NEWLINE starter_learning_rate = 0.0001NEWLINE end_learning_rate = 0NEWLINE decay_steps = params.train_stepsNEWLINE learning_rate = tf.train.polynomial_decay(starter_learning_rate, global_step,NEWLINE decay_steps, end_learning_rate,NEWLINE power=0.9)NEWLINE '''NEWLINE NEWLINE # SGD + momentum optimizerNEWLINE optimizer = tf.train.MomentumOptimizer(learning_rate,momentum = 0.9)NEWLINE # comment out next two lines if batch norm is frozenNEWLINE # NOTE still need this because aspp needs batch normNEWLINE update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)NEWLINE with tf.control_dependencies(update_ops):NEWLINE train_op = optimizer.minimize(reduced_loss, global_step=tf.train.get_or_create_global_step())NEWLINENEWLINE if mode == tf.estimator.ModeKeys.EVAL:NEWLINE eval_metric_ops = {NEWLINE 'miou': (miou, update_op)NEWLINE }NEWLINENEWLINE return tf.estimator.EstimatorSpec(NEWLINE mode=mode,NEWLINE predictions=predictions,NEWLINE loss=reduced_loss,NEWLINE train_op=train_op,NEWLINE eval_metric_ops=eval_metric_ops,NEWLINE export_outputs=None,NEWLINE )NEWLINE |
import jsonNEWLINEimport osNEWLINENEWLINEimport requestsNEWLINENEWLINENEWLINEclass _SdcCommon(object):NEWLINE '''Interact with the Sysdig Monitor/Secure API.NEWLINENEWLINE **Arguments**NEWLINE - **token**: A Sysdig Monitor/Secure API token from the *Sysdig Cloud API* section of the Settings page for `monitor <https://app.sysdigcloud.com/#/settings/user>`_ or .`secure <https://secure.sysdig.com/#/settings/user>`_.NEWLINE - **sdc_url**: URL for contacting the Sysdig API server. Set this in `On-Premises installs <https://support.sysdigcloud.com/hc/en-us/articles/206519903-On-Premises-Installation-Guide>`__.NEWLINE - **ssl_verify**: Whether to verify certificate. Set to False if using a self-signed certificate in an `On-Premises install <https://support.sysdigcloud.com/hc/en-us/articles/206519903-On-Premises-Installation-Guide>`__.NEWLINE - **custom_headers**: [dict] Pass in custom headers. Useful for authentication and will override the default headers.NEWLINENEWLINE **Returns**NEWLINE An object for further interactions with the Sysdig Monitor/Secure API. See methods below.NEWLINE '''NEWLINE lasterr = NoneNEWLINENEWLINE def __init__(self, token="", sdc_url='https://app.sysdigcloud.com', ssl_verify=True, custom_headers=None):NEWLINE self.token = os.environ.get("SDC_TOKEN", token)NEWLINE self.hdrs = self.__get_headers(custom_headers)NEWLINE self.url = os.environ.get("SDC_URL", sdc_url).rstrip('/')NEWLINE self.ssl_verify = os.environ.get("SDC_SSL_VERIFY", None)NEWLINE if self.ssl_verify == None:NEWLINE self.ssl_verify = ssl_verifyNEWLINE else:NEWLINE if self.ssl_verify.lower() in ['true', 'false']:NEWLINE self.ssl_verify = self.ssl_verify.lower() == 'true'NEWLINENEWLINE def __get_headers(self, custom_headers):NEWLINE headers = {NEWLINE 'Content-Type': 'application/json',NEWLINE 'Authorization': 'Bearer ' + self.tokenNEWLINE }NEWLINE if custom_headers:NEWLINE headers.update(custom_headers)NEWLINE return headersNEWLINENEWLINE def _checkResponse(self, res):NEWLINE if res.status_code >= 300: # FIXME: Should it be >=400? 301 = Moved Permanently, 302 = Found, 303 = See OtherNEWLINE errorcode = res.status_codeNEWLINE self.lasterr = NoneNEWLINENEWLINE try:NEWLINE j = res.json()NEWLINE except Exception:NEWLINE self.lasterr = 'status code ' + str(errorcode)NEWLINE return FalseNEWLINENEWLINE if 'errors' in j:NEWLINE error_msgs = []NEWLINE for error in j['errors']:NEWLINE error_msg = []NEWLINE if 'message' in error:NEWLINE error_msg.append(error['message'])NEWLINENEWLINE if 'reason' in error:NEWLINE error_msg.append(error['reason'])NEWLINENEWLINE error_msgs.append(': '.join(error_msg))NEWLINENEWLINE self.lasterr = '\n'.join(error_msgs)NEWLINE elif 'message' in j:NEWLINE self.lasterr = j['message']NEWLINE else:NEWLINE self.lasterr = 'status code ' + str(errorcode)NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINE def get_user_info(self):NEWLINE '''**Description**NEWLINE Get details about the current user.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary containing information about the user, for example its email and the maximum number of agents it can install.NEWLINENEWLINE **Example**NEWLINE `examples/print_user_info.py <https://github.com/draios/python-sdc-client/blob/master/examples/print_user_info.py>`_NEWLINE '''NEWLINE res = requests.get(self.url + '/api/user/me', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_user_token(self):NEWLINE '''**Description**NEWLINE Return the API token of the current user.NEWLINENEWLINE **Success Return Value**NEWLINE A string containing the user token.NEWLINE '''NEWLINE res = requests.get(self.url + '/api/token', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE tkinfo = res.json()NEWLINENEWLINE return [True, tkinfo['token']['key']]NEWLINENEWLINE def get_connected_agents(self):NEWLINE '''**Description**NEWLINE Return the agents currently connected to Sysdig Monitor for the current user.NEWLINENEWLINE **Success Return Value**NEWLINE A list of the agents with all their attributes.NEWLINE '''NEWLINE res = requests.get(self.url + '/api/agents/connected', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE return [True, data['agents']]NEWLINENEWLINE def get_n_connected_agents(self):NEWLINE '''**Description**NEWLINE Return the number of agents currently connected to Sysdig Monitor for the current user.NEWLINENEWLINE **Success Return Value**NEWLINE An integer number.NEWLINE '''NEWLINE res = requests.get(self.url + '/api/agents/connected', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE return [True, data['total']]NEWLINENEWLINE def list_notification_channels(self):NEWLINE '''**Description**NEWLINE List all configured Notification ChannelsNEWLINENEWLINE **Arguments**NEWLINE noneNEWLINENEWLINE **Success Return Value**NEWLINE A JSON representation of all the notification channelsNEWLINE '''NEWLINE res = requests.get(self.url + '/api/notificationChannels', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_notification_ids(self, channels=None):NEWLINE '''**Description**NEWLINE Get an array of all configured Notification Channel IDs, or a filtered subset of them.NEWLINENEWLINE **Arguments**NEWLINE - **channels**: an optional array of dictionaries to limit the set of Notification Channel IDs returned. If not specified, IDs for all configured Notification Channels are returned. Each dictionary contains a ``type`` field that can be one of the available types of Notification Channel (``EMAIL``, ``SNS``, ``PAGER_DUTY``, ``SLACK``, ``OPSGENIE``, ``VICTOROPS``, ``WEBHOOK``) as well as additional elements specific to each channel type.NEWLINENEWLINE **Success Return Value**NEWLINE An array of Notification Channel IDs (integers).NEWLINENEWLINE **Examples**NEWLINE - `examples/create_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_alert.py>`_NEWLINE - `examples/restore_alerts.py <https://github.com/draios/python-sdc-client/blob/master/examples/restore_alerts.py>`_NEWLINE '''NEWLINENEWLINE res = requests.get(self.url + '/api/notificationChannels', headers=self.hdrs, verify=self.ssl_verify)NEWLINENEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINENEWLINE ids = []NEWLINENEWLINE # If no array of channel types/names was provided to filter by,NEWLINE # just return them all.NEWLINE if channels is None:NEWLINE for ch in res.json()["notificationChannels"]:NEWLINE ids.append(ch['id'])NEWLINE return [True, ids]NEWLINENEWLINE # Return the filtered set of channels based on the provided types/names array.NEWLINE # Should try and improve this M * N lookupNEWLINE for c in channels:NEWLINE found = FalseNEWLINE for ch in res.json()["notificationChannels"]:NEWLINE if c['type'] == ch['type']:NEWLINE if c['type'] == 'SNS':NEWLINE opt = ch['options']NEWLINE if set(opt['snsTopicARNs']) == set(c['snsTopicARNs']):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'EMAIL':NEWLINE opt = ch['options']NEWLINE if 'emailRecipients' in c:NEWLINE if set(c['emailRecipients']) == set(opt['emailRecipients']):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'PAGER_DUTY':NEWLINE opt = ch['options']NEWLINE if opt['account'] == c['account'] and opt['serviceName'] == c['serviceName']:NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'SLACK':NEWLINE if 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'OPSGENIE':NEWLINE if 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'VICTOROPS':NEWLINE if 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE elif c['type'] == 'WEBHOOK':NEWLINE if 'name' in c:NEWLINE if c['name'] == ch.get('name'):NEWLINE found = TrueNEWLINE ids.append(ch['id'])NEWLINE if not found:NEWLINE return False, "Channel not found: " + str(c)NEWLINENEWLINE return True, idsNEWLINENEWLINE def create_email_notification_channel(self, channel_name, email_recipients):NEWLINE channel_json = {NEWLINE 'notificationChannel': {NEWLINE 'type': 'EMAIL',NEWLINE 'name': channel_name,NEWLINE 'enabled': True,NEWLINE 'options': {NEWLINE 'emailRecipients': email_recipientsNEWLINE }NEWLINE }NEWLINE }NEWLINENEWLINE res = requests.post(self.url + '/api/notificationChannels', headers=self.hdrs, data=json.dumps(channel_json),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def create_notification_channel(self, channel):NEWLINE channel["id"] = NoneNEWLINE channel["version"] = NoneNEWLINE channel["createdOn"] = NoneNEWLINE channel["modifiedOn"] = NoneNEWLINE channel_json = {NEWLINE 'notificationChannel': channelNEWLINE }NEWLINENEWLINE res = requests.post(self.url + '/api/notificationChannels', headers=self.hdrs, data=json.dumps(channel_json),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_notification_channel(self, id):NEWLINENEWLINE res = requests.get(self.url + '/api/notificationChannels/' + str(id), headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINENEWLINE return True, res.json()['notificationChannel']NEWLINENEWLINE def update_notification_channel(self, channel):NEWLINE if 'id' not in channel:NEWLINE return [False, "Invalid channel format"]NEWLINENEWLINE res = requests.put(self.url + '/api/notificationChannels/' + str(channel['id']), headers=self.hdrs,NEWLINE data=json.dumps({"notificationChannel": channel}), verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def delete_notification_channel(self, channel):NEWLINE if 'id' not in channel:NEWLINE return [False, "Invalid channel format"]NEWLINENEWLINE res = requests.delete(self.url + '/api/notificationChannels/' + str(channel['id']), headers=self.hdrs,NEWLINE verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINE return True, NoneNEWLINENEWLINE def get_data_retention_info(self):NEWLINE '''**Description**NEWLINE Return the list of data retention intervals, with beginning and end UTC time for each of them. Sysdig Monitor performs rollups of the data it stores. This means that data is stored at different time granularities depending on how far back in time it is. This call can be used to know what precision you can expect before you make a call to :func:`~SdcClient.get_data`.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary containing the list of available sampling intervals.NEWLINENEWLINE **Example**NEWLINE `examples/print_data_retention_info.py <https://github.com/draios/python-sdc-client/blob/master/examples/print_data_retention_info.py>`_NEWLINE '''NEWLINE res = requests.get(self.url + '/api/history/timelines/', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_topology_map(self, grouping_hierarchy, time_window_s, sampling_time_s):NEWLINE #NEWLINE # Craft the time interval sectionNEWLINE #NEWLINE tlines = self.get_data_retention_info()NEWLINENEWLINE for tline in tlines[1]['agents']:NEWLINE if tline['sampling'] == sampling_time_s * 1000000:NEWLINE timeinfo = tlineNEWLINENEWLINE if timeinfo is None:NEWLINE return [False, "sampling time " + str(sampling_time_s) + " not supported"]NEWLINENEWLINE timeinfo['from'] = timeinfo['to'] - timeinfo['sampling']NEWLINENEWLINE #NEWLINE # Create the grouping hierarchyNEWLINE #NEWLINE gby = [{'metric': g} for g in grouping_hierarchy]NEWLINENEWLINE #NEWLINE # Prepare the jsonNEWLINE #NEWLINE req_json = {NEWLINE 'format': {NEWLINE 'type': 'map',NEWLINE 'exportProcess': TrueNEWLINE },NEWLINE 'time': timeinfo,NEWLINE # 'filter': {NEWLINE # 'filters': [NEWLINE # {NEWLINE # 'metric': 'agent.tag.Tag',NEWLINE # 'op': '=',NEWLINE # 'value': 'production-maintenance',NEWLINE # 'filters': NoneNEWLINE # }NEWLINE # ],NEWLINE # 'logic': 'and'NEWLINE # },NEWLINE 'limit': {NEWLINE 'hostGroups': 20,NEWLINE 'hosts': 20,NEWLINE 'containers': 20,NEWLINE 'processes': 10NEWLINE },NEWLINE 'group': {NEWLINE 'configuration': {NEWLINE 'groups': [NEWLINE {NEWLINE 'filters': [],NEWLINE 'groupBy': gbyNEWLINE }NEWLINE ]NEWLINE }NEWLINE },NEWLINE 'nodeMetrics': [NEWLINE {NEWLINE 'id': 'cpu.used.percent',NEWLINE 'aggregation': 'timeAvg',NEWLINE 'groupAggregation': 'avg'NEWLINE }NEWLINE ],NEWLINE 'linkMetrics': [NEWLINE {NEWLINE 'id': 'net.bytes.total',NEWLINE 'aggregation': 'timeAvg',NEWLINE 'groupAggregation': 'sum'NEWLINE }NEWLINE ]NEWLINE }NEWLINENEWLINE #NEWLINE # Fire the requestNEWLINE #NEWLINE res = requests.post(self.url + '/api/data?format=map', headers=self.hdrs,NEWLINE data=json.dumps(req_json), verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_data(self, metrics, start_ts, end_ts=0, sampling_s=0,NEWLINE filter='', datasource_type='host', paging=None):NEWLINE '''**Description**NEWLINE Export metric data (both time-series and table-based).NEWLINENEWLINE **Arguments**NEWLINE - **metrics**: a list of dictionaries, specifying the metrics and grouping keys that the query will return. A metric is any of the entries that can be found in the *Metrics* section of the Explore page in Sysdig Monitor. Metric entries require an *aggregations* section specifying how to aggregate the metric across time and containers/hosts. A grouping key is any of the entries that can be found in the *Show* or *Segment By* sections of the Explore page in Sysdig Monitor. These entries are used to apply single or hierarchical segmentation to the returned data and don't require the aggregations section. Refer to the Example link below for ready-to-use code snippets.NEWLINE - **start_ts**: the UTC time (in seconds) of the beginning of the data window. A negative value can be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago".NEWLINE - **end_ts**: the UTC time (in seconds) of the end of the data window, or 0 to indicate "now". A negative value can also be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago".NEWLINE - **sampling_s**: the duration of the samples that will be returned. 0 means that the whole data will be returned as a single sample.NEWLINE - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the query will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*.NEWLINE - **datasource_type**: specify the metric source for the request, can be ``container`` or ``host``. Most metrics, for example ``cpu.used.percent`` or ``memory.bytes.used``, are reported by both hosts and containers. By default, host metrics are used, but if the request contains a container-specific grouping key in the metric list/filter (e.g. ``container.name``), then the container source is used. In cases where grouping keys are missing or apply to both hosts and containers (e.g. ``tag.Name``), *datasource_type* can be explicitly set to avoid any ambiguity and allow the user to select precisely what kind of data should be used for the request. `examples/get_data_datasource.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_datasource.py>`_ contains a few examples that should clarify the use of this argument.NEWLINE - **paging**: if segmentation of the query generates values for several different entities (e.g. containers/hosts), this parameter specifies which to include in the returned result. It's specified as a dictionary of inclusive values for ``from`` and ``to`` with the default being ``{ "from": 0, "to": 9 }``, which will return values for the "top 10" entities. The meaning of "top" is query-dependent, based on points having been sorted via the specified group aggregation, with the results sorted in ascending order if the group aggregation is ``min`` or ``none``, and descending order otherwise.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary with the requested data. Data is organized in a list of time samples, each of which includes a UTC timestamp and a list of values, whose content and order reflect what was specified in the *metrics* argument.NEWLINENEWLINE **Examples**NEWLINE - `examples/get_data_simple.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_simple.py>`_NEWLINE - `examples/get_data_advanced.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_advanced.py>`_NEWLINE - `examples/list_hosts.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_hosts.py>`_NEWLINE - `examples/get_data_datasource.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_datasource.py>`_NEWLINE '''NEWLINE reqbody = {NEWLINE 'metrics': metrics,NEWLINE 'dataSourceType': datasource_type,NEWLINE }NEWLINENEWLINE if start_ts < 0:NEWLINE reqbody['last'] = -start_tsNEWLINE elif start_ts == 0:NEWLINE return [False, "start_ts cannot be 0"]NEWLINE else:NEWLINE reqbody['start'] = start_tsNEWLINE reqbody['end'] = end_tsNEWLINENEWLINE if filter != '':NEWLINE reqbody['filter'] = filterNEWLINENEWLINE if paging is not None:NEWLINE reqbody['paging'] = pagingNEWLINENEWLINE if sampling_s != 0:NEWLINE reqbody['sampling'] = sampling_sNEWLINENEWLINE res = requests.post(self.url + '/api/data/', headers=self.hdrs, data=json.dumps(reqbody),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_sysdig_captures(self, from_sec=None, to_sec=None, scope_filter=None):NEWLINE '''**Description**NEWLINE Returns the list of sysdig captures for the user.NEWLINENEWLINE **Arguments**NEWLINE - from_sec: the start of the timerange for which to get the capturesNEWLINE - end_sec: the end of the timerange for which to get the capturesNEWLINE - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container).NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary containing the list of captures.NEWLINENEWLINE **Example**NEWLINE `examples/list_sysdig_captures.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_sysdig_captures.py>`_NEWLINE '''NEWLINE url = '{url}/api/sysdig?source={source}{frm}{to}{scopeFilter}'.format(NEWLINE url=self.url,NEWLINE source=self.product,NEWLINE frm="&from=%d" % (from_sec * 10 ** 6) if from_sec else "",NEWLINE to="&to=%d" % (to_sec * 10 ** 6) if to_sec else "",NEWLINE scopeFilter="&scopeFilter=%s" % scope_filter if scope_filter else "")NEWLINE res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def poll_sysdig_capture(self, capture):NEWLINE '''**Description**NEWLINE Fetch the updated state of a sysdig capture. Can be used to poll the status of a capture that has been previously created and started with :func:`~SdcClient.create_sysdig_capture`.NEWLINENEWLINE **Arguments**NEWLINE - **capture**: the capture object as returned by :func:`~SdcClient.get_sysdig_captures` or :func:`~SdcClient.create_sysdig_capture`.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary showing the updated details of the capture. Use the ``status`` field to check the progress of a capture.NEWLINENEWLINE **Example**NEWLINE `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_NEWLINE '''NEWLINE if 'id' not in capture:NEWLINE return [False, 'Invalid capture format']NEWLINENEWLINE url = '{url}/api/sysdig/{id}?source={source}'.format(NEWLINE url=self.url, id=capture['id'], source=self.product)NEWLINE res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def create_sysdig_capture(self, hostname, capture_name, duration, capture_filter='', folder='/'):NEWLINE '''**Description**NEWLINE Create a new sysdig capture. The capture will be immediately started.NEWLINENEWLINE **Arguments**NEWLINE - **hostname**: the hostname of the instrumented host where the capture will be taken.NEWLINE - **capture_name**: the name of the capture.NEWLINE - **duration**: the duration of the capture, in seconds.NEWLINE - **capture_filter**: a sysdig filter expression.NEWLINE - **folder**: directory in the S3 bucket where the capture will be saved.NEWLINENEWLINE **Success Return Value**NEWLINE A dictionary showing the details of the new capture.NEWLINENEWLINE **Example**NEWLINE `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_NEWLINE '''NEWLINE res = self.get_connected_agents()NEWLINE if not res[0]:NEWLINE return resNEWLINENEWLINE capture_agent = NoneNEWLINENEWLINE for agent in res[1]:NEWLINE if hostname == agent['hostName']:NEWLINE capture_agent = agentNEWLINE breakNEWLINENEWLINE if capture_agent is None:NEWLINE return [False, hostname + ' not found']NEWLINENEWLINE data = {NEWLINE 'agent': capture_agent,NEWLINE 'name': capture_name,NEWLINE 'duration': duration,NEWLINE 'folder': folder,NEWLINE 'filters': capture_filter,NEWLINE 'bucketName': '',NEWLINE 'source': self.productNEWLINE }NEWLINENEWLINE res = requests.post(self.url + '/api/sysdig', headers=self.hdrs, data=json.dumps(data), verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def download_sysdig_capture(self, capture_id):NEWLINE '''**Description**NEWLINE Download a sysdig capture by id.NEWLINENEWLINE **Arguments**NEWLINE - **capture_id**: the capture id to download.NEWLINENEWLINE **Success Return Value**NEWLINE The bytes of the scapNEWLINE '''NEWLINE url = '{url}/api/sysdig/{id}/download?_product={product}'.format(NEWLINE url=self.url, id=capture_id, product=self.product)NEWLINE res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINENEWLINE return True, res.contentNEWLINENEWLINE def create_user_invite(self, user_email, first_name=None, last_name=None, system_role=None):NEWLINE '''**Description**NEWLINE Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address.NEWLINENEWLINE **Arguments**NEWLINE - **user_email**: the email address of the user that will be invited to use Sysdig MonitorNEWLINE - **first_name**: the first name of the user being invitedNEWLINE - **last_name**: the last name of the user being invitedNEWLINE - **system_role**: system-wide privilege level for this user regardless of team. specify 'ROLE_CUSTOMER' to create an Admin. if not specified, default is a non-Admin ('ROLE_USER').NEWLINENEWLINE **Success Return Value**NEWLINE The newly created user.NEWLINENEWLINE **Examples**NEWLINE - `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_NEWLINE - `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_NEWLINENEWLINE '''NEWLINE # Look up the list of users to see if this exists, do not create if one existsNEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE for user in data['users']:NEWLINE if user['username'] == user_email:NEWLINE return [False, 'user ' + user_email + ' already exists']NEWLINENEWLINE # Create the userNEWLINE options = {'username': user_email,NEWLINE 'firstName': first_name,NEWLINE 'lastName': last_name,NEWLINE 'systemRole': system_role}NEWLINE user_json = {k: v for k, v in options.items() if v is not None}NEWLINENEWLINE res = requests.post(self.url + '/api/users', headers=self.hdrs, data=json.dumps(user_json),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def delete_user(self, user_email):NEWLINE '''**Description**NEWLINE Deletes a user from Sysdig Monitor.NEWLINENEWLINE **Arguments**NEWLINE - **user_email**: the email address of the user that will be deleted from Sysdig MonitorNEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_NEWLINE '''NEWLINE res = self.get_user_ids([user_email])NEWLINE if res[0] == False:NEWLINE return resNEWLINE userid = res[1][0]NEWLINE res = requests.delete(self.url + '/api/users/' + str(userid), headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE return [True, None]NEWLINENEWLINE def get_user(self, user_email):NEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE for u in res.json()['users']:NEWLINE if u['username'] == user_email:NEWLINE return [True, u]NEWLINE return [False, 'User not found']NEWLINENEWLINE def get_users(self):NEWLINE '''**Description**NEWLINE Return a list containing details about all users in the Sysdig Monitor environment. The API token must have Admin rights for this to succeed.NEWLINENEWLINE **Success Return Value**NEWLINE A list user objectsNEWLINE '''NEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE return [True, res.json()['users']]NEWLINENEWLINE def edit_user(self, user_email, firstName=None, lastName=None, systemRole=None):NEWLINE res = self.get_user(user_email)NEWLINE if res[0] == False:NEWLINE return resNEWLINE user = res[1]NEWLINE reqbody = {NEWLINE 'systemRole': systemRole if systemRole else user['systemRole'],NEWLINE 'username': user_email,NEWLINE 'enabled': user.get('enabled', False),NEWLINE 'version': user['version']NEWLINE }NEWLINENEWLINE if firstName == None:NEWLINE reqbody['firstName'] = user['firstName'] if 'firstName' in list(user.keys()) else ''NEWLINE else:NEWLINE reqbody['firstName'] = firstNameNEWLINENEWLINE if lastName == None:NEWLINE reqbody['lastName'] = user['lastName'] if 'lastName' in list(user.keys()) else ''NEWLINE else:NEWLINE reqbody['lastName'] = lastNameNEWLINENEWLINE res = requests.put(self.url + '/api/users/' + str(user['id']), headers=self.hdrs, data=json.dumps(reqbody),NEWLINE verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE return [True, 'Successfully edited user']NEWLINENEWLINE def get_teams(self, team_filter=''):NEWLINE '''**Description**NEWLINE Return the set of teams that match the filter specified. The *team_filter* should be a substring of the names of the teams to be returned.NEWLINENEWLINE **Arguments**NEWLINE - **team_filter**: the team filter to match when returning the list of teamsNEWLINENEWLINE **Success Return Value**NEWLINE The teams that match the filter.NEWLINE '''NEWLINE res = requests.get(self.url + '/api/teams', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE ret = [t for t in res.json()['teams'] if team_filter in t['name']]NEWLINE return [True, ret]NEWLINENEWLINE def get_team(self, name):NEWLINE '''**Description**NEWLINE Return the team with the specified team name, if it is present.NEWLINENEWLINE **Arguments**NEWLINE - **name**: the name of the team to returnNEWLINENEWLINE **Success Return Value**NEWLINE The requested team.NEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_NEWLINE '''NEWLINE res = self.get_teams(name)NEWLINE if res[0] == False:NEWLINE return resNEWLINE for t in res[1]:NEWLINE if t['name'] == name:NEWLINE return [True, t]NEWLINE return [False, 'Could not find team']NEWLINENEWLINE def get_team_ids(self, teams):NEWLINE res = requests.get(self.url + '/api/teams', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE u = [x for x in res.json()['teams'] if x['name'] in teams]NEWLINE return [True, [x['id'] for x in u]]NEWLINENEWLINE def _get_user_id_dict(self, users):NEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE u = [x for x in res.json()['users'] if x['username'] in users]NEWLINE return [True, dict((user['username'], user['id']) for user in u)]NEWLINENEWLINE def _get_id_user_dict(self, user_ids):NEWLINE res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE u = [x for x in res.json()['users'] if x['id'] in user_ids]NEWLINE return [True, dict((user['id'], user['username']) for user in u)]NEWLINENEWLINE def get_user_ids(self, users):NEWLINE res = self._get_user_id_dict(users)NEWLINE if res[0] == False:NEWLINE return resNEWLINE else:NEWLINE return [True, list(res[1].values())]NEWLINENEWLINE def create_team(self, name, memberships=None, filter='', description='', show='host', theme='#7BB0B2',NEWLINE perm_capture=False, perm_custom_events=False, perm_aws_data=False):NEWLINE '''NEWLINE **Description**NEWLINE Creates a new teamNEWLINENEWLINE **Arguments**NEWLINE - **name**: the name of the team to create.NEWLINE - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team.NEWLINE - **filter**: the scope that this team is able to access within Sysdig Monitor.NEWLINE - **description**: describes the team that will be created.NEWLINE - **show**: possible values are *host*, *container*.NEWLINE - **theme**: the color theme that Sysdig Monitor will use when displaying the team.NEWLINE - **perm_capture**: if True, this team will be allowed to take sysdig captures.NEWLINE - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent.NEWLINE - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope.NEWLINENEWLINE **Success Return Value**NEWLINE The newly created team.NEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_NEWLINE '''NEWLINE reqbody = {NEWLINE 'name': name,NEWLINE 'description': description,NEWLINE 'theme': theme,NEWLINE 'show': show,NEWLINE 'canUseSysdigCapture': perm_capture,NEWLINE 'canUseCustomEvents': perm_custom_events,NEWLINE 'canUseAwsMetrics': perm_aws_data,NEWLINE }NEWLINENEWLINE # Map user-names to IDsNEWLINE if memberships != None and len(memberships) != 0:NEWLINE res = self._get_user_id_dict(list(memberships.keys()))NEWLINE if res[0] == False:NEWLINE return [False, 'Could not fetch IDs for user names']NEWLINE reqbody['userRoles'] = [NEWLINE {NEWLINE 'userId': user_id,NEWLINE 'role': memberships[user_name]NEWLINE }NEWLINE for (user_name, user_id) in res[1].items()NEWLINE ]NEWLINE else:NEWLINE reqbody['users'] = []NEWLINENEWLINE if filter != '':NEWLINE reqbody['filter'] = filterNEWLINENEWLINE res = requests.post(self.url + '/api/teams', headers=self.hdrs, data=json.dumps(reqbody),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def edit_team(self, name, memberships=None, filter=None, description=None, show=None, theme=None,NEWLINE perm_capture=None, perm_custom_events=None, perm_aws_data=None):NEWLINE '''NEWLINE **Description**NEWLINE Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at their current settings.NEWLINENEWLINE **Arguments**NEWLINE - **name**: the name of the team to edit.NEWLINE - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team.NEWLINE - **filter**: the scope that this team is able to access within Sysdig Monitor.NEWLINE - **description**: describes the team that will be created.NEWLINE - **show**: possible values are *host*, *container*.NEWLINE - **theme**: the color theme that Sysdig Monitor will use when displaying the team.NEWLINE - **perm_capture**: if True, this team will be allowed to take sysdig captures.NEWLINE - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent.NEWLINE - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope.NEWLINENEWLINE **Success Return Value**NEWLINE The edited team.NEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_NEWLINE '''NEWLINE res = self.get_team(name)NEWLINE if res[0] == False:NEWLINE return resNEWLINENEWLINE t = res[1]NEWLINE reqbody = {NEWLINE 'name': name,NEWLINE 'theme': theme if theme else t['theme'],NEWLINE 'show': show if show else t['show'],NEWLINE 'canUseSysdigCapture': perm_capture if perm_capture else t['canUseSysdigCapture'],NEWLINE 'canUseCustomEvents': perm_custom_events if perm_custom_events else t['canUseCustomEvents'],NEWLINE 'canUseAwsMetrics': perm_aws_data if perm_aws_data else t['canUseAwsMetrics'],NEWLINE 'id': t['id'],NEWLINE 'version': t['version']NEWLINE }NEWLINENEWLINE # Handling team descriptionNEWLINE if description is not None:NEWLINE reqbody['description'] = descriptionNEWLINE elif 'description' in list(t.keys()):NEWLINE reqbody['description'] = t['description']NEWLINENEWLINE # Handling for users to map (user-name, team-role) pairs to membershipsNEWLINE if memberships != None:NEWLINE res = self._get_user_id_dict(list(memberships.keys()))NEWLINE if res[0] == False:NEWLINE return [False, 'Could not convert user names to IDs']NEWLINE reqbody['userRoles'] = [NEWLINE {NEWLINE 'userId': user_id,NEWLINE 'role': memberships[user_name]NEWLINE }NEWLINE for (user_name, user_id) in res[1].items()NEWLINE ]NEWLINE elif 'userRoles' in list(t.keys()):NEWLINE reqbody['userRoles'] = t['userRoles']NEWLINE else:NEWLINE reqbody['userRoles'] = []NEWLINENEWLINE # Special handling for filters since we don't support blank filtersNEWLINE if filter != None:NEWLINE reqbody['filter'] = filterNEWLINE elif 'filter' in list(t.keys()):NEWLINE reqbody['filter'] = t['filter']NEWLINENEWLINE res = requests.put(self.url + '/api/teams/' + str(t['id']), headers=self.hdrs, data=json.dumps(reqbody),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def delete_team(self, name):NEWLINE '''**Description**NEWLINE Deletes a team from Sysdig Monitor.NEWLINENEWLINE **Arguments**NEWLINE - **name**: the name of the team that will be deleted from Sysdig MonitorNEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_NEWLINE '''NEWLINE res = self.get_team(name)NEWLINE if res[0] == False:NEWLINE return resNEWLINENEWLINE t = res[1]NEWLINE res = requests.delete(self.url + '/api/teams/' + str(t['id']), headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE return [True, None]NEWLINENEWLINE def list_memberships(self, team):NEWLINE '''NEWLINE **Description**NEWLINE List all memberships for specified team.NEWLINENEWLINE **Arguments**NEWLINE - **team**: the name of the team for which we want to see membershipsNEWLINENEWLINE **Result**NEWLINE Dictionary of (user-name, team-role) pairs that should describe memberships of the team.NEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_NEWLINE '''NEWLINE res = self.get_team(team)NEWLINE if res[0] == False:NEWLINE return resNEWLINENEWLINE raw_memberships = res[1]['userRoles']NEWLINE user_ids = [m['userId'] for m in raw_memberships]NEWLINENEWLINE res = self._get_id_user_dict(user_ids)NEWLINE if res[0] == False:NEWLINE return [False, 'Could not fetch IDs for user names']NEWLINE else:NEWLINE id_user_dict = res[1]NEWLINENEWLINE return [True, dict([(id_user_dict[m['userId']], m['role']) for m in raw_memberships])]NEWLINENEWLINE def save_memberships(self, team, memberships):NEWLINE '''NEWLINE **Description**NEWLINE Create new user team memberships or update existing ones.NEWLINENEWLINE **Arguments**NEWLINE - **team**: the name of the team for which we are creating new membershipsNEWLINE - **memberships**: dictionary of (user-name, team-role) pairs that should describe new membershipsNEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_NEWLINE '''NEWLINENEWLINE res = self.list_memberships(team)NEWLINENEWLINE if res[0] is False:NEWLINE return resNEWLINENEWLINE full_memberships = res[1]NEWLINE full_memberships.update(memberships)NEWLINENEWLINE res = self.edit_team(team, full_memberships)NEWLINENEWLINE if res[0] is False:NEWLINE return resNEWLINE else:NEWLINE return [True, None]NEWLINENEWLINE def remove_memberships(self, team, users):NEWLINE '''NEWLINE **Description**NEWLINE Remove user memberships from specified team.NEWLINENEWLINE **Arguments**NEWLINE - **team**: the name of the team from which user memberships are removedNEWLINE - **users**: list of usernames which should be removed from teamNEWLINENEWLINE **Example**NEWLINE `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_NEWLINE '''NEWLINENEWLINE res = self.list_memberships(team)NEWLINENEWLINE if res[0] is False:NEWLINE return resNEWLINENEWLINE old_memberships = res[1]NEWLINE new_memberships = {k: v for k, v in old_memberships.items() if k not in users}NEWLINENEWLINE res = self.edit_team(team, new_memberships)NEWLINENEWLINE if res[0] is False:NEWLINE return resNEWLINE else:NEWLINE return [True, None]NEWLINENEWLINE def list_access_keys(self):NEWLINE '''NEWLINE **Description**NEWLINE List all the access keys enabled and disabled for this instance of Sysdig Monitor/SecureNEWLINENEWLINE **Reslut**NEWLINE A list of access keys objectsNEWLINENEWLINE **Example**NEWLINE `examples/list_access_keys.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_access_keys.py>`_NEWLINE '''NEWLINE res = requests.get(self.url + '/api/customer/accessKeys', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def create_access_key(self):NEWLINE '''NEWLINE **Description**NEWLINE Create a new access key for Sysdig Monitor/SecureNEWLINENEWLINE **Reslut**NEWLINE The access keys objectNEWLINE '''NEWLINE res = requests.post(self.url + '/api/customer/accessKeys', headers=self.hdrs, verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def disable_access_key(self, access_key):NEWLINE '''NEWLINE **Description**NEWLINE Disable an existing access keyNEWLINENEWLINE **Arguments**NEWLINE - **access_key**: the access key to be disabledNEWLINENEWLINE **Reslut**NEWLINE The access keys objectNEWLINE '''NEWLINE res = requests.post(self.url + '/api/customer/accessKeys/' + access_key + "/disable/", headers=self.hdrs,NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def enable_access_key(self, access_key):NEWLINE '''NEWLINE **Description**NEWLINE Enable an existing access keyNEWLINENEWLINE **Arguments**NEWLINE - **access_key**: the access key to be enabledNEWLINENEWLINE **Reslut**NEWLINE The access keys objectNEWLINE '''NEWLINE res = requests.post(self.url + '/api/customer/accessKeys/' + access_key + "/enable/", headers=self.hdrs,NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def get_agents_config(self):NEWLINE res = requests.get(self.url + '/api/agents/config', headers=self.hdrs, verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE return [True, data]NEWLINENEWLINE def set_agents_config(self, config):NEWLINE res = requests.put(self.url + '/api/agents/config', headers=self.hdrs, data=json.dumps(config),NEWLINE verify=self.ssl_verify)NEWLINE return self._request_result(res)NEWLINENEWLINE def clear_agents_config(self):NEWLINE data = {'files': []}NEWLINE return self.set_agents_config(data)NEWLINENEWLINE def get_user_api_token(self, username, teamname):NEWLINE res = self.get_team(teamname)NEWLINE if res[0] == False:NEWLINE return resNEWLINENEWLINE t = res[1]NEWLINENEWLINE res = requests.get(self.url + '/api/token/%s/%d' % (username, t['id']), headers=self.hdrs,NEWLINE verify=self.ssl_verify)NEWLINE if not self._checkResponse(res):NEWLINE return [False, self.lasterr]NEWLINE data = res.json()NEWLINE return [True, data['token']['key']]NEWLINENEWLINE def _request_result(self, res):NEWLINE if not self._checkResponse(res):NEWLINE return False, self.lasterrNEWLINENEWLINE return True, res.json()NEWLINE |
# Generated by Django 3.2.4 on 2021-06-06 05:11NEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ("farm", "0001_initial"),NEWLINE migrations.swappable_dependency(settings.AUTH_USER_MODEL),NEWLINE ("geometry", "0001_initial"),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name="Plot",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "name",NEWLINE models.CharField(NEWLINE blank=True, default="Unnamed Plot", max_length=128NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "description",NEWLINE models.CharField(blank=True, default="", max_length=1024),NEWLINE ),NEWLINE (NEWLINE "type",NEWLINE models.CharField(NEWLINE blank=True,NEWLINE choices=[NEWLINE ("F", "field"),NEWLINE ("W", "forest"),NEWLINE ("G", "garden"),NEWLINE ("O", "orchard"),NEWLINE ("P", "pasture"),NEWLINE ("S", "silvopasture"),NEWLINE ],NEWLINE default=None,NEWLINE max_length=1,NEWLINE null=True,NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "farm",NEWLINE models.ForeignKey(NEWLINE on_delete=django.db.models.deletion.CASCADE, to="farm.farm"NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "farmer",NEWLINE models.ForeignKey(NEWLINE on_delete=django.db.models.deletion.CASCADE,NEWLINE to=settings.AUTH_USER_MODEL,NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "parent",NEWLINE models.ForeignKey(NEWLINE blank=True,NEWLINE null=True,NEWLINE on_delete=django.db.models.deletion.CASCADE,NEWLINE to="plot.plot",NEWLINE ),NEWLINE ),NEWLINE (NEWLINE "shape",NEWLINE models.ForeignKey(NEWLINE default=None,NEWLINE null=True,NEWLINE on_delete=django.db.models.deletion.CASCADE,NEWLINE to="geometry.shape",NEWLINE ),NEWLINE ),NEWLINE ],NEWLINE options={NEWLINE "db_table": "plot",NEWLINE },NEWLINE ),NEWLINE ]NEWLINE |
# iterator objects implement __iter__ and __next__ methodsNEWLINENEWLINEl = [3, 54,32, 'name']NEWLINEl_iterator = iter(l)NEWLINENEWLINE#print(l_iterator)NEWLINE#print(next(l_iterator))NEWLINE#print(next(l_iterator))NEWLINE#print(next(l_iterator))NEWLINE#print(next(l_iterator))NEWLINE#print(next(l_iterator))NEWLINENEWLINEstring = 'this is a string'NEWLINEs_iterator = iter(string)NEWLINENEWLINEfor a in s_iterator:NEWLINE print(a)NEWLINENEWLINEnumber = 3940NEWLINEnumber_iterator = iter(3940) |
'''NEWLINEFile name: common_utils.pyNEWLINEProgrammed by: Mike BernardNEWLINEDate: 2019-11-08NEWLINENEWLINECommon helper functions used in multiple scripts.NEWLINE'''NEWLINENEWLINEfrom nav.utils.constants import PASSNEWLINENEWLINENEWLINEdef weighted_avg(values, weights):NEWLINE '''NEWLINE Takes a list of values and a list of weights associatedNEWLINE with those values (index-to-index) and returns a weightedNEWLINE averaged of those values as a float.NEWLINENEWLINE :param values: `list` of values to be averagedNEWLINE :param weights: `list` of weights for each value (index-to-index)NEWLINENEWLINE :return: `float` The weighted average of the valuesNEWLINE '''NEWLINE denom = sum([1 / w ** 2 for w in weights])NEWLINE num = sum([1 / w ** 2 * v for v, w in zip(values, weights)])NEWLINENEWLINE return num / denomNEWLINENEWLINENEWLINEdef unit_test(module_name, tests):NEWLINE '''NEWLINE Run a set of test functions and print out the results.NEWLINE See test directory for examples of how to structure these testsNEWLINE and how to set up calling this function.NEWLINE NEWLINE :param module_name: `str` the name of the module being testedNEWLINE :param tests: `list` of functions to test as objectsNEWLINE '''NEWLINE passed = 0NEWLINE failed = 0NEWLINE fail_messages = []NEWLINENEWLINE for test in tests:NEWLINE status, description = test()NEWLINE if status == PASS:NEWLINE passed += 1NEWLINE else:NEWLINE failed += 1NEWLINE fail_messages.append(description)NEWLINENEWLINE print(module_name, 'unit test results: ', end='')NEWLINE print('{} out of {} tests passed.'.format(passed, len(tests)))NEWLINE if len(fail_messages) > 0:NEWLINE print('Failed tests:')NEWLINE for msg in fail_messages:NEWLINE print('\t' + msg)NEWLINE |
#!/usr/bin/env pythonNEWLINENEWLINE"""NEWLINEFill the "Player" table with info from this and past seasonss FPLNEWLINE"""NEWLINEimport osNEWLINENEWLINEimport jsonNEWLINENEWLINEfrom airsenal.framework.mappings import positionsNEWLINEfrom airsenal.framework.schema import PlayerAttributes, session_scope, sessionNEWLINENEWLINEfrom airsenal.framework.utils import (NEWLINE get_next_gameweek,NEWLINE get_player,NEWLINE get_player_from_api_id,NEWLINE get_team_name,NEWLINE get_past_seasons,NEWLINE CURRENT_SEASON,NEWLINE get_player_attributes,NEWLINE get_player_team_from_fixture,NEWLINE get_return_gameweek_from_news,NEWLINE)NEWLINENEWLINEfrom airsenal.framework.data_fetcher import FPLDataFetcherNEWLINENEWLINENEWLINEdef fill_attributes_table_from_file(detail_data, season, dbsession=session):NEWLINE """Fill player attributes table for previous season using data fromNEWLINE player detail JSON files.NEWLINE """NEWLINENEWLINE for player_name in detail_data.keys():NEWLINE # find the player id in the player table. If they're notNEWLINE # there, then we don't care (probably not a current player).NEWLINE player = get_player(player_name, dbsession=dbsession)NEWLINE if not player:NEWLINE print("Couldn't find player {}".format(player_name))NEWLINE continueNEWLINENEWLINE print("ATTRIBUTES {} {}".format(season, player))NEWLINE # now loop through all the fixtures that player played inNEWLINE # Only one attributes row per gameweek - create list of gameweeksNEWLINE # encountered so can ignore duplicates (e.g. from double gameweeks).NEWLINE previous_gameweeks = []NEWLINE for fixture_data in detail_data[player_name]:NEWLINE gameweek = int(fixture_data["gameweek"])NEWLINE if gameweek in previous_gameweeks:NEWLINE # already done this gameweekNEWLINE continueNEWLINE else:NEWLINE previous_gameweeks.append(gameweek)NEWLINENEWLINE pa = PlayerAttributes()NEWLINE pa.player = playerNEWLINE pa.player_id = player.player_idNEWLINE pa.season = seasonNEWLINE pa.gameweek = gameweekNEWLINE pa.price = int(fixture_data["value"])NEWLINE pa.team = fixture_data["played_for"]NEWLINE pa.position = fixture_data["position"]NEWLINE pa.transfers_balance = int(fixture_data["transfers_balance"])NEWLINE pa.selected = int(fixture_data["selected"])NEWLINE pa.transfers_in = int(fixture_data["transfers_in"])NEWLINE pa.transfers_out = int(fixture_data["transfers_out"])NEWLINE dbsession.add(pa)NEWLINENEWLINENEWLINEdef fill_attributes_table_from_api(season, gw_start=1, dbsession=session):NEWLINE """NEWLINE use the FPL API to get player attributes info for the current seasonNEWLINE """NEWLINE fetcher = FPLDataFetcher()NEWLINE next_gw = get_next_gameweek(season=season, dbsession=dbsession)NEWLINENEWLINE # needed for selected by calculation from percentage belowNEWLINE n_players = fetcher.get_current_summary_data()["total_players"]NEWLINENEWLINE input_data = fetcher.get_player_summary_data()NEWLINENEWLINE for player_api_id in input_data.keys():NEWLINE # find the player in the player tableNEWLINE player = get_player_from_api_id(player_api_id, dbsession=dbsession)NEWLINE if not player:NEWLINE print(NEWLINE "ATTRIBUTES {} No player found with id {}".format(season, player_api_id)NEWLINE )NEWLINE continueNEWLINENEWLINE print("ATTRIBUTES {} {}".format(season, player.name))NEWLINENEWLINE # First update the current gameweek using the summary dataNEWLINE p_summary = input_data[player_api_id]NEWLINE position = positions[p_summary["element_type"]]NEWLINENEWLINE pa = get_player_attributes(NEWLINE player.player_id, season=season, gameweek=next_gw, dbsession=dbsessionNEWLINE )NEWLINE if pa:NEWLINE # found pre-existing attributes for this gameweekNEWLINE update = TrueNEWLINE else:NEWLINE # no attributes for this gameweek for this player yetNEWLINE pa = PlayerAttributes()NEWLINE update = FalseNEWLINENEWLINE pa.player = playerNEWLINE pa.player_id = player.player_idNEWLINE pa.season = seasonNEWLINE pa.gameweek = next_gwNEWLINE pa.price = int(p_summary["now_cost"])NEWLINE pa.team = get_team_name(p_summary["team"], season=season, dbsession=dbsession)NEWLINE pa.position = positions[p_summary["element_type"]]NEWLINE pa.selected = int(float(p_summary["selected_by_percent"]) * n_players / 100)NEWLINE pa.transfers_in = int(p_summary["transfers_in_event"])NEWLINE pa.transfers_out = int(p_summary["transfers_out_event"])NEWLINE pa.transfers_balance = pa.transfers_in - pa.transfers_outNEWLINE pa.chance_of_playing_next_round = p_summary["chance_of_playing_next_round"]NEWLINE pa.news = p_summary["news"]NEWLINE if (NEWLINE pa.chance_of_playing_next_round is not NoneNEWLINE and pa.chance_of_playing_next_round <= 50NEWLINE ):NEWLINE pa.return_gameweek = get_return_gameweek_from_news(NEWLINE p_summary["news"],NEWLINE season=season,NEWLINE dbsession=dbsession,NEWLINE )NEWLINENEWLINE if not update:NEWLINE # only need to add to the dbsession for new entries, if we're doingNEWLINE # an update the final dbsession.commit() is enoughNEWLINE dbsession.add(pa)NEWLINENEWLINE # now get data for previous gameweeksNEWLINE player_data = fetcher.get_gameweek_data_for_player(player_api_id)NEWLINE if not player_data:NEWLINE print("Failed to get data for", player.name)NEWLINE continueNEWLINE for gameweek, data in player_data.items():NEWLINE if gameweek < gw_start:NEWLINE continueNEWLINENEWLINE for result in data:NEWLINE # check whether there are pre-existing attributes to updateNEWLINE pa = get_player_attributes(NEWLINE player.player_id,NEWLINE season=season,NEWLINE gameweek=gameweek,NEWLINE dbsession=dbsession,NEWLINE )NEWLINE if pa:NEWLINE update = TrueNEWLINE else:NEWLINE pa = PlayerAttributes()NEWLINE update = FalseNEWLINENEWLINE # determine the team the player played for in this fixtureNEWLINE opponent_id = result["opponent_team"]NEWLINE was_home = result["was_home"]NEWLINE kickoff_time = result["kickoff_time"]NEWLINE team = get_player_team_from_fixture(NEWLINE gameweek,NEWLINE opponent_id,NEWLINE was_home,NEWLINE kickoff_time,NEWLINE season=season,NEWLINE dbsession=dbsession,NEWLINE )NEWLINENEWLINE pa.player = playerNEWLINE pa.player_id = player.player_idNEWLINE pa.season = seasonNEWLINE pa.gameweek = gameweekNEWLINE pa.price = int(result["value"])NEWLINE pa.team = teamNEWLINE pa.position = position # does not change during seasonNEWLINE pa.transfers_balance = int(result["transfers_balance"])NEWLINE pa.selected = int(result["selected"])NEWLINE pa.transfers_in = int(result["transfers_in"])NEWLINE pa.transfers_out = int(result["transfers_out"])NEWLINENEWLINE if not update:NEWLINE # don't need to add to dbsession if updating pre-existing rowNEWLINE dbsession.add(pa)NEWLINENEWLINE break # done this gameweek nowNEWLINENEWLINENEWLINEdef make_attributes_table(seasons=[], dbsession=session):NEWLINE """Create the player attributes table using the previous 3 seasons (fromNEWLINE player details JSON files) and the current season (from API)NEWLINE """NEWLINE if not seasons:NEWLINE seasons = get_past_seasons(3)NEWLINE seasons.append(CURRENT_SEASON)NEWLINENEWLINE for season in seasons:NEWLINE if season == CURRENT_SEASON:NEWLINE continueNEWLINE input_path = os.path.join(NEWLINE os.path.dirname(__file__), "../data/player_details_{}.json".format(season)NEWLINE )NEWLINE with open(input_path, "r") as f:NEWLINE input_data = json.load(f)NEWLINENEWLINE fill_attributes_table_from_file(NEWLINE detail_data=input_data, season=season, dbsession=dbsessionNEWLINE )NEWLINENEWLINE # this season's data from the APINEWLINE if CURRENT_SEASON in seasons:NEWLINE fill_attributes_table_from_api(season=CURRENT_SEASON, dbsession=dbsession)NEWLINENEWLINE dbsession.commit()NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE with session_scope() as dbsession:NEWLINE make_attributes_table(dbsession=dbsession)NEWLINE |
# -*- coding: utf-8 -*-NEWLINENEWLINEimport pymysqlNEWLINEimport structNEWLINENEWLINEfrom pymysql.constants.COMMAND import COM_BINLOG_DUMP, COM_REGISTER_SLAVENEWLINEfrom pymysql.cursors import DictCursorNEWLINEfrom pymysql.util import int2byteNEWLINENEWLINEfrom .packet import BinLogPacketWrapperNEWLINEfrom .constants.BINLOG import TABLE_MAP_EVENT, ROTATE_EVENTNEWLINEfrom .gtid import GtidSetNEWLINEfrom .event import (NEWLINE QueryEvent, RotateEvent, FormatDescriptionEvent,NEWLINE XidEvent, GtidEvent, StopEvent,NEWLINE BeginLoadQueryEvent, ExecuteLoadQueryEvent,NEWLINE HeartbeatLogEvent, NotImplementedEvent)NEWLINEfrom .exceptions import BinLogNotEnabledNEWLINEfrom .row_event import (NEWLINE UpdateRowsEvent, WriteRowsEvent, DeleteRowsEvent, TableMapEvent)NEWLINENEWLINEtry:NEWLINE from pymysql.constants.COMMAND import COM_BINLOG_DUMP_GTIDNEWLINEexcept ImportError:NEWLINE # Handle old pymysql versionsNEWLINE # See: https://github.com/PyMySQL/PyMySQL/pull/261NEWLINE COM_BINLOG_DUMP_GTID = 0x1eNEWLINENEWLINE# 2013 Connection LostNEWLINE# 2006 MySQL server has gone awayNEWLINEMYSQL_EXPECTED_ERROR_CODES = [2013, 2006]NEWLINENEWLINENEWLINEclass ReportSlave(object):NEWLINENEWLINE """Represent the values that you may report when connecting as a slaveNEWLINE to a master. SHOW SLAVE HOSTS related"""NEWLINENEWLINE hostname = ''NEWLINE username = ''NEWLINE password = ''NEWLINE port = 0NEWLINENEWLINE def __init__(self, value):NEWLINE """NEWLINE Attributes:NEWLINE value: string or tupleNEWLINE if string, then it will be used hostnameNEWLINE if tuple it will be used as (hostname, user, password, port)NEWLINE """NEWLINENEWLINE if isinstance(value, (tuple, list)):NEWLINE try:NEWLINE self.hostname = value[0]NEWLINE self.username = value[1]NEWLINE self.password = value[2]NEWLINE self.port = int(value[3])NEWLINE except IndexError:NEWLINE passNEWLINE elif isinstance(value, dict):NEWLINE for key in ['hostname', 'username', 'password', 'port']:NEWLINE try:NEWLINE setattr(self, key, value[key])NEWLINE except KeyError:NEWLINE passNEWLINE else:NEWLINE self.hostname = valueNEWLINENEWLINE def __repr__(self):NEWLINE return '<ReportSlave hostname=%s username=%s password=%s port=%d>' %\NEWLINE (self.hostname, self.username, self.password, self.port)NEWLINENEWLINE def encoded(self, server_id, master_id=0):NEWLINE """NEWLINE server_id: the slave server-idNEWLINE master_id: usually 0. Appears as "master id" in SHOW SLAVE HOSTSNEWLINE on the master. Unknown what else it impacts.NEWLINE """NEWLINENEWLINE # 1 [15] COM_REGISTER_SLAVENEWLINE # 4 server-idNEWLINE # 1 slaves hostname lengthNEWLINE # string[$len] slaves hostnameNEWLINE # 1 slaves user lenNEWLINE # string[$len] slaves userNEWLINE # 1 slaves password lenNEWLINE # string[$len] slaves passwordNEWLINE # 2 slaves mysql-portNEWLINE # 4 replication rankNEWLINE # 4 master-idNEWLINENEWLINE lhostname = len(self.hostname.encode())NEWLINE lusername = len(self.username.encode())NEWLINE lpassword = len(self.password.encode())NEWLINENEWLINE packet_len = (1 + # commandNEWLINE 4 + # server-idNEWLINE 1 + # hostname lengthNEWLINE lhostname +NEWLINE 1 + # username lengthNEWLINE lusername +NEWLINE 1 + # password lengthNEWLINE lpassword +NEWLINE 2 + # slave mysql portNEWLINE 4 + # replication rankNEWLINE 4) # master-idNEWLINENEWLINE MAX_STRING_LEN = 257 # one byte for length + 256 charsNEWLINENEWLINE return (struct.pack('<i', packet_len) +NEWLINE int2byte(COM_REGISTER_SLAVE) +NEWLINE struct.pack('<L', server_id) +NEWLINE struct.pack('<%dp' % min(MAX_STRING_LEN, lhostname + 1),NEWLINE self.hostname.encode()) +NEWLINE struct.pack('<%dp' % min(MAX_STRING_LEN, lusername + 1),NEWLINE self.username.encode()) +NEWLINE struct.pack('<%dp' % min(MAX_STRING_LEN, lpassword + 1),NEWLINE self.password.encode()) +NEWLINE struct.pack('<H', self.port) +NEWLINE struct.pack('<l', 0) +NEWLINE struct.pack('<l', master_id))NEWLINENEWLINENEWLINEclass BinLogStreamReader(object):NEWLINENEWLINE """Connect to replication stream and read eventNEWLINE """NEWLINE report_slave = NoneNEWLINENEWLINE def __init__(self, connection_settings, server_id, ctl_connection_settings=None, resume_stream=False,NEWLINE blocking=False, only_events=None, log_file=None, log_pos=None,NEWLINE filter_non_implemented_events=True,NEWLINE ignored_events=None, auto_position=None,NEWLINE only_tables=None, ignored_tables=None,NEWLINE only_schemas=None, ignored_schemas=None,NEWLINE freeze_schema=False, skip_to_timestamp=None,NEWLINE report_slave=None, slave_uuid=None,NEWLINE pymysql_wrapper=None,NEWLINE fail_on_table_metadata_unavailable=False,NEWLINE slave_heartbeat=None):NEWLINE """NEWLINE Attributes:NEWLINE ctl_connection_settings: Connection settings for cluster holding schema informationNEWLINE resume_stream: Start for event from position or the latest event ofNEWLINE binlog or from older available eventNEWLINE blocking: Read on stream is blockingNEWLINE only_events: Array of allowed eventsNEWLINE ignored_events: Array of ignored eventsNEWLINE log_file: Set replication start log fileNEWLINE log_pos: Set replication start log pos (resume_stream should be true)NEWLINE auto_position: Use master_auto_position gtid to set positionNEWLINE only_tables: An array with the tables you want to watch (only worksNEWLINE in binlog_format ROW)NEWLINE ignored_tables: An array with the tables you want to skipNEWLINE only_schemas: An array with the schemas you want to watchNEWLINE ignored_schemas: An array with the schemas you want to skipNEWLINE freeze_schema: If true do not support ALTER TABLE. It's faster.NEWLINE skip_to_timestamp: Ignore all events until reaching specified timestamp.NEWLINE report_slave: Report slave in SHOW SLAVE HOSTS.NEWLINE slave_uuid: Report slave_uuid in SHOW SLAVE HOSTS.NEWLINE fail_on_table_metadata_unavailable: Should raise exception if we can't getNEWLINE table information on row_eventsNEWLINE slave_heartbeat: (seconds) Should master actively send heartbeat onNEWLINE connection. This also reduces traffic in GTID replicationNEWLINE on replication resumption (in case many event to skip inNEWLINE binlog). See MASTER_HEARTBEAT_PERIOD in mysql documentationNEWLINE for semanticsNEWLINE """NEWLINENEWLINE self.__connection_settings = connection_settingsNEWLINE self.__connection_settings.setdefault("charset", "utf8")NEWLINENEWLINE self.__connected_stream = FalseNEWLINE self.__connected_ctl = FalseNEWLINE self.__resume_stream = resume_streamNEWLINE self.__blocking = blockingNEWLINE self._ctl_connection_settings = ctl_connection_settingsNEWLINE if ctl_connection_settings:NEWLINE self._ctl_connection_settings.setdefault("charset", "utf8")NEWLINENEWLINE self.__only_tables = only_tablesNEWLINE self.__ignored_tables = ignored_tablesNEWLINE self.__only_schemas = only_schemasNEWLINE self.__ignored_schemas = ignored_schemasNEWLINE self.__freeze_schema = freeze_schemaNEWLINE self.__allowed_events = self._allowed_event_list(NEWLINE only_events, ignored_events, filter_non_implemented_events)NEWLINE self.__fail_on_table_metadata_unavailable = fail_on_table_metadata_unavailableNEWLINENEWLINE # We can't filter on packet level TABLE_MAP and rotate event becauseNEWLINE # we need them for handling other operationsNEWLINE self.__allowed_events_in_packet = frozenset(NEWLINE [TableMapEvent, RotateEvent]).union(self.__allowed_events)NEWLINENEWLINE self.__server_id = server_idNEWLINE self.__use_checksum = FalseNEWLINENEWLINE # Store table meta informationNEWLINE self.table_map = {}NEWLINE self.log_pos = log_posNEWLINE self.log_file = log_fileNEWLINE self.auto_position = auto_positionNEWLINE self.skip_to_timestamp = skip_to_timestampNEWLINENEWLINE if report_slave:NEWLINE self.report_slave = ReportSlave(report_slave)NEWLINE self.slave_uuid = slave_uuidNEWLINE self.slave_heartbeat = slave_heartbeatNEWLINENEWLINE if pymysql_wrapper:NEWLINE self.pymysql_wrapper = pymysql_wrapperNEWLINE else:NEWLINE self.pymysql_wrapper = pymysql.connectNEWLINENEWLINE def close(self):NEWLINE if self.__connected_stream:NEWLINE self._stream_connection.close()NEWLINE self.__connected_stream = FalseNEWLINE if self.__connected_ctl:NEWLINE # break reference cycle between stream reader and underlyingNEWLINE # mysql connection objectNEWLINE self._ctl_connection._get_table_information = NoneNEWLINE self._ctl_connection.close()NEWLINE self.__connected_ctl = FalseNEWLINENEWLINE def __connect_to_ctl(self):NEWLINE if not self._ctl_connection_settings:NEWLINE self._ctl_connection_settings = dict(self.__connection_settings)NEWLINE self._ctl_connection_settings["db"] = "information_schema"NEWLINE self._ctl_connection_settings["cursorclass"] = DictCursorNEWLINE self._ctl_connection = self.pymysql_wrapper(**self._ctl_connection_settings)NEWLINE self._ctl_connection._get_table_information = self.__get_table_informationNEWLINE self.__connected_ctl = TrueNEWLINENEWLINE def __checksum_enabled(self):NEWLINE """Return True if binlog-checksum = CRC32. Only for MySQL > 5.6"""NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("SHOW GLOBAL VARIABLES LIKE 'BINLOG_CHECKSUM'")NEWLINE result = cur.fetchone()NEWLINE cur.close()NEWLINENEWLINE if result is None:NEWLINE return FalseNEWLINE var, value = result[:2]NEWLINE if value == 'NONE':NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINE def _register_slave(self):NEWLINE if not self.report_slave:NEWLINE returnNEWLINENEWLINE packet = self.report_slave.encoded(self.__server_id)NEWLINENEWLINE if pymysql.__version__ < "0.6":NEWLINE self._stream_connection.wfile.write(packet)NEWLINE self._stream_connection.wfile.flush()NEWLINE self._stream_connection.read_packet()NEWLINE else:NEWLINE self._stream_connection._write_bytes(packet)NEWLINE self._stream_connection._next_seq_id = 1NEWLINE self._stream_connection._read_packet()NEWLINENEWLINE def __connect_to_stream(self):NEWLINE # log_pos (4) -- position in the binlog-file to start the stream withNEWLINE # flags (2) BINLOG_DUMP_NON_BLOCK (0 or 1)NEWLINE # server_id (4) -- server id of this slaveNEWLINE # log_file (string.EOF) -- filename of the binlog on the masterNEWLINE self._stream_connection = self.pymysql_wrapper(**self.__connection_settings)NEWLINENEWLINE self.__use_checksum = self.__checksum_enabled()NEWLINENEWLINE # If checksum is enabled we need to inform the server about the thatNEWLINE # we support itNEWLINE if self.__use_checksum:NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("set @master_binlog_checksum= @@global.binlog_checksum")NEWLINE cur.close()NEWLINENEWLINE if self.slave_uuid:NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("set @slave_uuid= '%s'" % self.slave_uuid)NEWLINE cur.close()NEWLINENEWLINE if self.slave_heartbeat:NEWLINE # 4294967 is documented as the max value for heartbeatsNEWLINE net_timeout = float(self.__connection_settings.get('read_timeout',NEWLINE 4294967))NEWLINE # If heartbeat is too low, the connection will disconnect before,NEWLINE # this is also the behavior in mysqlNEWLINE heartbeat = float(min(net_timeout/2., self.slave_heartbeat))NEWLINE if heartbeat > 4294967:NEWLINE heartbeat = 4294967NEWLINENEWLINE # master_heartbeat_period is nanosecondsNEWLINE heartbeat = int(heartbeat * 1000000000)NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("set @master_heartbeat_period= %d" % heartbeat)NEWLINE cur.close()NEWLINENEWLINE self._register_slave()NEWLINENEWLINE if not self.auto_position:NEWLINE # only when log_file and log_pos both provided, the position info isNEWLINE # valid, if not, get the current position from masterNEWLINE if self.log_file is None or self.log_pos is None:NEWLINE cur = self._stream_connection.cursor()NEWLINE cur.execute("SHOW MASTER STATUS")NEWLINE master_status = cur.fetchone()NEWLINE if master_status is None:NEWLINE raise BinLogNotEnabled()NEWLINE self.log_file, self.log_pos = master_status[:2]NEWLINE cur.close()NEWLINENEWLINE prelude = struct.pack('<i', len(self.log_file) + 11) \NEWLINE + int2byte(COM_BINLOG_DUMP)NEWLINENEWLINE if self.__resume_stream:NEWLINE prelude += struct.pack('<I', self.log_pos)NEWLINE else:NEWLINE prelude += struct.pack('<I', 4)NEWLINENEWLINE if self.__blocking:NEWLINE prelude += struct.pack('<h', 0)NEWLINE else:NEWLINE prelude += struct.pack('<h', 1)NEWLINENEWLINE prelude += struct.pack('<I', self.__server_id)NEWLINE prelude += self.log_file.encode()NEWLINE else:NEWLINE # Format for mysql packet master_auto_positionNEWLINE #NEWLINE # All fields are little endianNEWLINE # All fields are unsignedNEWLINENEWLINE # Packet length uint 4bytesNEWLINE # Packet type byte 1byte == 0x1eNEWLINE # Binlog flags ushort 2bytes == 0 (for retrocompatibilty)NEWLINE # Server id uint 4bytesNEWLINE # binlognamesize uint 4bytesNEWLINE # binlogname str Nbytes N = binlognamesizeNEWLINE # ZeroifiedNEWLINE # binlog position uint 4bytes == 4NEWLINE # payload_size uint 4bytesNEWLINENEWLINE # What come next, is the payload, where the slave gtid_executedNEWLINE # is sent to the masterNEWLINE # n_sid ulong 8bytes == which size is the gtid_setNEWLINE # | sid uuid 16bytes UUID as a binaryNEWLINE # | n_intervals ulong 8bytes == how many intervals are sent for this gtidNEWLINE # | | start ulong 8bytes Start position of this intervalNEWLINE # | | stop ulong 8bytes Stop position of this intervalNEWLINENEWLINE # A gtid set looks like:NEWLINE # 19d69c1e-ae97-4b8c-a1ef-9e12ba966457:1-3:8-10,NEWLINE # 1c2aad49-ae92-409a-b4df-d05a03e4702e:42-47:80-100:130-140NEWLINE #NEWLINE # In this particular gtid set, 19d69c1e-ae97-4b8c-a1ef-9e12ba966457:1-3:8-10NEWLINE # is the first member of the set, it is called a gtid.NEWLINE # In this gtid, 19d69c1e-ae97-4b8c-a1ef-9e12ba966457 is the sidNEWLINE # and have two intervals, 1-3 and 8-10, 1 is the start position of the first intervalNEWLINE # 3 is the stop position of the first interval.NEWLINENEWLINE gtid_set = GtidSet(self.auto_position)NEWLINE encoded_data_size = gtid_set.encoded_lengthNEWLINENEWLINE header_size = (2 + # binlog_flagsNEWLINE 4 + # server_idNEWLINE 4 + # binlog_name_info_sizeNEWLINE 4 + # empty binlog nameNEWLINE 8 + # binlog_pos_info_sizeNEWLINE 4) # encoded_data_sizeNEWLINENEWLINE prelude = b'' + struct.pack('<i', header_size + encoded_data_size) \NEWLINE + int2byte(COM_BINLOG_DUMP_GTID)NEWLINENEWLINE # binlog_flags = 0 (2 bytes)NEWLINE prelude += struct.pack('<H', 0)NEWLINE # server_id (4 bytes)NEWLINE prelude += struct.pack('<I', self.__server_id)NEWLINE # binlog_name_info_size (4 bytes)NEWLINE prelude += struct.pack('<I', 3)NEWLINE # empty_binlog_name (4 bytes)NEWLINE prelude += b'\0\0\0'NEWLINE # binlog_pos_info (8 bytes)NEWLINE prelude += struct.pack('<Q', 4)NEWLINENEWLINE # encoded_data_size (4 bytes)NEWLINE prelude += struct.pack('<I', gtid_set.encoded_length)NEWLINE # encoded_dataNEWLINE prelude += gtid_set.encoded()NEWLINENEWLINE if pymysql.__version__ < "0.6":NEWLINE self._stream_connection.wfile.write(prelude)NEWLINE self._stream_connection.wfile.flush()NEWLINE else:NEWLINE self._stream_connection._write_bytes(prelude)NEWLINE self._stream_connection._next_seq_id = 1NEWLINE self.__connected_stream = TrueNEWLINENEWLINE def fetchone(self):NEWLINE while True:NEWLINE if not self.__connected_stream:NEWLINE self.__connect_to_stream()NEWLINENEWLINE if not self.__connected_ctl:NEWLINE self.__connect_to_ctl()NEWLINENEWLINE try:NEWLINE if pymysql.__version__ < "0.6":NEWLINE pkt = self._stream_connection.read_packet()NEWLINE else:NEWLINE pkt = self._stream_connection._read_packet()NEWLINE except pymysql.OperationalError as error:NEWLINE code, message = error.argsNEWLINE if code in MYSQL_EXPECTED_ERROR_CODES:NEWLINE self._stream_connection.close()NEWLINE self.__connected_stream = FalseNEWLINE continueNEWLINE raiseNEWLINENEWLINE if pkt.is_eof_packet():NEWLINE self.close()NEWLINE return NoneNEWLINENEWLINE if not pkt.is_ok_packet():NEWLINE continueNEWLINENEWLINE binlog_event = BinLogPacketWrapper(pkt, self.table_map,NEWLINE self._ctl_connection,NEWLINE self.__use_checksum,NEWLINE self.__allowed_events_in_packet,NEWLINE self.__only_tables,NEWLINE self.__ignored_tables,NEWLINE self.__only_schemas,NEWLINE self.__ignored_schemas,NEWLINE self.__freeze_schema,NEWLINE self.__fail_on_table_metadata_unavailable)NEWLINENEWLINE if binlog_event.event_type == ROTATE_EVENT:NEWLINE self.log_pos = binlog_event.event.positionNEWLINE self.log_file = binlog_event.event.next_binlogNEWLINE # Table Id in binlog are NOT persistent in MySQL - they are in-memory identifiersNEWLINE # that means that when MySQL master restarts, it will reuse same table id for different tablesNEWLINE # which will cause errors for us since our in-memory map will try to decode row data withNEWLINE # wrong table schema.NEWLINE # The fix is to rely on the fact that MySQL will also rotate to a new binlog file every time itNEWLINE # restarts. That means every rotation we see *could* be a sign of restart and so potentiallyNEWLINE # invalidates all our cached table id to schema mappings. This means we have to load them allNEWLINE # again for each logfile which is potentially wasted effort but we can't really do much betterNEWLINE # without being broken in restart caseNEWLINE self.table_map = {}NEWLINE elif binlog_event.log_pos:NEWLINE self.log_pos = binlog_event.log_posNEWLINENEWLINE # This check must not occur before clearing the ``table_map`` as aNEWLINE # result of a RotateEvent.NEWLINE #NEWLINE # The first RotateEvent in a binlog file has a timestamp ofNEWLINE # zero. If the server has moved to a new log and not written aNEWLINE # timestamped RotateEvent at the end of the previous log, theNEWLINE # RotateEvent at the beginning of the new log will be ignoredNEWLINE # if the caller provided a positive ``skip_to_timestamp``NEWLINE # value. This will result in the ``table_map`` becomingNEWLINE # corrupt.NEWLINE #NEWLINE # https://dev.mysql.com/doc/internals/en/event-data-for-specific-event-types.htmlNEWLINE # From the MySQL Internals Manual:NEWLINE #NEWLINE # ROTATE_EVENT is generated locally and written to the binaryNEWLINE # log on the master. It is written to the relay log on theNEWLINE # slave when FLUSH LOGS occurs, and when receiving aNEWLINE # ROTATE_EVENT from the master. In the latter case, thereNEWLINE # will be two rotate events in total originating on differentNEWLINE # servers.NEWLINE #NEWLINE # There are conditions under which the terminatingNEWLINE # log-rotation event does not occur. For example, the serverNEWLINE # might crash.NEWLINE if self.skip_to_timestamp and binlog_event.timestamp < self.skip_to_timestamp:NEWLINE continueNEWLINENEWLINE if binlog_event.event_type == TABLE_MAP_EVENT and \NEWLINE binlog_event.event is not None:NEWLINE self.table_map[binlog_event.event.table_id] = \NEWLINE binlog_event.event.get_table()NEWLINENEWLINE # event is none if we have filter it on packet levelNEWLINE # we filter also not allowed eventsNEWLINE if binlog_event.event is None or (binlog_event.event.__class__ not in self.__allowed_events):NEWLINE continueNEWLINENEWLINE return binlog_event.eventNEWLINENEWLINE def _allowed_event_list(self, only_events, ignored_events,NEWLINE filter_non_implemented_events):NEWLINE if only_events is not None:NEWLINE events = set(only_events)NEWLINE else:NEWLINE events = set((NEWLINE QueryEvent,NEWLINE RotateEvent,NEWLINE StopEvent,NEWLINE FormatDescriptionEvent,NEWLINE XidEvent,NEWLINE GtidEvent,NEWLINE BeginLoadQueryEvent,NEWLINE ExecuteLoadQueryEvent,NEWLINE UpdateRowsEvent,NEWLINE WriteRowsEvent,NEWLINE DeleteRowsEvent,NEWLINE TableMapEvent,NEWLINE HeartbeatLogEvent,NEWLINE NotImplementedEvent,NEWLINE ))NEWLINE if ignored_events is not None:NEWLINE for e in ignored_events:NEWLINE events.remove(e)NEWLINE if filter_non_implemented_events:NEWLINE try:NEWLINE events.remove(NotImplementedEvent)NEWLINE except KeyError:NEWLINE passNEWLINE return frozenset(events)NEWLINENEWLINE def __get_table_information(self, schema, table):NEWLINE for i in range(1, 3):NEWLINE try:NEWLINE if not self.__connected_ctl:NEWLINE self.__connect_to_ctl()NEWLINENEWLINE cur = self._ctl_connection.cursor()NEWLINE cur.execute("""NEWLINE SELECTNEWLINE COLUMN_NAME, COLLATION_NAME, CHARACTER_SET_NAME,NEWLINE COLUMN_COMMENT, COLUMN_TYPE, COLUMN_KEYNEWLINE FROMNEWLINE information_schema.columnsNEWLINE WHERENEWLINE table_schema = %s AND table_name = %sNEWLINE ORDER BY ORDINAL_POSITIONNEWLINE """, (schema, table))NEWLINENEWLINE return cur.fetchall()NEWLINE except pymysql.OperationalError as error:NEWLINE code, message = error.argsNEWLINE if code in MYSQL_EXPECTED_ERROR_CODES:NEWLINE self.__connected_ctl = FalseNEWLINE continueNEWLINE else:NEWLINE raise errorNEWLINENEWLINE def __iter__(self):NEWLINE return iter(self.fetchone, None)NEWLINE |
import warningsNEWLINEfrom unittest.mock import MagicMockNEWLINENEWLINEfrom joblibspark.backend import SparkDistributedBackendNEWLINENEWLINENEWLINEdef test_effective_n_jobs():NEWLINENEWLINE backend = SparkDistributedBackend()NEWLINE max_num_concurrent_tasks = 8NEWLINE backend._get_max_num_concurrent_tasks = MagicMock(return_value=max_num_concurrent_tasks)NEWLINENEWLINE assert backend.effective_n_jobs(n_jobs=None) == 1NEWLINE assert backend.effective_n_jobs(n_jobs=-1) == 8NEWLINE assert backend.effective_n_jobs(n_jobs=4) == 4NEWLINENEWLINE with warnings.catch_warnings(record=True) as w:NEWLINE warnings.simplefilter("always")NEWLINE assert backend.effective_n_jobs(n_jobs=16) == 16NEWLINE assert len(w) == 1NEWLINE |
#!/usr/bin/env pythonNEWLINENEWLINE'''NEWLINEEC2 external inventory scriptNEWLINE=================================NEWLINENEWLINEGenerates inventory that Ansible can understand by making API request toNEWLINEAWS EC2 using the Boto library.NEWLINENEWLINENOTE: This script assumes Ansible is being executed where the environmentNEWLINEvariables needed for Boto have already been set:NEWLINE export AWS_ACCESS_KEY_ID='AK123'NEWLINE export AWS_SECRET_ACCESS_KEY='abc123'NEWLINENEWLINEoptional region environment variable if region is 'auto'NEWLINENEWLINEThis script also assumes there is an ec2.ini file alongside it. To specify aNEWLINEdifferent path to ec2.ini, define the EC2_INI_PATH environment variable:NEWLINENEWLINE export EC2_INI_PATH=/path/to/my_ec2.iniNEWLINENEWLINEIf you're using eucalyptus you need to set the above variables andNEWLINEyou need to define:NEWLINENEWLINE export EC2_URL=http://hostname_of_your_cc:port/services/EucalyptusNEWLINENEWLINEIf you're using boto profiles (requires boto>=2.24.0) you can choose a profileNEWLINEusing the --boto-profile command line argument (e.g. ec2.py --boto-profile prod) or usingNEWLINEthe AWS_PROFILE variable:NEWLINENEWLINE AWS_PROFILE=prod ansible-playbook -i ec2.py myplaybook.ymlNEWLINENEWLINEFor more details, see: http://docs.pythonboto.org/en/latest/boto_config_tut.htmlNEWLINENEWLINEWhen run against a specific host, this script returns the following variables:NEWLINE - ec2_ami_launch_indexNEWLINE - ec2_architectureNEWLINE - ec2_associationNEWLINE - ec2_attachTimeNEWLINE - ec2_attachmentNEWLINE - ec2_attachmentIdNEWLINE - ec2_block_devicesNEWLINE - ec2_client_tokenNEWLINE - ec2_deleteOnTerminationNEWLINE - ec2_descriptionNEWLINE - ec2_deviceIndexNEWLINE - ec2_dns_nameNEWLINE - ec2_eventsSetNEWLINE - ec2_group_nameNEWLINE - ec2_hypervisorNEWLINE - ec2_idNEWLINE - ec2_image_idNEWLINE - ec2_instanceStateNEWLINE - ec2_instance_typeNEWLINE - ec2_ipOwnerIdNEWLINE - ec2_ip_addressNEWLINE - ec2_itemNEWLINE - ec2_kernelNEWLINE - ec2_key_nameNEWLINE - ec2_launch_timeNEWLINE - ec2_monitoredNEWLINE - ec2_monitoringNEWLINE - ec2_networkInterfaceIdNEWLINE - ec2_ownerIdNEWLINE - ec2_persistentNEWLINE - ec2_placementNEWLINE - ec2_platformNEWLINE - ec2_previous_stateNEWLINE - ec2_private_dns_nameNEWLINE - ec2_private_ip_addressNEWLINE - ec2_publicIpNEWLINE - ec2_public_dns_nameNEWLINE - ec2_ramdiskNEWLINE - ec2_reasonNEWLINE - ec2_regionNEWLINE - ec2_requester_idNEWLINE - ec2_root_device_nameNEWLINE - ec2_root_device_typeNEWLINE - ec2_security_group_idsNEWLINE - ec2_security_group_namesNEWLINE - ec2_shutdown_stateNEWLINE - ec2_sourceDestCheckNEWLINE - ec2_spot_instance_request_idNEWLINE - ec2_stateNEWLINE - ec2_state_codeNEWLINE - ec2_state_reasonNEWLINE - ec2_statusNEWLINE - ec2_subnet_idNEWLINE - ec2_tenancyNEWLINE - ec2_virtualization_typeNEWLINE - ec2_vpc_idNEWLINENEWLINEThese variables are pulled out of a boto.ec2.instance object. There is a lack ofNEWLINEconsistency with variable spellings (camelCase and underscores) since thisNEWLINEjust loops through all variables the object exposes. It is preferred to use theNEWLINEones with underscores when multiple exist.NEWLINENEWLINEIn addition, if an instance has AWS Tags associated with it, each tag is a newNEWLINEvariable named:NEWLINE - ec2_tag_[Key] = [Value]NEWLINENEWLINESecurity groups are comma-separated in 'ec2_security_group_ids' andNEWLINE'ec2_security_group_names'.NEWLINE'''NEWLINENEWLINE# (c) 2012, Peter SankauskasNEWLINE#NEWLINE# This file is part of Ansible,NEWLINE#NEWLINE# Ansible is free software: you can redistribute it and/or modifyNEWLINE# it under the terms of the GNU General Public License as published byNEWLINE# the Free Software Foundation, either version 3 of the License, orNEWLINE# (at your option) any later version.NEWLINE#NEWLINE# Ansible is distributed in the hope that it will be useful,NEWLINE# but WITHOUT ANY WARRANTY; without even the implied warranty ofNEWLINE# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theNEWLINE# GNU General Public License for more details.NEWLINE#NEWLINE# You should have received a copy of the GNU General Public LicenseNEWLINE# along with Ansible. If not, see <http://www.gnu.org/licenses/>.NEWLINENEWLINE######################################################################NEWLINENEWLINEimport sysNEWLINEimport osNEWLINEimport argparseNEWLINEimport reNEWLINEfrom time import timeNEWLINEimport botoNEWLINEfrom boto import ec2NEWLINEfrom boto import rdsNEWLINEfrom boto import elasticacheNEWLINEfrom boto import route53NEWLINEfrom boto import stsNEWLINEimport sixNEWLINENEWLINEfrom ansible.module_utils import ec2 as ec2_utilsNEWLINENEWLINEHAS_BOTO3 = FalseNEWLINEtry:NEWLINE import boto3NEWLINE HAS_BOTO3 = TrueNEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINEfrom six.moves import configparserNEWLINEfrom collections import defaultdictNEWLINENEWLINEtry:NEWLINE import jsonNEWLINEexcept ImportError:NEWLINE import simplejson as jsonNEWLINENEWLINENEWLINEclass Ec2Inventory(object):NEWLINENEWLINE def _empty_inventory(self):NEWLINE return {"_meta": {"hostvars": {}}}NEWLINENEWLINE def __init__(self):NEWLINE ''' Main execution path '''NEWLINENEWLINE # Inventory grouped by instance IDs, tags, security groups, regions,NEWLINE # and availability zonesNEWLINE self.inventory = self._empty_inventory()NEWLINENEWLINE self.aws_account_id = NoneNEWLINENEWLINE # Index of hostname (address) to instance IDNEWLINE self.index = {}NEWLINENEWLINE # Boto profile to use (if any)NEWLINE self.boto_profile = NoneNEWLINENEWLINE # AWS credentials.NEWLINE self.credentials = {}NEWLINENEWLINE # Read settings and parse CLI argumentsNEWLINE self.parse_cli_args()NEWLINE self.read_settings()NEWLINENEWLINE # Make sure that profile_name is not passed at all if not setNEWLINE # as pre 2.24 boto will fall over otherwiseNEWLINE if self.boto_profile:NEWLINE if not hasattr(boto.ec2.EC2Connection, 'profile_name'):NEWLINE self.fail_with_error("boto version must be >= 2.24 to use profile")NEWLINENEWLINE # CacheNEWLINE if self.args.refresh_cache:NEWLINE self.do_api_calls_update_cache()NEWLINE elif not self.is_cache_valid():NEWLINE self.do_api_calls_update_cache()NEWLINENEWLINE # Data to printNEWLINE if self.args.host:NEWLINE data_to_print = self.get_host_info()NEWLINENEWLINE elif self.args.list:NEWLINE # Display list of instances for inventoryNEWLINE if self.inventory == self._empty_inventory():NEWLINE data_to_print = self.get_inventory_from_cache()NEWLINE else:NEWLINE data_to_print = self.json_format_dict(self.inventory, True)NEWLINENEWLINE print(data_to_print)NEWLINENEWLINE def is_cache_valid(self):NEWLINE ''' Determines if the cache files have expired, or if it is still valid '''NEWLINENEWLINE if os.path.isfile(self.cache_path_cache):NEWLINE mod_time = os.path.getmtime(self.cache_path_cache)NEWLINE current_time = time()NEWLINE if (mod_time + self.cache_max_age) > current_time:NEWLINE if os.path.isfile(self.cache_path_index):NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINE def read_settings(self):NEWLINE ''' Reads the settings from the ec2.ini file '''NEWLINENEWLINE scriptbasename = __file__NEWLINE scriptbasename = os.path.basename(scriptbasename)NEWLINE scriptbasename = scriptbasename.replace('.py', '')NEWLINENEWLINE defaults = {NEWLINE 'ec2': {NEWLINE 'ini_fallback': os.path.join(os.path.dirname(__file__), 'ec2.ini'),NEWLINE 'ini_path': os.path.join(os.path.dirname(__file__), '%s.ini' % scriptbasename)NEWLINE }NEWLINE }NEWLINENEWLINE if six.PY3:NEWLINE config = configparser.ConfigParser()NEWLINE else:NEWLINE config = configparser.SafeConfigParser()NEWLINE ec2_ini_path = os.environ.get('EC2_INI_PATH', defaults['ec2']['ini_path'])NEWLINE ec2_ini_path = os.path.expanduser(os.path.expandvars(ec2_ini_path))NEWLINENEWLINE if not os.path.isfile(ec2_ini_path):NEWLINE ec2_ini_path = os.path.expanduser(defaults['ec2']['ini_fallback'])NEWLINENEWLINE config.read(ec2_ini_path)NEWLINENEWLINE # is eucalyptus?NEWLINE self.eucalyptus_host = NoneNEWLINE self.eucalyptus = FalseNEWLINE if config.has_option('ec2', 'eucalyptus'):NEWLINE self.eucalyptus = config.getboolean('ec2', 'eucalyptus')NEWLINE if self.eucalyptus and config.has_option('ec2', 'eucalyptus_host'):NEWLINE self.eucalyptus_host = config.get('ec2', 'eucalyptus_host')NEWLINENEWLINE # RegionsNEWLINE self.regions = []NEWLINE configRegions = config.get('ec2', 'regions')NEWLINE if (configRegions == 'all'):NEWLINE if self.eucalyptus_host:NEWLINE self.regions.append(boto.connect_euca(host=self.eucalyptus_host).region.name, **self.credentials)NEWLINE else:NEWLINE configRegions_exclude = config.get('ec2', 'regions_exclude')NEWLINE for regionInfo in ec2.regions():NEWLINE if regionInfo.name not in configRegions_exclude:NEWLINE self.regions.append(regionInfo.name)NEWLINE else:NEWLINE self.regions = configRegions.split(",")NEWLINE if 'auto' in self.regions:NEWLINE env_region = os.environ.get('AWS_REGION')NEWLINE if env_region is None:NEWLINE env_region = os.environ.get('AWS_DEFAULT_REGION')NEWLINE self.regions = [env_region]NEWLINENEWLINE # Destination addressesNEWLINE self.destination_variable = config.get('ec2', 'destination_variable')NEWLINE self.vpc_destination_variable = config.get('ec2', 'vpc_destination_variable')NEWLINENEWLINE if config.has_option('ec2', 'hostname_variable'):NEWLINE self.hostname_variable = config.get('ec2', 'hostname_variable')NEWLINE else:NEWLINE self.hostname_variable = NoneNEWLINENEWLINE if config.has_option('ec2', 'destination_format') and \NEWLINE config.has_option('ec2', 'destination_format_tags'):NEWLINE self.destination_format = config.get('ec2', 'destination_format')NEWLINE self.destination_format_tags = config.get('ec2', 'destination_format_tags').split(',')NEWLINE else:NEWLINE self.destination_format = NoneNEWLINE self.destination_format_tags = NoneNEWLINENEWLINE # Route53NEWLINE self.route53_enabled = config.getboolean('ec2', 'route53')NEWLINE if config.has_option('ec2', 'route53_hostnames'):NEWLINE self.route53_hostnames = config.get('ec2', 'route53_hostnames')NEWLINE else:NEWLINE self.route53_hostnames = NoneNEWLINE self.route53_excluded_zones = []NEWLINE if config.has_option('ec2', 'route53_excluded_zones'):NEWLINE self.route53_excluded_zones.extend(NEWLINE config.get('ec2', 'route53_excluded_zones', '').split(','))NEWLINENEWLINE # Include RDS instances?NEWLINE self.rds_enabled = TrueNEWLINE if config.has_option('ec2', 'rds'):NEWLINE self.rds_enabled = config.getboolean('ec2', 'rds')NEWLINENEWLINE # Include RDS cluster instances?NEWLINE if config.has_option('ec2', 'include_rds_clusters'):NEWLINE self.include_rds_clusters = config.getboolean('ec2', 'include_rds_clusters')NEWLINE else:NEWLINE self.include_rds_clusters = FalseNEWLINENEWLINE # Include ElastiCache instances?NEWLINE self.elasticache_enabled = TrueNEWLINE if config.has_option('ec2', 'elasticache'):NEWLINE self.elasticache_enabled = config.getboolean('ec2', 'elasticache')NEWLINENEWLINE # Return all EC2 instances?NEWLINE if config.has_option('ec2', 'all_instances'):NEWLINE self.all_instances = config.getboolean('ec2', 'all_instances')NEWLINE else:NEWLINE self.all_instances = FalseNEWLINENEWLINE # Instance states to be gathered in inventory. Default is 'running'.NEWLINE # Setting 'all_instances' to 'yes' overrides this option.NEWLINE ec2_valid_instance_states = [NEWLINE 'pending',NEWLINE 'running',NEWLINE 'shutting-down',NEWLINE 'terminated',NEWLINE 'stopping',NEWLINE 'stopped'NEWLINE ]NEWLINE self.ec2_instance_states = []NEWLINE if self.all_instances:NEWLINE self.ec2_instance_states = ec2_valid_instance_statesNEWLINE elif config.has_option('ec2', 'instance_states'):NEWLINE for instance_state in config.get('ec2', 'instance_states').split(','):NEWLINE instance_state = instance_state.strip()NEWLINE if instance_state not in ec2_valid_instance_states:NEWLINE continueNEWLINE self.ec2_instance_states.append(instance_state)NEWLINE else:NEWLINE self.ec2_instance_states = ['running']NEWLINENEWLINE # Return all RDS instances? (if RDS is enabled)NEWLINE if config.has_option('ec2', 'all_rds_instances') and self.rds_enabled:NEWLINE self.all_rds_instances = config.getboolean('ec2', 'all_rds_instances')NEWLINE else:NEWLINE self.all_rds_instances = FalseNEWLINENEWLINE # Return all ElastiCache replication groups? (if ElastiCache is enabled)NEWLINE if config.has_option('ec2', 'all_elasticache_replication_groups') and self.elasticache_enabled:NEWLINE self.all_elasticache_replication_groups = config.getboolean('ec2', 'all_elasticache_replication_groups')NEWLINE else:NEWLINE self.all_elasticache_replication_groups = FalseNEWLINENEWLINE # Return all ElastiCache clusters? (if ElastiCache is enabled)NEWLINE if config.has_option('ec2', 'all_elasticache_clusters') and self.elasticache_enabled:NEWLINE self.all_elasticache_clusters = config.getboolean('ec2', 'all_elasticache_clusters')NEWLINE else:NEWLINE self.all_elasticache_clusters = FalseNEWLINENEWLINE # Return all ElastiCache nodes? (if ElastiCache is enabled)NEWLINE if config.has_option('ec2', 'all_elasticache_nodes') and self.elasticache_enabled:NEWLINE self.all_elasticache_nodes = config.getboolean('ec2', 'all_elasticache_nodes')NEWLINE else:NEWLINE self.all_elasticache_nodes = FalseNEWLINENEWLINE # boto configuration profile (prefer CLI argument then environment variables then config file)NEWLINE self.boto_profile = self.args.boto_profile or os.environ.get('AWS_PROFILE')NEWLINE if config.has_option('ec2', 'boto_profile') and not self.boto_profile:NEWLINE self.boto_profile = config.get('ec2', 'boto_profile')NEWLINENEWLINE # AWS credentials (prefer environment variables)NEWLINE if not (self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID') orNEWLINE os.environ.get('AWS_PROFILE')):NEWLINE if config.has_option('credentials', 'aws_access_key_id'):NEWLINE aws_access_key_id = config.get('credentials', 'aws_access_key_id')NEWLINE else:NEWLINE aws_access_key_id = NoneNEWLINE if config.has_option('credentials', 'aws_secret_access_key'):NEWLINE aws_secret_access_key = config.get('credentials', 'aws_secret_access_key')NEWLINE else:NEWLINE aws_secret_access_key = NoneNEWLINE if config.has_option('credentials', 'aws_security_token'):NEWLINE aws_security_token = config.get('credentials', 'aws_security_token')NEWLINE else:NEWLINE aws_security_token = NoneNEWLINE if aws_access_key_id:NEWLINE self.credentials = {NEWLINE 'aws_access_key_id': aws_access_key_id,NEWLINE 'aws_secret_access_key': aws_secret_access_keyNEWLINE }NEWLINE if aws_security_token:NEWLINE self.credentials['security_token'] = aws_security_tokenNEWLINENEWLINE # Cache relatedNEWLINE cache_dir = os.path.expanduser(config.get('ec2', 'cache_path'))NEWLINE if self.boto_profile:NEWLINE cache_dir = os.path.join(cache_dir, 'profile_' + self.boto_profile)NEWLINE if not os.path.exists(cache_dir):NEWLINE os.makedirs(cache_dir)NEWLINENEWLINE cache_name = 'ansible-ec2'NEWLINE cache_id = self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID', self.credentials.get('aws_access_key_id'))NEWLINE if cache_id:NEWLINE cache_name = '%s-%s' % (cache_name, cache_id)NEWLINE self.cache_path_cache = os.path.join(cache_dir, "%s.cache" % cache_name)NEWLINE self.cache_path_index = os.path.join(cache_dir, "%s.index" % cache_name)NEWLINE self.cache_max_age = config.getint('ec2', 'cache_max_age')NEWLINENEWLINE if config.has_option('ec2', 'expand_csv_tags'):NEWLINE self.expand_csv_tags = config.getboolean('ec2', 'expand_csv_tags')NEWLINE else:NEWLINE self.expand_csv_tags = FalseNEWLINENEWLINE # Configure nested groups instead of flat namespace.NEWLINE if config.has_option('ec2', 'nested_groups'):NEWLINE self.nested_groups = config.getboolean('ec2', 'nested_groups')NEWLINE else:NEWLINE self.nested_groups = FalseNEWLINENEWLINE # Replace dash or not in group namesNEWLINE if config.has_option('ec2', 'replace_dash_in_groups'):NEWLINE self.replace_dash_in_groups = config.getboolean('ec2', 'replace_dash_in_groups')NEWLINE else:NEWLINE self.replace_dash_in_groups = TrueNEWLINENEWLINE # IAM role to assume for connectionNEWLINE if config.has_option('ec2', 'iam_role'):NEWLINE self.iam_role = config.get('ec2', 'iam_role')NEWLINE else:NEWLINE self.iam_role = NoneNEWLINENEWLINE # Configure which groups should be created.NEWLINE group_by_options = [NEWLINE 'group_by_instance_id',NEWLINE 'group_by_region',NEWLINE 'group_by_availability_zone',NEWLINE 'group_by_ami_id',NEWLINE 'group_by_instance_type',NEWLINE 'group_by_instance_state',NEWLINE 'group_by_key_pair',NEWLINE 'group_by_vpc_id',NEWLINE 'group_by_security_group',NEWLINE 'group_by_tag_keys',NEWLINE 'group_by_tag_none',NEWLINE 'group_by_route53_names',NEWLINE 'group_by_rds_engine',NEWLINE 'group_by_rds_parameter_group',NEWLINE 'group_by_elasticache_engine',NEWLINE 'group_by_elasticache_cluster',NEWLINE 'group_by_elasticache_parameter_group',NEWLINE 'group_by_elasticache_replication_group',NEWLINE 'group_by_aws_account',NEWLINE ]NEWLINE for option in group_by_options:NEWLINE if config.has_option('ec2', option):NEWLINE setattr(self, option, config.getboolean('ec2', option))NEWLINE else:NEWLINE setattr(self, option, True)NEWLINENEWLINE # Do we need to just include hosts that match a pattern?NEWLINE try:NEWLINE pattern_include = config.get('ec2', 'pattern_include')NEWLINE if pattern_include and len(pattern_include) > 0:NEWLINE self.pattern_include = re.compile(pattern_include)NEWLINE else:NEWLINE self.pattern_include = NoneNEWLINE except configparser.NoOptionError:NEWLINE self.pattern_include = NoneNEWLINENEWLINE # Do we need to exclude hosts that match a pattern?NEWLINE try:NEWLINE pattern_exclude = config.get('ec2', 'pattern_exclude')NEWLINE if pattern_exclude and len(pattern_exclude) > 0:NEWLINE self.pattern_exclude = re.compile(pattern_exclude)NEWLINE else:NEWLINE self.pattern_exclude = NoneNEWLINE except configparser.NoOptionError:NEWLINE self.pattern_exclude = NoneNEWLINENEWLINE # Do we want to stack multiple filters?NEWLINE if config.has_option('ec2', 'stack_filters'):NEWLINE self.stack_filters = config.getboolean('ec2', 'stack_filters')NEWLINE else:NEWLINE self.stack_filters = FalseNEWLINENEWLINE # Instance filters (see boto and EC2 API docs). Ignore invalid filters.NEWLINE self.ec2_instance_filters = defaultdict(list)NEWLINE if config.has_option('ec2', 'instance_filters'):NEWLINENEWLINE filters = [f for f in config.get('ec2', 'instance_filters').split(',') if f]NEWLINENEWLINE for instance_filter in filters:NEWLINE instance_filter = instance_filter.strip()NEWLINE if not instance_filter or '=' not in instance_filter:NEWLINE continueNEWLINE filter_key, filter_value = [x.strip() for x in instance_filter.split('=', 1)]NEWLINE if not filter_key:NEWLINE continueNEWLINE self.ec2_instance_filters[filter_key].append(filter_value)NEWLINENEWLINE def parse_cli_args(self):NEWLINE ''' Command line argument processing '''NEWLINENEWLINE parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on EC2')NEWLINE parser.add_argument('--list', action='store_true', default=True,NEWLINE help='List instances (default: True)')NEWLINE parser.add_argument('--host', action='store',NEWLINE help='Get all the variables about a specific instance')NEWLINE parser.add_argument('--refresh-cache', action='store_true', default=False,NEWLINE help='Force refresh of cache by making API requests to EC2 (default: False - use cache files)')NEWLINE parser.add_argument('--profile', '--boto-profile', action='store', dest='boto_profile',NEWLINE help='Use boto profile for connections to EC2')NEWLINE self.args = parser.parse_args()NEWLINENEWLINE def do_api_calls_update_cache(self):NEWLINE ''' Do API calls to each region, and save data in cache files '''NEWLINENEWLINE if self.route53_enabled:NEWLINE self.get_route53_records()NEWLINENEWLINE for region in self.regions:NEWLINE self.get_instances_by_region(region)NEWLINE if self.rds_enabled:NEWLINE self.get_rds_instances_by_region(region)NEWLINE if self.elasticache_enabled:NEWLINE self.get_elasticache_clusters_by_region(region)NEWLINE self.get_elasticache_replication_groups_by_region(region)NEWLINE if self.include_rds_clusters:NEWLINE self.include_rds_clusters_by_region(region)NEWLINENEWLINE self.write_to_cache(self.inventory, self.cache_path_cache)NEWLINE self.write_to_cache(self.index, self.cache_path_index)NEWLINENEWLINE def connect(self, region):NEWLINE ''' create connection to api server'''NEWLINE if self.eucalyptus:NEWLINE conn = boto.connect_euca(host=self.eucalyptus_host, **self.credentials)NEWLINE conn.APIVersion = '2010-08-31'NEWLINE else:NEWLINE conn = self.connect_to_aws(ec2, region)NEWLINE return connNEWLINENEWLINE def boto_fix_security_token_in_profile(self, connect_args):NEWLINE ''' monkey patch for boto issue boto/boto#2100 '''NEWLINE profile = 'profile ' + self.boto_profileNEWLINE if boto.config.has_option(profile, 'aws_security_token'):NEWLINE connect_args['security_token'] = boto.config.get(profile, 'aws_security_token')NEWLINE return connect_argsNEWLINENEWLINE def connect_to_aws(self, module, region):NEWLINE connect_args = self.credentialsNEWLINENEWLINE # only pass the profile name if it's set (as it is not supported by older boto versions)NEWLINE if self.boto_profile:NEWLINE connect_args['profile_name'] = self.boto_profileNEWLINE self.boto_fix_security_token_in_profile(connect_args)NEWLINENEWLINE if self.iam_role:NEWLINE sts_conn = sts.connect_to_region(region, **connect_args)NEWLINE role = sts_conn.assume_role(self.iam_role, 'ansible_dynamic_inventory')NEWLINE connect_args['aws_access_key_id'] = role.credentials.access_keyNEWLINE connect_args['aws_secret_access_key'] = role.credentials.secret_keyNEWLINE connect_args['security_token'] = role.credentials.session_tokenNEWLINENEWLINE conn = module.connect_to_region(region, **connect_args)NEWLINE # connect_to_region will fail "silently" by returning None if the region name is wrong or not supportedNEWLINE if conn is None:NEWLINE self.fail_with_error("region name: %s likely not supported, or AWS is down. connection to region failed." % region)NEWLINE return connNEWLINENEWLINE def get_instances_by_region(self, region):NEWLINE ''' Makes an AWS EC2 API call to the list of instances in a particularNEWLINE region '''NEWLINENEWLINE try:NEWLINE conn = self.connect(region)NEWLINE reservations = []NEWLINE if self.ec2_instance_filters:NEWLINE if self.stack_filters:NEWLINE filters_dict = {}NEWLINE for filter_key, filter_values in self.ec2_instance_filters.items():NEWLINE filters_dict[filter_key] = filter_valuesNEWLINE reservations.extend(conn.get_all_instances(filters=filters_dict))NEWLINE else:NEWLINE for filter_key, filter_values in self.ec2_instance_filters.items():NEWLINE reservations.extend(conn.get_all_instances(filters={filter_key: filter_values}))NEWLINE else:NEWLINE reservations = conn.get_all_instances()NEWLINENEWLINE # Pull the tags back in a second stepNEWLINE # AWS are on record as saying that the tags fetched in the first `get_all_instances` request are notNEWLINE # reliable and may be missing, and the only way to guarantee they are there is by calling `get_all_tags`NEWLINE instance_ids = []NEWLINE for reservation in reservations:NEWLINE instance_ids.extend([instance.id for instance in reservation.instances])NEWLINENEWLINE max_filter_value = 199NEWLINE tags = []NEWLINE for i in range(0, len(instance_ids), max_filter_value):NEWLINE tags.extend(conn.get_all_tags(filters={'resource-type': 'instance', 'resource-id': instance_ids[i:i + max_filter_value]}))NEWLINENEWLINE tags_by_instance_id = defaultdict(dict)NEWLINE for tag in tags:NEWLINE tags_by_instance_id[tag.res_id][tag.name] = tag.valueNEWLINENEWLINE if (not self.aws_account_id) and reservations:NEWLINE self.aws_account_id = reservations[0].owner_idNEWLINENEWLINE for reservation in reservations:NEWLINE for instance in reservation.instances:NEWLINE instance.tags = tags_by_instance_id[instance.id]NEWLINE self.add_instance(instance, region)NEWLINENEWLINE except boto.exception.BotoServerError as e:NEWLINE if e.error_code == 'AuthFailure':NEWLINE error = self.get_auth_error_message()NEWLINE else:NEWLINE backend = 'Eucalyptus' if self.eucalyptus else 'AWS'NEWLINE error = "Error connecting to %s backend.\n%s" % (backend, e.message)NEWLINE self.fail_with_error(error, 'getting EC2 instances')NEWLINENEWLINE def get_rds_instances_by_region(self, region):NEWLINE ''' Makes an AWS API call to the list of RDS instances in a particularNEWLINE region '''NEWLINENEWLINE if not HAS_BOTO3:NEWLINE self.fail_with_error("Working with RDS instances requires boto3 - please install boto3 and try again",NEWLINE "getting RDS instances")NEWLINENEWLINE client = ec2_utils.boto3_inventory_conn('client', 'rds', region, **self.credentials)NEWLINE db_instances = client.describe_db_instances()NEWLINENEWLINE try:NEWLINE conn = self.connect_to_aws(rds, region)NEWLINE if conn:NEWLINE marker = NoneNEWLINE while True:NEWLINE instances = conn.get_all_dbinstances(marker=marker)NEWLINE marker = instances.markerNEWLINE for index, instance in enumerate(instances):NEWLINE # Add tags to instances.NEWLINE instance.arn = db_instances['DBInstances'][index]['DBInstanceArn']NEWLINE tags = client.list_tags_for_resource(ResourceName=instance.arn)['TagList']NEWLINE instance.tags = {}NEWLINE for tag in tags:NEWLINE instance.tags[tag['Key']] = tag['Value']NEWLINENEWLINE self.add_rds_instance(instance, region)NEWLINE if not marker:NEWLINE breakNEWLINE except boto.exception.BotoServerError as e:NEWLINE error = e.reasonNEWLINENEWLINE if e.error_code == 'AuthFailure':NEWLINE error = self.get_auth_error_message()NEWLINE elif e.error_code == "OptInRequired":NEWLINE error = "RDS hasn't been enabled for this account yet. " \NEWLINE "You must either log in to the RDS service through the AWS console to enable it, " \NEWLINE "or set 'rds = False' in ec2.ini"NEWLINE elif not e.reason == "Forbidden":NEWLINE error = "Looks like AWS RDS is down:\n%s" % e.messageNEWLINE self.fail_with_error(error, 'getting RDS instances')NEWLINENEWLINE def include_rds_clusters_by_region(self, region):NEWLINE if not HAS_BOTO3:NEWLINE self.fail_with_error("Working with RDS clusters requires boto3 - please install boto3 and try again",NEWLINE "getting RDS clusters")NEWLINENEWLINE client = ec2_utils.boto3_inventory_conn('client', 'rds', region, **self.credentials)NEWLINENEWLINE marker, clusters = '', []NEWLINE while marker is not None:NEWLINE resp = client.describe_db_clusters(Marker=marker)NEWLINE clusters.extend(resp["DBClusters"])NEWLINE marker = resp.get('Marker', None)NEWLINENEWLINE account_id = boto.connect_iam().get_user().arn.split(':')[4]NEWLINE c_dict = {}NEWLINE for c in clusters:NEWLINE # remove these datetime objects as there is no serialisation to jsonNEWLINE # currently in place and we don't need the data yetNEWLINE if 'EarliestRestorableTime' in c:NEWLINE del c['EarliestRestorableTime']NEWLINE if 'LatestRestorableTime' in c:NEWLINE del c['LatestRestorableTime']NEWLINENEWLINE if self.ec2_instance_filters == {}:NEWLINE matches_filter = TrueNEWLINE else:NEWLINE matches_filter = FalseNEWLINENEWLINE try:NEWLINE # arn:aws:rds:<region>:<account number>:<resourcetype>:<name>NEWLINE tags = client.list_tags_for_resource(NEWLINE ResourceName='arn:aws:rds:' + region + ':' + account_id + ':cluster:' + c['DBClusterIdentifier'])NEWLINE c['Tags'] = tags['TagList']NEWLINENEWLINE if self.ec2_instance_filters:NEWLINE for filter_key, filter_values in self.ec2_instance_filters.items():NEWLINE # get AWS tag key e.g. tag:env will be 'env'NEWLINE tag_name = filter_key.split(":", 1)[1]NEWLINE # Filter values is a list (if you put multiple values for the same tag name)NEWLINE matches_filter = any(d['Key'] == tag_name and d['Value'] in filter_values for d in c['Tags'])NEWLINENEWLINE if matches_filter:NEWLINE # it matches a filter, so stop looking for further matchesNEWLINE breakNEWLINENEWLINE except Exception as e:NEWLINE if e.message.find('DBInstanceNotFound') >= 0:NEWLINE # AWS RDS bug (2016-01-06) means deletion does not fully complete and leave an 'empty' cluster.NEWLINE # Ignore errors when trying to find tags for theseNEWLINE passNEWLINENEWLINE # ignore empty clusters caused by AWS bugNEWLINE if len(c['DBClusterMembers']) == 0:NEWLINE continueNEWLINE elif matches_filter:NEWLINE c_dict[c['DBClusterIdentifier']] = cNEWLINENEWLINE self.inventory['db_clusters'] = c_dictNEWLINENEWLINE def get_elasticache_clusters_by_region(self, region):NEWLINE ''' Makes an AWS API call to the list of ElastiCache clusters (withNEWLINE nodes' info) in a particular region.'''NEWLINENEWLINE # ElastiCache boto module doesn't provide a get_all_instances method,NEWLINE # that's why we need to call describe directly (it would be called byNEWLINE # the shorthand method anyway...)NEWLINE try:NEWLINE conn = self.connect_to_aws(elasticache, region)NEWLINE if conn:NEWLINE # show_cache_node_info = TrueNEWLINE # because we also want nodes' informationNEWLINE response = conn.describe_cache_clusters(None, None, None, True)NEWLINENEWLINE except boto.exception.BotoServerError as e:NEWLINE error = e.reasonNEWLINENEWLINE if e.error_code == 'AuthFailure':NEWLINE error = self.get_auth_error_message()NEWLINE elif e.error_code == "OptInRequired":NEWLINE error = "ElastiCache hasn't been enabled for this account yet. " \NEWLINE "You must either log in to the ElastiCache service through the AWS console to enable it, " \NEWLINE "or set 'elasticache = False' in ec2.ini"NEWLINE elif not e.reason == "Forbidden":NEWLINE error = "Looks like AWS ElastiCache is down:\n%s" % e.messageNEWLINE self.fail_with_error(error, 'getting ElastiCache clusters')NEWLINENEWLINE try:NEWLINE # Boto also doesn't provide wrapper classes to CacheClusters orNEWLINE # CacheNodes. Because of that we can't make use of the get_listNEWLINE # method in the AWSQueryConnection. Let's do the work manuallyNEWLINE clusters = response['DescribeCacheClustersResponse']['DescribeCacheClustersResult']['CacheClusters']NEWLINENEWLINE except KeyError as e:NEWLINE error = "ElastiCache query to AWS failed (unexpected format)."NEWLINE self.fail_with_error(error, 'getting ElastiCache clusters')NEWLINENEWLINE for cluster in clusters:NEWLINE self.add_elasticache_cluster(cluster, region)NEWLINENEWLINE def get_elasticache_replication_groups_by_region(self, region):NEWLINE ''' Makes an AWS API call to the list of ElastiCache replication groupsNEWLINE in a particular region.'''NEWLINENEWLINE # ElastiCache boto module doesn't provide a get_all_instances method,NEWLINE # that's why we need to call describe directly (it would be called byNEWLINE # the shorthand method anyway...)NEWLINE try:NEWLINE conn = self.connect_to_aws(elasticache, region)NEWLINE if conn:NEWLINE response = conn.describe_replication_groups()NEWLINENEWLINE except boto.exception.BotoServerError as e:NEWLINE error = e.reasonNEWLINENEWLINE if e.error_code == 'AuthFailure':NEWLINE error = self.get_auth_error_message()NEWLINE if not e.reason == "Forbidden":NEWLINE error = "Looks like AWS ElastiCache [Replication Groups] is down:\n%s" % e.messageNEWLINE self.fail_with_error(error, 'getting ElastiCache clusters')NEWLINENEWLINE try:NEWLINE # Boto also doesn't provide wrapper classes to ReplicationGroupsNEWLINE # Because of that we can't make use of the get_list method in theNEWLINE # AWSQueryConnection. Let's do the work manuallyNEWLINE replication_groups = response['DescribeReplicationGroupsResponse']['DescribeReplicationGroupsResult']['ReplicationGroups']NEWLINENEWLINE except KeyError as e:NEWLINE error = "ElastiCache [Replication Groups] query to AWS failed (unexpected format)."NEWLINE self.fail_with_error(error, 'getting ElastiCache clusters')NEWLINENEWLINE for replication_group in replication_groups:NEWLINE self.add_elasticache_replication_group(replication_group, region)NEWLINENEWLINE def get_auth_error_message(self):NEWLINE ''' create an informative error message if there is an issue authenticating'''NEWLINE errors = ["Authentication error retrieving ec2 inventory."]NEWLINE if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]:NEWLINE errors.append(' - No AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment vars found')NEWLINE else:NEWLINE errors.append(' - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment vars found but may not be correct')NEWLINENEWLINE boto_paths = ['/etc/boto.cfg', '~/.boto', '~/.aws/credentials']NEWLINE boto_config_found = list(p for p in boto_paths if os.path.isfile(os.path.expanduser(p)))NEWLINE if len(boto_config_found) > 0:NEWLINE errors.append(" - Boto configs found at '%s', but the credentials contained may not be correct" % ', '.join(boto_config_found))NEWLINE else:NEWLINE errors.append(" - No Boto config found at any expected location '%s'" % ', '.join(boto_paths))NEWLINENEWLINE return '\n'.join(errors)NEWLINENEWLINE def fail_with_error(self, err_msg, err_operation=None):NEWLINE '''log an error to std err for ansible-playbook to consume and exit'''NEWLINE if err_operation:NEWLINE err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format(NEWLINE err_msg=err_msg, err_operation=err_operation)NEWLINE sys.stderr.write(err_msg)NEWLINE sys.exit(1)NEWLINENEWLINE def get_instance(self, region, instance_id):NEWLINE conn = self.connect(region)NEWLINENEWLINE reservations = conn.get_all_instances([instance_id])NEWLINE for reservation in reservations:NEWLINE for instance in reservation.instances:NEWLINE return instanceNEWLINENEWLINE def add_instance(self, instance, region):NEWLINE ''' Adds an instance to the inventory and index, as long as it isNEWLINE addressable '''NEWLINENEWLINE # Only return instances with desired instance statesNEWLINE if instance.state not in self.ec2_instance_states:NEWLINE returnNEWLINENEWLINE # Select the best destination addressNEWLINE if self.destination_format and self.destination_format_tags:NEWLINE dest = self.destination_format.format(*[getattr(instance, 'tags').get(tag, '') for tag in self.destination_format_tags])NEWLINE elif instance.subnet_id:NEWLINE dest = getattr(instance, self.vpc_destination_variable, None)NEWLINE if dest is None:NEWLINE dest = getattr(instance, 'tags').get(self.vpc_destination_variable, None)NEWLINE else:NEWLINE dest = getattr(instance, self.destination_variable, None)NEWLINE if dest is None:NEWLINE dest = getattr(instance, 'tags').get(self.destination_variable, None)NEWLINENEWLINE if not dest:NEWLINE # Skip instances we cannot address (e.g. private VPC subnet)NEWLINE returnNEWLINENEWLINE # Set the inventory nameNEWLINE hostname = NoneNEWLINE if self.hostname_variable:NEWLINE if self.hostname_variable.startswith('tag_'):NEWLINE hostname = instance.tags.get(self.hostname_variable[4:], None)NEWLINE else:NEWLINE hostname = getattr(instance, self.hostname_variable)NEWLINENEWLINE # set the hostname from route53NEWLINE if self.route53_enabled and self.route53_hostnames:NEWLINE route53_names = self.get_instance_route53_names(instance)NEWLINE for name in route53_names:NEWLINE if name.endswith(self.route53_hostnames):NEWLINE hostname = nameNEWLINENEWLINE # If we can't get a nice hostname, use the destination addressNEWLINE if not hostname:NEWLINE hostname = destNEWLINE # to_safe strips hostname characters like dots, so don't strip route53 hostnamesNEWLINE elif self.route53_enabled and self.route53_hostnames and hostname.endswith(self.route53_hostnames):NEWLINE hostname = hostname.lower()NEWLINE else:NEWLINE hostname = self.to_safe(hostname).lower()NEWLINENEWLINE # if we only want to include hosts that match a pattern, skip those that don'tNEWLINE if self.pattern_include and not self.pattern_include.match(hostname):NEWLINE returnNEWLINENEWLINE # if we need to exclude hosts that match a pattern, skip thoseNEWLINE if self.pattern_exclude and self.pattern_exclude.match(hostname):NEWLINE returnNEWLINENEWLINE # Add to indexNEWLINE self.index[hostname] = [region, instance.id]NEWLINENEWLINE # Inventory: Group by instance ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[instance.id] = [hostname]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', instance.id)NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region:NEWLINE self.push(self.inventory, region, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zoneNEWLINE if self.group_by_availability_zone:NEWLINE self.push(self.inventory, instance.placement, hostname)NEWLINE if self.nested_groups:NEWLINE if self.group_by_region:NEWLINE self.push_group(self.inventory, region, instance.placement)NEWLINE self.push_group(self.inventory, 'zones', instance.placement)NEWLINENEWLINE # Inventory: Group by Amazon Machine Image (AMI) IDNEWLINE if self.group_by_ami_id:NEWLINE ami_id = self.to_safe(instance.image_id)NEWLINE self.push(self.inventory, ami_id, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'images', ami_id)NEWLINENEWLINE # Inventory: Group by instance typeNEWLINE if self.group_by_instance_type:NEWLINE type_name = self.to_safe('type_' + instance.instance_type)NEWLINE self.push(self.inventory, type_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'types', type_name)NEWLINENEWLINE # Inventory: Group by instance stateNEWLINE if self.group_by_instance_state:NEWLINE state_name = self.to_safe('instance_state_' + instance.state)NEWLINE self.push(self.inventory, state_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instance_states', state_name)NEWLINENEWLINE # Inventory: Group by key pairNEWLINE if self.group_by_key_pair and instance.key_name:NEWLINE key_name = self.to_safe('key_' + instance.key_name)NEWLINE self.push(self.inventory, key_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'keys', key_name)NEWLINENEWLINE # Inventory: Group by VPCNEWLINE if self.group_by_vpc_id and instance.vpc_id:NEWLINE vpc_id_name = self.to_safe('vpc_id_' + instance.vpc_id)NEWLINE self.push(self.inventory, vpc_id_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'vpcs', vpc_id_name)NEWLINENEWLINE # Inventory: Group by security groupNEWLINE if self.group_by_security_group:NEWLINE try:NEWLINE for group in instance.groups:NEWLINE key = self.to_safe("security_group_" + group.name)NEWLINE self.push(self.inventory, key, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'security_groups', key)NEWLINE except AttributeError:NEWLINE self.fail_with_error('\n'.join(['Package boto seems a bit older.',NEWLINE 'Please upgrade boto >= 2.3.0.']))NEWLINENEWLINE # Inventory: Group by AWS account IDNEWLINE if self.group_by_aws_account:NEWLINE self.push(self.inventory, self.aws_account_id, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'accounts', self.aws_account_id)NEWLINENEWLINE # Inventory: Group by tag keysNEWLINE if self.group_by_tag_keys:NEWLINE for k, v in instance.tags.items():NEWLINE if self.expand_csv_tags and v and ',' in v:NEWLINE values = map(lambda x: x.strip(), v.split(','))NEWLINE else:NEWLINE values = [v]NEWLINENEWLINE for v in values:NEWLINE if v:NEWLINE key = self.to_safe("tag_" + k + "=" + v)NEWLINE else:NEWLINE key = self.to_safe("tag_" + k)NEWLINE self.push(self.inventory, key, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'tags', self.to_safe("tag_" + k))NEWLINE if v:NEWLINE self.push_group(self.inventory, self.to_safe("tag_" + k), key)NEWLINENEWLINE # Inventory: Group by Route53 domain names if enabledNEWLINE if self.route53_enabled and self.group_by_route53_names:NEWLINE route53_names = self.get_instance_route53_names(instance)NEWLINE for name in route53_names:NEWLINE self.push(self.inventory, name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'route53', name)NEWLINENEWLINE # Global Tag: instances without tagsNEWLINE if self.group_by_tag_none and len(instance.tags) == 0:NEWLINE self.push(self.inventory, 'tag_none', hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'tags', 'tag_none')NEWLINENEWLINE # Global Tag: tag all EC2 instancesNEWLINE self.push(self.inventory, 'ec2', hostname)NEWLINENEWLINE self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance)NEWLINE self.inventory["_meta"]["hostvars"][hostname]['ansible_host'] = destNEWLINENEWLINE def add_rds_instance(self, instance, region):NEWLINE ''' Adds an RDS instance to the inventory and index, as long as it isNEWLINE addressable '''NEWLINENEWLINE # Only want available instances unless all_rds_instances is TrueNEWLINE if not self.all_rds_instances and instance.status != 'available':NEWLINE returnNEWLINENEWLINE # Select the best destination addressNEWLINE dest = instance.endpoint[0]NEWLINENEWLINE if not dest:NEWLINE # Skip instances we cannot address (e.g. private VPC subnet)NEWLINE returnNEWLINENEWLINE # Set the inventory nameNEWLINE hostname = NoneNEWLINE if self.hostname_variable:NEWLINE if self.hostname_variable.startswith('tag_'):NEWLINE hostname = instance.tags.get(self.hostname_variable[4:], None)NEWLINE else:NEWLINE hostname = getattr(instance, self.hostname_variable)NEWLINENEWLINE # If we can't get a nice hostname, use the destination addressNEWLINE if not hostname:NEWLINE hostname = destNEWLINENEWLINE hostname = self.to_safe(hostname).lower()NEWLINENEWLINE # Add to indexNEWLINE self.index[hostname] = [region, instance.id]NEWLINENEWLINE # Inventory: Group by instance ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[instance.id] = [hostname]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', instance.id)NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region:NEWLINE self.push(self.inventory, region, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zoneNEWLINE if self.group_by_availability_zone:NEWLINE self.push(self.inventory, instance.availability_zone, hostname)NEWLINE if self.nested_groups:NEWLINE if self.group_by_region:NEWLINE self.push_group(self.inventory, region, instance.availability_zone)NEWLINE self.push_group(self.inventory, 'zones', instance.availability_zone)NEWLINENEWLINE # Inventory: Group by instance typeNEWLINE if self.group_by_instance_type:NEWLINE type_name = self.to_safe('type_' + instance.instance_class)NEWLINE self.push(self.inventory, type_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'types', type_name)NEWLINENEWLINE # Inventory: Group by VPCNEWLINE if self.group_by_vpc_id and instance.subnet_group and instance.subnet_group.vpc_id:NEWLINE vpc_id_name = self.to_safe('vpc_id_' + instance.subnet_group.vpc_id)NEWLINE self.push(self.inventory, vpc_id_name, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'vpcs', vpc_id_name)NEWLINENEWLINE # Inventory: Group by security groupNEWLINE if self.group_by_security_group:NEWLINE try:NEWLINE if instance.security_group:NEWLINE key = self.to_safe("security_group_" + instance.security_group.name)NEWLINE self.push(self.inventory, key, hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'security_groups', key)NEWLINENEWLINE except AttributeError:NEWLINE self.fail_with_error('\n'.join(['Package boto seems a bit older.',NEWLINE 'Please upgrade boto >= 2.3.0.']))NEWLINENEWLINE # Inventory: Group by engineNEWLINE if self.group_by_rds_engine:NEWLINE self.push(self.inventory, self.to_safe("rds_" + instance.engine), hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'rds_engines', self.to_safe("rds_" + instance.engine))NEWLINENEWLINE # Inventory: Group by parameter groupNEWLINE if self.group_by_rds_parameter_group:NEWLINE self.push(self.inventory, self.to_safe("rds_parameter_group_" + instance.parameter_group.name), hostname)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'rds_parameter_groups', self.to_safe("rds_parameter_group_" + instance.parameter_group.name))NEWLINENEWLINE # Global Tag: all RDS instancesNEWLINE self.push(self.inventory, 'rds', hostname)NEWLINENEWLINE self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance)NEWLINE self.inventory["_meta"]["hostvars"][hostname]['ansible_host'] = destNEWLINENEWLINE def add_elasticache_cluster(self, cluster, region):NEWLINE ''' Adds an ElastiCache cluster to the inventory and index, as long asNEWLINE it's nodes are addressable '''NEWLINENEWLINE # Only want available clusters unless all_elasticache_clusters is TrueNEWLINE if not self.all_elasticache_clusters and cluster['CacheClusterStatus'] != 'available':NEWLINE returnNEWLINENEWLINE # Select the best destination addressNEWLINE if 'ConfigurationEndpoint' in cluster and cluster['ConfigurationEndpoint']:NEWLINE # Memcached clusterNEWLINE dest = cluster['ConfigurationEndpoint']['Address']NEWLINE is_redis = FalseNEWLINE else:NEWLINE # Redis sigle node clusterNEWLINE # Because all Redis clusters are single nodes, we'll merge theNEWLINE # info from the cluster with info about the nodeNEWLINE dest = cluster['CacheNodes'][0]['Endpoint']['Address']NEWLINE is_redis = TrueNEWLINENEWLINE if not dest:NEWLINE # Skip clusters we cannot address (e.g. private VPC subnet)NEWLINE returnNEWLINENEWLINE # Add to indexNEWLINE self.index[dest] = [region, cluster['CacheClusterId']]NEWLINENEWLINE # Inventory: Group by instance ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[cluster['CacheClusterId']] = [dest]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', cluster['CacheClusterId'])NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region and not is_redis:NEWLINE self.push(self.inventory, region, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zoneNEWLINE if self.group_by_availability_zone and not is_redis:NEWLINE self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest)NEWLINE if self.nested_groups:NEWLINE if self.group_by_region:NEWLINE self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone'])NEWLINE self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone'])NEWLINENEWLINE # Inventory: Group by node typeNEWLINE if self.group_by_instance_type and not is_redis:NEWLINE type_name = self.to_safe('type_' + cluster['CacheNodeType'])NEWLINE self.push(self.inventory, type_name, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'types', type_name)NEWLINENEWLINE # Inventory: Group by VPC (information not available in the currentNEWLINE # AWS API version for ElastiCache)NEWLINENEWLINE # Inventory: Group by security groupNEWLINE if self.group_by_security_group and not is_redis:NEWLINENEWLINE # Check for the existence of the 'SecurityGroups' key and also ifNEWLINE # this key has some value. When the cluster is not placed in a SGNEWLINE # the query can return None here and cause an error.NEWLINE if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None:NEWLINE for security_group in cluster['SecurityGroups']:NEWLINE key = self.to_safe("security_group_" + security_group['SecurityGroupId'])NEWLINE self.push(self.inventory, key, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'security_groups', key)NEWLINENEWLINE # Inventory: Group by engineNEWLINE if self.group_by_elasticache_engine and not is_redis:NEWLINE self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_engines', self.to_safe(cluster['Engine']))NEWLINENEWLINE # Inventory: Group by parameter groupNEWLINE if self.group_by_elasticache_parameter_group:NEWLINE self.push(self.inventory, self.to_safe("elasticache_parameter_group_" + cluster['CacheParameterGroup']['CacheParameterGroupName']), dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_parameter_groups', self.to_safe(cluster['CacheParameterGroup']['CacheParameterGroupName']))NEWLINENEWLINE # Inventory: Group by replication groupNEWLINE if self.group_by_elasticache_replication_group and 'ReplicationGroupId' in cluster and cluster['ReplicationGroupId']:NEWLINE self.push(self.inventory, self.to_safe("elasticache_replication_group_" + cluster['ReplicationGroupId']), dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_replication_groups', self.to_safe(cluster['ReplicationGroupId']))NEWLINENEWLINE # Global Tag: all ElastiCache clustersNEWLINE self.push(self.inventory, 'elasticache_clusters', cluster['CacheClusterId'])NEWLINENEWLINE host_info = self.get_host_info_dict_from_describe_dict(cluster)NEWLINENEWLINE self.inventory["_meta"]["hostvars"][dest] = host_infoNEWLINENEWLINE # Add the nodesNEWLINE for node in cluster['CacheNodes']:NEWLINE self.add_elasticache_node(node, cluster, region)NEWLINENEWLINE def add_elasticache_node(self, node, cluster, region):NEWLINE ''' Adds an ElastiCache node to the inventory and index, as long asNEWLINE it is addressable '''NEWLINENEWLINE # Only want available nodes unless all_elasticache_nodes is TrueNEWLINE if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available':NEWLINE returnNEWLINENEWLINE # Select the best destination addressNEWLINE dest = node['Endpoint']['Address']NEWLINENEWLINE if not dest:NEWLINE # Skip nodes we cannot address (e.g. private VPC subnet)NEWLINE returnNEWLINENEWLINE node_id = self.to_safe(cluster['CacheClusterId'] + '_' + node['CacheNodeId'])NEWLINENEWLINE # Add to indexNEWLINE self.index[dest] = [region, node_id]NEWLINENEWLINE # Inventory: Group by node ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[node_id] = [dest]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', node_id)NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region:NEWLINE self.push(self.inventory, region, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zoneNEWLINE if self.group_by_availability_zone:NEWLINE self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest)NEWLINE if self.nested_groups:NEWLINE if self.group_by_region:NEWLINE self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone'])NEWLINE self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone'])NEWLINENEWLINE # Inventory: Group by node typeNEWLINE if self.group_by_instance_type:NEWLINE type_name = self.to_safe('type_' + cluster['CacheNodeType'])NEWLINE self.push(self.inventory, type_name, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'types', type_name)NEWLINENEWLINE # Inventory: Group by VPC (information not available in the currentNEWLINE # AWS API version for ElastiCache)NEWLINENEWLINE # Inventory: Group by security groupNEWLINE if self.group_by_security_group:NEWLINENEWLINE # Check for the existence of the 'SecurityGroups' key and also ifNEWLINE # this key has some value. When the cluster is not placed in a SGNEWLINE # the query can return None here and cause an error.NEWLINE if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None:NEWLINE for security_group in cluster['SecurityGroups']:NEWLINE key = self.to_safe("security_group_" + security_group['SecurityGroupId'])NEWLINE self.push(self.inventory, key, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'security_groups', key)NEWLINENEWLINE # Inventory: Group by engineNEWLINE if self.group_by_elasticache_engine:NEWLINE self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_engines', self.to_safe("elasticache_" + cluster['Engine']))NEWLINENEWLINE # Inventory: Group by parameter group (done at cluster level)NEWLINENEWLINE # Inventory: Group by replication group (done at cluster level)NEWLINENEWLINE # Inventory: Group by ElastiCache ClusterNEWLINE if self.group_by_elasticache_cluster:NEWLINE self.push(self.inventory, self.to_safe("elasticache_cluster_" + cluster['CacheClusterId']), dest)NEWLINENEWLINE # Global Tag: all ElastiCache nodesNEWLINE self.push(self.inventory, 'elasticache_nodes', dest)NEWLINENEWLINE host_info = self.get_host_info_dict_from_describe_dict(node)NEWLINENEWLINE if dest in self.inventory["_meta"]["hostvars"]:NEWLINE self.inventory["_meta"]["hostvars"][dest].update(host_info)NEWLINE else:NEWLINE self.inventory["_meta"]["hostvars"][dest] = host_infoNEWLINENEWLINE def add_elasticache_replication_group(self, replication_group, region):NEWLINE ''' Adds an ElastiCache replication group to the inventory and index '''NEWLINENEWLINE # Only want available clusters unless all_elasticache_replication_groups is TrueNEWLINE if not self.all_elasticache_replication_groups and replication_group['Status'] != 'available':NEWLINE returnNEWLINENEWLINE # Skip clusters we cannot address (e.g. private VPC subnet or clustered redis)NEWLINE if replication_group['NodeGroups'][0]['PrimaryEndpoint'] is None or \NEWLINE replication_group['NodeGroups'][0]['PrimaryEndpoint']['Address'] is None:NEWLINE returnNEWLINENEWLINE # Select the best destination address (PrimaryEndpoint)NEWLINE dest = replication_group['NodeGroups'][0]['PrimaryEndpoint']['Address']NEWLINENEWLINE # Add to indexNEWLINE self.index[dest] = [region, replication_group['ReplicationGroupId']]NEWLINENEWLINE # Inventory: Group by ID (always a group of 1)NEWLINE if self.group_by_instance_id:NEWLINE self.inventory[replication_group['ReplicationGroupId']] = [dest]NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'instances', replication_group['ReplicationGroupId'])NEWLINENEWLINE # Inventory: Group by regionNEWLINE if self.group_by_region:NEWLINE self.push(self.inventory, region, dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'regions', region)NEWLINENEWLINE # Inventory: Group by availability zone (doesn't apply to replication groups)NEWLINENEWLINE # Inventory: Group by node type (doesn't apply to replication groups)NEWLINENEWLINE # Inventory: Group by VPC (information not available in the currentNEWLINE # AWS API version for replication groupsNEWLINENEWLINE # Inventory: Group by security group (doesn't apply to replication groups)NEWLINE # Check this value in cluster levelNEWLINENEWLINE # Inventory: Group by engine (replication groups are always Redis)NEWLINE if self.group_by_elasticache_engine:NEWLINE self.push(self.inventory, 'elasticache_redis', dest)NEWLINE if self.nested_groups:NEWLINE self.push_group(self.inventory, 'elasticache_engines', 'redis')NEWLINENEWLINE # Global Tag: all ElastiCache clustersNEWLINE self.push(self.inventory, 'elasticache_replication_groups', replication_group['ReplicationGroupId'])NEWLINENEWLINE host_info = self.get_host_info_dict_from_describe_dict(replication_group)NEWLINENEWLINE self.inventory["_meta"]["hostvars"][dest] = host_infoNEWLINENEWLINE def get_route53_records(self):NEWLINE ''' Get and store the map of resource records to domain names thatNEWLINE point to them. '''NEWLINENEWLINE if self.boto_profile:NEWLINE r53_conn = route53.Route53Connection(profile_name=self.boto_profile)NEWLINE else:NEWLINE r53_conn = route53.Route53Connection()NEWLINE all_zones = r53_conn.get_zones()NEWLINENEWLINE route53_zones = [zone for zone in all_zones if zone.name[:-1] not in self.route53_excluded_zones]NEWLINENEWLINE self.route53_records = {}NEWLINENEWLINE for zone in route53_zones:NEWLINE rrsets = r53_conn.get_all_rrsets(zone.id)NEWLINENEWLINE for record_set in rrsets:NEWLINE record_name = record_set.nameNEWLINENEWLINE if record_name.endswith('.'):NEWLINE record_name = record_name[:-1]NEWLINENEWLINE for resource in record_set.resource_records:NEWLINE self.route53_records.setdefault(resource, set())NEWLINE self.route53_records[resource].add(record_name)NEWLINENEWLINE def get_instance_route53_names(self, instance):NEWLINE ''' Check if an instance is referenced in the records we have fromNEWLINE Route53. If it is, return the list of domain names pointing to saidNEWLINE instance. If nothing points to it, return an empty list. '''NEWLINENEWLINE instance_attributes = ['public_dns_name', 'private_dns_name',NEWLINE 'ip_address', 'private_ip_address']NEWLINENEWLINE name_list = set()NEWLINENEWLINE for attrib in instance_attributes:NEWLINE try:NEWLINE value = getattr(instance, attrib)NEWLINE except AttributeError:NEWLINE continueNEWLINENEWLINE if value in self.route53_records:NEWLINE name_list.update(self.route53_records[value])NEWLINENEWLINE return list(name_list)NEWLINENEWLINE def get_host_info_dict_from_instance(self, instance):NEWLINE instance_vars = {}NEWLINE for key in vars(instance):NEWLINE value = getattr(instance, key)NEWLINE key = self.to_safe('ec2_' + key)NEWLINENEWLINE # Handle complex typesNEWLINE # state/previous_state changed to properties in boto in https://github.com/boto/boto/commit/a23c379837f698212252720d2af8dec0325c9518NEWLINE if key == 'ec2__state':NEWLINE instance_vars['ec2_state'] = instance.state or ''NEWLINE instance_vars['ec2_state_code'] = instance.state_codeNEWLINE elif key == 'ec2__previous_state':NEWLINE instance_vars['ec2_previous_state'] = instance.previous_state or ''NEWLINE instance_vars['ec2_previous_state_code'] = instance.previous_state_codeNEWLINE elif isinstance(value, (int, bool)):NEWLINE instance_vars[key] = valueNEWLINE elif isinstance(value, six.string_types):NEWLINE instance_vars[key] = value.strip()NEWLINE elif value is None:NEWLINE instance_vars[key] = ''NEWLINE elif key == 'ec2_region':NEWLINE instance_vars[key] = value.nameNEWLINE elif key == 'ec2__placement':NEWLINE instance_vars['ec2_placement'] = value.zoneNEWLINE elif key == 'ec2_tags':NEWLINE for k, v in value.items():NEWLINE if self.expand_csv_tags and ',' in v:NEWLINE v = list(map(lambda x: x.strip(), v.split(',')))NEWLINE key = self.to_safe('ec2_tag_' + k)NEWLINE instance_vars[key] = vNEWLINE elif key == 'ec2_groups':NEWLINE group_ids = []NEWLINE group_names = []NEWLINE for group in value:NEWLINE group_ids.append(group.id)NEWLINE group_names.append(group.name)NEWLINE instance_vars["ec2_security_group_ids"] = ','.join([str(i) for i in group_ids])NEWLINE instance_vars["ec2_security_group_names"] = ','.join([str(i) for i in group_names])NEWLINE elif key == 'ec2_block_device_mapping':NEWLINE instance_vars["ec2_block_devices"] = {}NEWLINE for k, v in value.items():NEWLINE instance_vars["ec2_block_devices"][os.path.basename(k)] = v.volume_idNEWLINE else:NEWLINE passNEWLINE # TODO Product codes if someone finds them usefulNEWLINE # print keyNEWLINE # print type(value)NEWLINE # print valueNEWLINENEWLINE instance_vars[self.to_safe('ec2_account_id')] = self.aws_account_idNEWLINENEWLINE return instance_varsNEWLINENEWLINE def get_host_info_dict_from_describe_dict(self, describe_dict):NEWLINE ''' Parses the dictionary returned by the API call into a flat listNEWLINE of parameters. This method should be used only when 'describe' isNEWLINE used directly because Boto doesn't provide specific classes. '''NEWLINENEWLINE # I really don't agree with prefixing everything with 'ec2'NEWLINE # because EC2, RDS and ElastiCache are different services.NEWLINE # I'm just following the pattern used until now to not break anyNEWLINE # compatibility.NEWLINENEWLINE host_info = {}NEWLINE for key in describe_dict:NEWLINE value = describe_dict[key]NEWLINE key = self.to_safe('ec2_' + self.uncammelize(key))NEWLINENEWLINE # Handle complex typesNEWLINENEWLINE # Target: Memcached Cache ClustersNEWLINE if key == 'ec2_configuration_endpoint' and value:NEWLINE host_info['ec2_configuration_endpoint_address'] = value['Address']NEWLINE host_info['ec2_configuration_endpoint_port'] = value['Port']NEWLINENEWLINE # Target: Cache Nodes and Redis Cache Clusters (single node)NEWLINE if key == 'ec2_endpoint' and value:NEWLINE host_info['ec2_endpoint_address'] = value['Address']NEWLINE host_info['ec2_endpoint_port'] = value['Port']NEWLINENEWLINE # Target: Redis Replication GroupsNEWLINE if key == 'ec2_node_groups' and value:NEWLINE host_info['ec2_endpoint_address'] = value[0]['PrimaryEndpoint']['Address']NEWLINE host_info['ec2_endpoint_port'] = value[0]['PrimaryEndpoint']['Port']NEWLINE replica_count = 0NEWLINE for node in value[0]['NodeGroupMembers']:NEWLINE if node['CurrentRole'] == 'primary':NEWLINE host_info['ec2_primary_cluster_address'] = node['ReadEndpoint']['Address']NEWLINE host_info['ec2_primary_cluster_port'] = node['ReadEndpoint']['Port']NEWLINE host_info['ec2_primary_cluster_id'] = node['CacheClusterId']NEWLINE elif node['CurrentRole'] == 'replica':NEWLINE host_info['ec2_replica_cluster_address_' + str(replica_count)] = node['ReadEndpoint']['Address']NEWLINE host_info['ec2_replica_cluster_port_' + str(replica_count)] = node['ReadEndpoint']['Port']NEWLINE host_info['ec2_replica_cluster_id_' + str(replica_count)] = node['CacheClusterId']NEWLINE replica_count += 1NEWLINENEWLINE # Target: Redis Replication GroupsNEWLINE if key == 'ec2_member_clusters' and value:NEWLINE host_info['ec2_member_clusters'] = ','.join([str(i) for i in value])NEWLINENEWLINE # Target: All Cache ClustersNEWLINE elif key == 'ec2_cache_parameter_group':NEWLINE host_info["ec2_cache_node_ids_to_reboot"] = ','.join([str(i) for i in value['CacheNodeIdsToReboot']])NEWLINE host_info['ec2_cache_parameter_group_name'] = value['CacheParameterGroupName']NEWLINE host_info['ec2_cache_parameter_apply_status'] = value['ParameterApplyStatus']NEWLINENEWLINE # Target: Almost everythingNEWLINE elif key == 'ec2_security_groups':NEWLINENEWLINE # Skip if SecurityGroups is NoneNEWLINE # (it is possible to have the key defined but no value in it).NEWLINE if value is not None:NEWLINE sg_ids = []NEWLINE for sg in value:NEWLINE sg_ids.append(sg['SecurityGroupId'])NEWLINE host_info["ec2_security_group_ids"] = ','.join([str(i) for i in sg_ids])NEWLINENEWLINE # Target: EverythingNEWLINE # Preserve booleans and integersNEWLINE elif isinstance(value, (int, bool)):NEWLINE host_info[key] = valueNEWLINENEWLINE # Target: EverythingNEWLINE # Sanitize string valuesNEWLINE elif isinstance(value, six.string_types):NEWLINE host_info[key] = value.strip()NEWLINENEWLINE # Target: EverythingNEWLINE # Replace None by an empty stringNEWLINE elif value is None:NEWLINE host_info[key] = ''NEWLINENEWLINE else:NEWLINE # Remove non-processed complex typesNEWLINE passNEWLINENEWLINE return host_infoNEWLINENEWLINE def get_host_info(self):NEWLINE ''' Get variables about a specific host '''NEWLINENEWLINE if len(self.index) == 0:NEWLINE # Need to load index from cacheNEWLINE self.load_index_from_cache()NEWLINENEWLINE if self.args.host not in self.index:NEWLINE # try updating the cacheNEWLINE self.do_api_calls_update_cache()NEWLINE if self.args.host not in self.index:NEWLINE # host might not exist anymoreNEWLINE return self.json_format_dict({}, True)NEWLINENEWLINE (region, instance_id) = self.index[self.args.host]NEWLINENEWLINE instance = self.get_instance(region, instance_id)NEWLINE return self.json_format_dict(self.get_host_info_dict_from_instance(instance), True)NEWLINENEWLINE def push(self, my_dict, key, element):NEWLINE ''' Push an element onto an array that may not have been defined inNEWLINE the dict '''NEWLINE group_info = my_dict.setdefault(key, [])NEWLINE if isinstance(group_info, dict):NEWLINE host_list = group_info.setdefault('hosts', [])NEWLINE host_list.append(element)NEWLINE else:NEWLINE group_info.append(element)NEWLINENEWLINE def push_group(self, my_dict, key, element):NEWLINE ''' Push a group as a child of another group. '''NEWLINE parent_group = my_dict.setdefault(key, {})NEWLINE if not isinstance(parent_group, dict):NEWLINE parent_group = my_dict[key] = {'hosts': parent_group}NEWLINE child_groups = parent_group.setdefault('children', [])NEWLINE if element not in child_groups:NEWLINE child_groups.append(element)NEWLINENEWLINE def get_inventory_from_cache(self):NEWLINE ''' Reads the inventory from the cache file and returns it as a JSONNEWLINE object '''NEWLINENEWLINE with open(self.cache_path_cache, 'r') as f:NEWLINE json_inventory = f.read()NEWLINE return json_inventoryNEWLINENEWLINE def load_index_from_cache(self):NEWLINE ''' Reads the index from the cache file sets self.index '''NEWLINENEWLINE with open(self.cache_path_index, 'rb') as f:NEWLINE self.index = json.load(f)NEWLINENEWLINE def write_to_cache(self, data, filename):NEWLINE ''' Writes data in JSON format to a file '''NEWLINENEWLINE json_data = self.json_format_dict(data, True)NEWLINE with open(filename, 'w') as f:NEWLINE f.write(json_data)NEWLINENEWLINE def uncammelize(self, key):NEWLINE temp = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', key)NEWLINE return re.sub('([a-z0-9])([A-Z])', r'\1_\2', temp).lower()NEWLINENEWLINE def to_safe(self, word):NEWLINE ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups '''NEWLINE regex = "[^A-Za-z0-9\_"NEWLINE if not self.replace_dash_in_groups:NEWLINE regex += "\-"NEWLINE return re.sub(regex + "]", "_", word)NEWLINENEWLINE def json_format_dict(self, data, pretty=False):NEWLINE ''' Converts a dict to a JSON object and dumps it as a formattedNEWLINE string '''NEWLINENEWLINE if pretty:NEWLINE return json.dumps(data, sort_keys=True, indent=2)NEWLINE else:NEWLINE return json.dumps(data)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE # Run the scriptNEWLINE Ec2Inventory()NEWLINE |
#NEWLINE# Copyright (c) 2016-2021 JEP AUTHORS.NEWLINE#NEWLINE# This file is licensed under the the zlib/libpng License.NEWLINE#NEWLINE# This software is provided 'as-is', without any express or impliedNEWLINE# warranty. In no event will the authors be held liable for anyNEWLINE# damages arising from the use of this software.NEWLINE# NEWLINE# Permission is granted to anyone to use this software for anyNEWLINE# purpose, including commercial applications, and to alter it andNEWLINE# redistribute it freely, subject to the following restrictions:NEWLINE# NEWLINE# 1. The origin of this software must not be misrepresented; youNEWLINE# must not claim that you wrote the original software. If you useNEWLINE# this software in a product, an acknowledgment in the productNEWLINE# documentation would be appreciated but is not required.NEWLINE# NEWLINE# 2. Altered source versions must be plainly marked as such, andNEWLINE# must not be misrepresented as being the original software.NEWLINE# NEWLINE# 3. This notice may not be removed or altered from any sourceNEWLINE# distribution.NEWLINE#NEWLINENEWLINEimport sysNEWLINENEWLINEclass StreamRedirect(object):NEWLINE "Redirects a Python output stream to a Java OutputStream"NEWLINENEWLINE def __init__(self, javaOutputStream):NEWLINE from java.io import PrintStreamNEWLINE self.printstream = PrintStream(javaOutputStream)NEWLINE self.printmethod = getattr(self.printstream, 'print')NEWLINE self.flushmethod = getattr(self.printstream, 'flush')NEWLINENEWLINE def write(self, msg):NEWLINE self.printmethod(msg)NEWLINENEWLINE def flush(self):NEWLINE self.flushmethod()NEWLINENEWLINEdef redirectStdout(javaOutputStream):NEWLINE sys.stdout = StreamRedirect(javaOutputStream)NEWLINENEWLINEdef redirectStderr(javaOutputStream):NEWLINE sys.stderr = StreamRedirect(javaOutputStream)NEWLINE |
#!/usr/bin/env pythonNEWLINE#NEWLINE# Copyright 2015-2016 Rafael Ferreira da SilvaNEWLINE# http://www.rafaelsilva.com/toolsNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing,NEWLINE# software distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINE__author__ = "Rafael Ferreira da Silva"NEWLINENEWLINEimport unicodedataNEWLINEfrom tools.utils import *NEWLINENEWLINElog = logging.getLogger(__name__)NEWLINENEWLINENEWLINEclass EntryType:NEWLINE ARTICLE = "article"NEWLINE BOOK = "book"NEWLINE INCOLLECTION = "incollection"NEWLINE INPROCEEDINGS = "inproceedings"NEWLINE MASTERTHESIS = "mastersthesis"NEWLINE PHDTHESIS = "phdthesis"NEWLINE MISC = "misc"NEWLINE PROCEEDINGS = "proceedings"NEWLINE TECHREPORT = "techreport"NEWLINENEWLINENEWLINEclass Entry:NEWLINE def __init__(self, entry_type=None, cite_key=None, address=None, annote=None, authors=None, booktitle=None,NEWLINE chapter=None, crossref=None, edition=None, editor=None, howpublished=None, institution=None,NEWLINE journal=None, key=None, month=None, note=None, number=None, organization=None, pages=None,NEWLINE publisher=None, school=None, series=None, title=None, type=None, url=None, volume=None,NEWLINE year=None, doi=None):NEWLINE """NEWLINE Create a bib entry.NEWLINE :param entry_type: type of the entry (e.g., article, inproceedings, etc.)NEWLINE :param cite_key: cite key used in latex files to reference the entryNEWLINE :param address:NEWLINE :param annote:NEWLINE :param authors: list of authors (separated by 'and')NEWLINE :param booktitle: title of the conference bookNEWLINE :param chapter:NEWLINE :param crossref:NEWLINE :param edition:NEWLINE :param editors: list of editors (separated by 'and')NEWLINE :param howpublished:NEWLINE :param institution:NEWLINE :param journal: title of the journalNEWLINE :param key: publication key (usually required for 'misc' entry types)NEWLINE :param month:NEWLINE :param note:NEWLINE :param number: journal issue numberNEWLINE :param organization:NEWLINE :param pages: page numbers (separated by dashes)NEWLINE :param publisher:NEWLINE :param school:NEWLINE :param series:NEWLINE :param title: publication titleNEWLINE :param type:NEWLINE :param url: publication urlNEWLINE :param volume: journal volumeNEWLINE :param year: publication yearNEWLINE :param doi: document object identifierNEWLINE """NEWLINE self.entry_type = entry_typeNEWLINE self.cite_key = cite_keyNEWLINE self.address = addressNEWLINE self.annote = annoteNEWLINE self.authors = Authors(authors_list=authors)NEWLINE self.booktitle = _parse_booktitle(booktitle)NEWLINE self.chapter = chapterNEWLINE self.crossref = crossrefNEWLINE self.edition = editionNEWLINE self.editors = Authors(authors_list=editor)NEWLINE self.howpublished = howpublishedNEWLINE self.institution = institutionNEWLINE self.journal = journalNEWLINE self.key = keyNEWLINE self.month = monthNEWLINE self.note = noteNEWLINE self.number = numberNEWLINE self.organization = organizationNEWLINE self.pages = _parse_pages(pages)NEWLINE self.publisher = publisherNEWLINE self.school = schoolNEWLINE self.series = seriesNEWLINE self.title = titleNEWLINE self.type = typeNEWLINE self.url = urlNEWLINE self.volume = volumeNEWLINE self.year = yearNEWLINE self.doi = doiNEWLINE # Entry internal propertiesNEWLINE self.online_processed = FalseNEWLINE self.compressed = FalseNEWLINENEWLINE def merge(self, entry):NEWLINE """NEWLINE Merge two entries.NEWLINE :param entry: entry to be mergedNEWLINE """NEWLINE self.entry_type = _merge_entry_type(self.entry_type, entry.entry_type)NEWLINE self.address = _merge_field(self.address, entry.address)NEWLINE self.annote = _merge_field(self.annote, entry.annote)NEWLINE self.booktitle = _merge_field(self.booktitle, entry.booktitle)NEWLINE self.chapter = _merge_field(self.chapter, entry.chapter)NEWLINE self.crossref = _merge_field(self.crossref, entry.crossref)NEWLINE self.edition = _merge_field(self.edition, entry.edition)NEWLINE self.howpublished = _merge_field(self.howpublished, entry.howpublished)NEWLINE self.institution = _merge_field(self.institution, entry.institution)NEWLINE self.journal = _merge_field(self.journal, entry.journal)NEWLINE self.key = _merge_field(self.key, entry.key)NEWLINE self.month = _merge_field(self.month, entry.month)NEWLINE self.note = _merge_field(self.note, entry.note)NEWLINE self.number = _merge_field(self.number, entry.number, is_int=True)NEWLINE self.organization = _merge_field(self.organization, entry.organization)NEWLINE self.pages = _merge_field(self.pages, entry.pages)NEWLINE self.publisher = _merge_field(self.publisher, entry.publisher)NEWLINE self.school = _merge_field(self.school, entry.school)NEWLINE self.series = _merge_field(self.series, entry.series)NEWLINE self.title = _merge_field(self.title, entry.title)NEWLINE self.type = _merge_field(self.type, entry.type)NEWLINE self.url = _merge_field(self.url, entry.url)NEWLINE self.volume = _merge_field(self.volume, entry.volume)NEWLINE self.year = _merge_field(self.year, entry.year, is_int=True)NEWLINE self.doi = _merge_field(self.doi, entry.doi)NEWLINE self.editors.merge(entry.editors.authors)NEWLINE self.authors.merge(entry.authors.authors)NEWLINENEWLINE def __str__(self):NEWLINE entry_str = "@%s{%s,\n" % (self.entry_type, self.cite_key)NEWLINE entry_str += _print_field("author", self.authors)NEWLINE entry_str += _print_field("booktitle", self.booktitle, capitals=True)NEWLINE entry_str += _print_field("journal", self.journal, capitals=True)NEWLINE entry_str += _print_field("number", self.number)NEWLINE entry_str += _print_field("title", self.title)NEWLINE entry_str += _print_field("volume", self.volume)NEWLINE entry_str += _print_field("year", self.year)NEWLINENEWLINE if not self.compressed:NEWLINE entry_str += _print_field("address", self.address)NEWLINE entry_str += _print_field("annote", self.annote)NEWLINE entry_str += _print_field("chapter", self.chapter)NEWLINE entry_str += _print_field("crossref", self.crossref)NEWLINE entry_str += _print_field("edition", self.edition)NEWLINE entry_str += _print_field("editor", self.editors)NEWLINE entry_str += _print_field("howpublished", self.howpublished)NEWLINE entry_str += _print_field("institution", self.institution)NEWLINE entry_str += _print_field("key", self.key)NEWLINE entry_str += _print_field("month", self.month)NEWLINE entry_str += _print_field("note", self.note)NEWLINE entry_str += _print_field("organization", self.organization)NEWLINE entry_str += _print_field("pages", self.pages)NEWLINE entry_str += _print_field("publisher", self.publisher)NEWLINE entry_str += _print_field("school", self.school)NEWLINE entry_str += _print_field("series", self.series)NEWLINE entry_str += _print_field("type", self.type)NEWLINE entry_str += _print_field("url", self.url)NEWLINE entry_str += _print_field("doi", self.doi)NEWLINENEWLINE entry_str += "}\n\n"NEWLINE return entry_strNEWLINENEWLINE def __repr__(self):NEWLINE return self.__str__NEWLINENEWLINENEWLINEclass Authors:NEWLINE def __init__(self, authors_list=None):NEWLINE """NEWLINENEWLINE :param authors_list: list of authors namesNEWLINE """NEWLINE self.authors = []NEWLINE if authors_list:NEWLINE authors_list = authors_list.replace(" AND ", " and ")NEWLINE for author in authors_list.split(" and "):NEWLINE self.authors.append(Author(author.strip()))NEWLINENEWLINE def merge(self, merge_authors):NEWLINE max_len = min(len(merge_authors), len(self.authors))NEWLINE for i in range(0, max_len):NEWLINE self.authors[i].merge(merge_authors[i])NEWLINE if len(merge_authors) > len(self.authors):NEWLINE for i in range(max_len, len(merge_authors)):NEWLINE self.authors.append(merge_authors[i])NEWLINENEWLINE def __str__(self):NEWLINE authors = ""NEWLINE for author in self.authors:NEWLINE if len(authors) > 0:NEWLINE authors += " and "NEWLINE authors += author.__str__()NEWLINE return authorsNEWLINENEWLINE def __repr__(self):NEWLINE return self.__str__NEWLINENEWLINE def __len__(self):NEWLINE return len(self.authors)NEWLINENEWLINENEWLINEclass Author:NEWLINE def __init__(self, author_name):NEWLINE """NEWLINE Create an author object with first and last names.NEWLINE :param author_name: name of a single authorNEWLINE """NEWLINE self.first_name = ""NEWLINE self.last_name = ""NEWLINENEWLINE if "," in author_name:NEWLINE s = author_name.split(",")NEWLINE self.first_name = s[1].strip()NEWLINE self.last_name = s[0].strip()NEWLINE else:NEWLINE s = author_name.split(" ")NEWLINE if len(s) == 2:NEWLINE self.first_name = s[0].strip()NEWLINE self.last_name = s[1].strip()NEWLINE elif len(s) > 2:NEWLINE index = len(s) - 1NEWLINE value = s[len(s) - 2]NEWLINE if len(value) <= 2 and not value.endswith('.'):NEWLINE self.last_name = value + " " + s[len(s) - 1]NEWLINE index -= 1NEWLINE else:NEWLINE self.last_name = s[len(s) - 1]NEWLINE for i in range(0, index):NEWLINE if len(self.first_name) > 0:NEWLINE self.first_name += " "NEWLINE self.first_name += s[i]NEWLINE else:NEWLINE self.first_name = author_nameNEWLINE self.last_name = NoneNEWLINE if not author_name.lower() == "others":NEWLINE log.warning("Unable to find last name: %s" % author_name)NEWLINENEWLINE if self.first_name and self.last_name:NEWLINE self._remove_duplicated_names()NEWLINENEWLINE def merge(self, author_merge):NEWLINE """NEWLINE Merge author's first and last names with another similar entry.NEWLINE :param author_merge: author names to be mergedNEWLINE """NEWLINE if not self.last_name and author_merge.last_name:NEWLINE self.last_name = author_merge.last_nameNEWLINE if self.first_name.lower() == "others":NEWLINE self.first_name = author_merge.first_nameNEWLINENEWLINE elif author_merge.last_name and is_similar(self.last_name, author_merge.last_name, threshold=0.5):NEWLINE if len(author_merge.last_name) > len(self.last_name):NEWLINE self.last_name = author_merge.last_nameNEWLINE if len(author_merge.first_name) > len(self.first_name):NEWLINE self.first_name = author_merge.first_nameNEWLINENEWLINE self._remove_duplicated_names()NEWLINENEWLINE def _remove_duplicated_names(self):NEWLINE """NEWLINE Look for duplicated names in authors and remove them (Bug #13).NEWLINE """NEWLINE given_names = self.first_name.split(" ")NEWLINE last_names = self.last_name.split(" ")NEWLINE change = FalseNEWLINENEWLINE if len(given_names) > 0 and len(last_names) > 1:NEWLINE for name in given_names[1:]:NEWLINE if "." not in name and name in self.last_name:NEWLINE self.first_name = self.first_name.replace(name, "")NEWLINENEWLINE if len(last_names) > 0 and len(given_names) == 1:NEWLINE if given_names[0] in last_names:NEWLINE change = TrueNEWLINE self.last_name = self.last_name.replace(given_names[0], "")NEWLINENEWLINE def __str__(self):NEWLINE if self.last_name:NEWLINE return self.last_name + ", " + self.first_nameNEWLINE else:NEWLINE return self.first_nameNEWLINENEWLINE def __repr__(self):NEWLINE return self.__str__NEWLINENEWLINENEWLINEdef _parse_pages(pages):NEWLINE """NEWLINE Parse the page number to a 2-dashes format (e.g. 100--120).NEWLINE :param pages: entry page numbersNEWLINE :return:NEWLINE """NEWLINE if pages:NEWLINE if "-" in pages:NEWLINE if not pages.count("-") == 2:NEWLINE pages = re.sub("-+", "--", pages)NEWLINE return pagesNEWLINE return NoneNEWLINENEWLINENEWLINEdef _parse_booktitle(booktitle):NEWLINE """NEWLINENEWLINE :param booktitle: entry book titleNEWLINE """NEWLINE if booktitle:NEWLINE if "," in booktitle:NEWLINE bt = booktitle.split(",")NEWLINE booktitle = bt[1].strip() + " " + bt[0].strip()NEWLINE return booktitleNEWLINE return NoneNEWLINENEWLINENEWLINEdef _print_field(field_name, field_value, capitals=False):NEWLINE """NEWLINE Print a field in bib format if value is not none.NEWLINE :param field_name: name of the fieldNEWLINE :param field_value: value of the fieldNEWLINE :param capitals: whether to addNEWLINE :return: field in bib format or blank if field is NoneNEWLINE """NEWLINE if field_value:NEWLINE field_value = str(field_value).replace("_", "\_")NEWLINE field_value = str(field_value).replace("\\\\_", "\_")NEWLINE field_value = str(field_value).replace("#", "\#")NEWLINE field_value = str(field_value).replace("\\\\#", "\#")NEWLINE field_value = str(field_value).replace("$", "")NEWLINE if capitals:NEWLINE return "\t%s = {{%s}},\n" % (field_name, field_value)NEWLINE else:NEWLINE return "\t%s = {%s},\n" % (field_name, field_value)NEWLINE return ""NEWLINENEWLINENEWLINEdef _merge_field(f1, f2, is_int=False):NEWLINE """NEWLINE Merge field contents from two entries.NEWLINE :param f1: first fieldNEWLINE :param f2: second fieldNEWLINE :param is_int: whether the field is an integerNEWLINE :return: merged field contentsNEWLINE """NEWLINE if not f1 and not f2:NEWLINE return NoneNEWLINE if not f2 and f1 is not None:NEWLINE return f1NEWLINE if not f1 and f2 is not None:NEWLINE return f2NEWLINE if is_int:NEWLINE try:NEWLINE if int(f1) >= int(f2):NEWLINE return f1NEWLINE else:NEWLINE return f2NEWLINE except ValueError:NEWLINE passNEWLINE if len(f1) >= len(f2):NEWLINE return f1NEWLINE else:NEWLINE return f2NEWLINE return f1NEWLINENEWLINENEWLINEdef _merge_entry_type(t1, t2):NEWLINE """NEWLINE Merge entry type field from two entries according to entry type level.NEWLINE :param t1: first entry typeNEWLINE :param t2: second entry typeNEWLINE :return: merged entry typeNEWLINE """NEWLINE if t1 == EntryType.ARTICLE or t2 == EntryType.ARTICLE:NEWLINE return EntryType.ARTICLENEWLINE if t1 == EntryType.INPROCEEDINGS or t2 == EntryType.INPROCEEDINGS:NEWLINE return EntryType.INPROCEEDINGSNEWLINE if t1 == EntryType.INCOLLECTION or t2 == EntryType.INCOLLECTION:NEWLINE return EntryType.INCOLLECTIONNEWLINE if t1 == EntryType.PROCEEDINGS or t2 == EntryType.PROCEEDINGS:NEWLINE return EntryType.PROCEEDINGSNEWLINE if t1 == EntryType.BOOK or t2 == EntryType.BOOK:NEWLINE return EntryType.BOOKNEWLINE if t1 == EntryType.PHDTHESIS or t2 == EntryType.PHDTHESIS:NEWLINE return EntryType.PHDTHESISNEWLINE if t1 == EntryType.MASTERTHESIS or t2 == EntryType.MASTERTHESIS:NEWLINE return EntryType.MASTERTHESISNEWLINE if t1 == EntryType.TECHREPORT or t2 == EntryType.TECHREPORT:NEWLINE return EntryType.TECHREPORTNEWLINE return EntryType.MISCNEWLINE |
"""NEWLINE OpenVINO DL WorkbenchNEWLINE Script to check internet connectionNEWLINENEWLINE Copyright (c) 2020 Intel CorporationNEWLINENEWLINE Licensed under the Apache License, Version 2.0 (the "License");NEWLINE you may not use this file except in compliance with the License.NEWLINE You may obtain a copy of the License atNEWLINE http://www.apache.org/licenses/LICENSE-2.0NEWLINE Unless required by applicable law or agreed to in writing, softwareNEWLINE distributed under the License is distributed on an "AS IS" BASIS,NEWLINE WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE See the License for the specific language governing permissions andNEWLINE limitations under the License.NEWLINE"""NEWLINEfrom cpuinfo import get_cpu_infoNEWLINEfrom psutil import cpu_count, cpu_freqNEWLINENEWLINEif __name__ == '__main__':NEWLINE FULL_CPU_NAME = get_cpu_info()['brand_raw']NEWLINE print(f'Full CPU name is {FULL_CPU_NAME}')NEWLINE print(f'CPU cores number: {cpu_count(logical=False)}')NEWLINE CPU_FREQUENCY_RANGE = cpu_freq(percpu=False)NEWLINE CPU_FREQUENCY_UNITS = 'GHz'NEWLINE MHZ_IN_GHZ = 1000NEWLINE if CPU_FREQUENCY_RANGE.min == CPU_FREQUENCY_RANGE.max:NEWLINE CPU_FREQUENCY = '{:.1f} {units}'.format(CPU_FREQUENCY_RANGE.min / MHZ_IN_GHZ, units=CPU_FREQUENCY_UNITS)NEWLINE else:NEWLINE CPU_FREQUENCY = '{:.1f}-{:.1f} {units}'.format(CPU_FREQUENCY_RANGE.min / MHZ_IN_GHZ,NEWLINE CPU_FREQUENCY_RANGE.max / MHZ_IN_GHZ, units=CPU_FREQUENCY_UNITS)NEWLINE print(f'CPU frequency range: {CPU_FREQUENCY}')NEWLINE |
import pandas as pdNEWLINEfrom sklearn.metrics import mean_squared_errorNEWLINEfrom sklearn.model_selection import train_test_splitNEWLINEfrom sklearn.preprocessing import LabelEncoderNEWLINENEWLINEfrom deepctr.models import DeepFMNEWLINEfrom deepctr.feature_column import SparseFeat,get_feature_namesNEWLINENEWLINEif __name__ == "__main__":NEWLINENEWLINE data = pd.read_csv("./movielens_sample.txt")NEWLINE sparse_features = ["movie_id", "user_id",NEWLINE "gender", "age", "occupation", "zip"]NEWLINE target = ['rating']NEWLINENEWLINE # 1.Label Encoding for sparse features,and do simple Transformation for dense featuresNEWLINE for feat in sparse_features:NEWLINE lbe = LabelEncoder()NEWLINE data[feat] = lbe.fit_transform(data[feat])NEWLINE # 2.count #unique features for each sparse fieldNEWLINE fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique(),embedding_dim=4)NEWLINE for feat in sparse_features]NEWLINE linear_feature_columns = fixlen_feature_columnsNEWLINE dnn_feature_columns = fixlen_feature_columnsNEWLINE feature_names = get_feature_names(linear_feature_columns + dnn_feature_columns)NEWLINENEWLINE # 3.generate input data for modelNEWLINE train, test = train_test_split(data, test_size=0.2)NEWLINE train_model_input = {name:train[name].values for name in feature_names}NEWLINE test_model_input = {name:test[name].values for name in feature_names}NEWLINENEWLINE # 4.Define Model,train,predict and evaluateNEWLINE model = DeepFM(linear_feature_columns, dnn_feature_columns, task='regression')NEWLINE model.compile("adam", "mse", metrics=['mse'], )NEWLINENEWLINE history = model.fit(train_model_input, train[target].values,NEWLINE batch_size=256, epochs=10, verbose=2, validation_split=0.2, )NEWLINE pred_ans = model.predict(test_model_input, batch_size=256)NEWLINE print("test MSE", round(mean_squared_error(NEWLINE test[target].values, pred_ans), 4))NEWLINE |
"""NEWLINENEWLINE208. Implement Trie (Prefix Tree)NEWLINEMediumNEWLINENEWLINE5115NEWLINENEWLINE77NEWLINENEWLINEAdd to ListNEWLINENEWLINEShareNEWLINEA trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.NEWLINENEWLINEImplement the Trie class:NEWLINENEWLINETrie() Initializes the trie object.NEWLINEvoid insert(String word) Inserts the string word into the trie.NEWLINEboolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.NEWLINEboolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.NEWLINE NEWLINENEWLINEExample 1:NEWLINENEWLINEInputNEWLINE["Trie", "insert", "search", "search", "startsWith", "insert", "search"]NEWLINE[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]NEWLINEOutputNEWLINE[null, null, true, false, true, null, true]NEWLINENEWLINEExplanationNEWLINETrie trie = new Trie();NEWLINEtrie.insert("apple");NEWLINEtrie.search("apple"); // return TrueNEWLINEtrie.search("app"); // return FalseNEWLINEtrie.startsWith("app"); // return TrueNEWLINEtrie.insert("app");NEWLINEtrie.search("app"); // return TrueNEWLINE NEWLINENEWLINEConstraints:NEWLINENEWLINE1 <= word.length, prefix.length <= 2000NEWLINEword and prefix consist only of lowercase English letters.NEWLINEAt most 3 * 104 calls in total will be made to insert, search, and startsWith.NEWLINENEWLINE"""NEWLINENEWLINE# V0NEWLINE# IDEA : USE dict AS data structure (# TrieNode: is dict, or hashmap)NEWLINEclass Trie(object): NEWLINE def __init__(self):NEWLINE self.root = {} # TrieNode: is dict, or hashmap NEWLINE NEWLINE def insert(self, word):NEWLINE p = self.rootNEWLINE for c in word: NEWLINE if c not in p: NEWLINE p[c] = {}NEWLINE ### NOTE THISNEWLINE p = p[c]NEWLINE ### NOTE HERENEWLINE p['#'] = True # ‘#’ is a key indicating word boundayNEWLINE NEWLINE def search(self, word):NEWLINE node = self.find(word)NEWLINE return node is not None and '#' in node # NOTE NEWLINE NEWLINE def startsWith(self, prefix):NEWLINE return self.find(prefix) is not None # NOTE NEWLINE NEWLINE ### NOTE : remember to implement this help fuuncNEWLINE def find(self, prefix):NEWLINE p = self.rootNEWLINE for c in prefix: NEWLINE if c not in p: NEWLINE return NoneNEWLINE # for validating if "search to the end" (check '#' in the node or not) NEWLINE p = p[c]NEWLINE return pNEWLINENEWLINE# V1NEWLINE# IDEA : USE dict AS data structure (# TrieNode: is dict, or hashmap)NEWLINE# https://leetcode.com/problems/implement-trie-prefix-tree/discuss/633007/25-lines-python-use-50-less-code-than-c%2B%2B-should-I-change-to-pythonNEWLINEclass Trie(object): NEWLINE def __init__(self):NEWLINE self.root = {} # TrieNode: is dict, or hashmap NEWLINE NEWLINE def insert(self, word):NEWLINE p = self.rootNEWLINE for c in word: NEWLINE if c not in p: NEWLINE p[c] = {}NEWLINE p = p[c]NEWLINE ### NOTE HERENEWLINE p['#'] = True # ‘#’ is a key indicating word boundayNEWLINE NEWLINE def search(self, word):NEWLINE node = self.find(word)NEWLINE return node is not None and '#' in node # NOTE NEWLINE NEWLINE def startsWith(self, prefix):NEWLINE return self.find(prefix) is not None # NOTE NEWLINE NEWLINE def find(self, prefix):NEWLINE p = self.rootNEWLINE for c in prefix: NEWLINE if c not in p: NEWLINE return NoneNEWLINE p = p[c]NEWLINE return pNEWLINENEWLINE# V1 NEWLINE# https://blog.csdn.net/fuxuemingzhu/article/details/79388432NEWLINEclass Node(object):NEWLINE def __init__(self):NEWLINE self.children = collections.defaultdict(Node)NEWLINE self.isword = FalseNEWLINE NEWLINEclass Trie(object):NEWLINENEWLINE def __init__(self):NEWLINE """NEWLINE Initialize your data structure here.NEWLINE """NEWLINE self.root = Node()NEWLINENEWLINE def insert(self, word):NEWLINE """NEWLINE Inserts a word into the trie.NEWLINE :type word: strNEWLINE :rtype: voidNEWLINE """NEWLINE current = self.rootNEWLINE for w in word:NEWLINE current = current.children[w]NEWLINE current.isword = TrueNEWLINENEWLINE def search(self, word):NEWLINE """NEWLINE Returns if the word is in the trie.NEWLINE :type word: strNEWLINE :rtype: boolNEWLINE """NEWLINE current = self.rootNEWLINE for w in word:NEWLINE current = current.children.get(w)NEWLINE if current == None:NEWLINE return FalseNEWLINE return current.iswordNEWLINENEWLINE def startsWith(self, prefix):NEWLINE """NEWLINE Returns if there is any word in the trie that starts with the given prefix.NEWLINE :type prefix: strNEWLINE :rtype: boolNEWLINE """NEWLINE current = self.rootNEWLINE for w in prefix:NEWLINE current = current.children.get(w)NEWLINE if current == None:NEWLINE return FalseNEWLINE return True NEWLINENEWLINENEWLINE# Your Trie object will be instantiated and called as such:NEWLINE# obj = Trie()NEWLINE# obj.insert(word)NEWLINE# param_2 = obj.search(word)NEWLINE# param_3 = obj.startsWith(prefix)NEWLINENEWLINE# V1'NEWLINE# https://www.jiuzhang.com/solution/implement-trie-prefix-tree/#tag-highlight-lang-pythonNEWLINEclass TrieNode:NEWLINE NEWLINE def __init__(self):NEWLINE self.children = {}NEWLINE self.is_word = FalseNEWLINE NEWLINE NEWLINEclass Trie:NEWLINE NEWLINE def __init__(self):NEWLINE self.root = TrieNode()NEWLINENEWLINE """NEWLINE @param: word: a wordNEWLINE @return: nothingNEWLINE """NEWLINE def insert(self, word):NEWLINE node = self.rootNEWLINE for c in word:NEWLINE if c not in node.children:NEWLINE node.children[c] = TrieNode()NEWLINE node = node.children[c]NEWLINE NEWLINE node.is_word = TrueNEWLINENEWLINE """NEWLINE return the node in the trie if exists NEWLINE """NEWLINE def find(self, word):NEWLINE node = self.rootNEWLINE for c in word:NEWLINE node = node.children.get(c)NEWLINE if node is None:NEWLINE return NoneNEWLINE return nodeNEWLINE NEWLINE """NEWLINE @param: word: A stringNEWLINE @return: if the word is in the trie.NEWLINE """NEWLINE def search(self, word):NEWLINE node = self.find(word)NEWLINE return node is not None and node.is_wordNEWLINENEWLINE """NEWLINE @param: prefix: A stringNEWLINE @return: if there is any word in the trie that starts with the given prefix.NEWLINE """NEWLINE def startsWith(self, prefix):NEWLINE return self.find(prefix) is not NoneNEWLINENEWLINE# V1''NEWLINE# https://www.jiuzhang.com/solution/implement-trie-prefix-tree/#tag-highlight-lang-pythonNEWLINEclass TrieNode:NEWLINE NEWLINE def __init__(self):NEWLINE self.children = {}NEWLINE self.is_word = FalseNEWLINE NEWLINE NEWLINEclass Trie:NEWLINE NEWLINE def __init__(self):NEWLINE self.root = TrieNode()NEWLINENEWLINE """NEWLINE @param: word: a wordNEWLINE @return: nothingNEWLINE """NEWLINE def insert(self, word):NEWLINE node = self.rootNEWLINE for c in word:NEWLINE if c not in node.children:NEWLINE node.children[c] = TrieNode()NEWLINE node = node.children[c]NEWLINE NEWLINE node.is_word = TrueNEWLINENEWLINE """NEWLINE return the node in the trie if exists NEWLINE """NEWLINE def find(self, word):NEWLINE node = self.rootNEWLINE for c in word:NEWLINE node = node.children.get(c)NEWLINE if node is None:NEWLINE return NoneNEWLINE return nodeNEWLINE NEWLINE """NEWLINE @param: word: A stringNEWLINE @return: if the word is in the trie.NEWLINE """NEWLINE def search(self, word):NEWLINE node = self.find(word)NEWLINE return node is not None and node.is_wordNEWLINENEWLINE """NEWLINE @param: prefix: A stringNEWLINE @return: if there is any word in the trie that starts with the given prefix.NEWLINE """NEWLINE def startsWith(self, prefix):NEWLINE return self.find(prefix) is not NoneNEWLINENEWLINE# V2 NEWLINE# Time: O(n), per operationNEWLINE# Space: O(1)NEWLINEclass TrieNode(object):NEWLINE # Initialize your data structure here.NEWLINE def __init__(self):NEWLINE self.is_string = FalseNEWLINE self.leaves = {}NEWLINENEWLINEclass Trie(object):NEWLINENEWLINE def __init__(self):NEWLINE self.root = TrieNode()NEWLINENEWLINE # @param {string} wordNEWLINE # @return {void}NEWLINE # Inserts a word into the trie.NEWLINE def insert(self, word):NEWLINE cur = self.rootNEWLINE for c in word:NEWLINE if not c in cur.leaves:NEWLINE cur.leaves[c] = TrieNode()NEWLINE cur = cur.leaves[c]NEWLINE cur.is_string = TrueNEWLINENEWLINE # @param {string} wordNEWLINE # @return {boolean}NEWLINE # Returns if the word is in the trie.NEWLINE def search(self, word):NEWLINE node = self.childSearch(word)NEWLINE if node:NEWLINE return node.is_stringNEWLINE return FalseNEWLINENEWLINE # @param {string} prefixNEWLINE # @return {boolean}NEWLINE # Returns if there is any word in the trieNEWLINE # that starts with the given prefix.NEWLINE def startsWith(self, prefix):NEWLINE return self.childSearch(prefix) is not NoneNEWLINENEWLINE def childSearch(self, word):NEWLINE cur = self.rootNEWLINE for c in word:NEWLINE if c in cur.leaves:NEWLINE cur = cur.leaves[c]NEWLINE else:NEWLINE return NoneNEWLINE return cur |
# NEED THIS INIT FOR PYTEST --COV TO GENERATE A PROPER REPORTNEWLINENEWLINENEWLINE# Found the answer:NEWLINE#NEWLINE# DO NOT put a __init__.py file in a folder containing TESTS ifNEWLINE# you plan on using pytest. I had one such file, deleting itNEWLINE# solved the problem.NEWLINE#NEWLINE# This was actually buried in the comments to the secondNEWLINE# answer of PATH issue with pytestNEWLINE# 'ImportError: No module named YadaYadaYada' so I didNEWLINE# not see it, hope it gets more visibility here.NEWLINENEWLINE#https://stackoverflow.com/questions/41748464/pytest-cannot-import-module-while-python-canNEWLINE |
import numpy as npNEWLINEimport torchNEWLINEimport torch.nn as nnNEWLINENEWLINEfrom mmcv.cnn import constant_init, normal_initNEWLINEfrom mmdet.models.anchor_heads.ssd_head import SSDHeadNEWLINEfrom mmdet.models.registry import HEADSNEWLINENEWLINEfrom .operations import [email protected]_moduleNEWLINEclass SSDLightHead(SSDHead):NEWLINENEWLINE def __init__(self,NEWLINE input_size=300,NEWLINE num_classes=81,NEWLINE in_channels=(512, 1024, 512, 256, 256, 256),NEWLINE anchor_strides=(8, 16, 32, 64, 100, 300),NEWLINE basesize_ratio_range=(0.1, 0.9),NEWLINE anchor_ratios=([2], [2, 3], [2, 3], [2, 3], [2], [2]),NEWLINE target_means=(.0, .0, .0, .0),NEWLINE target_stds=(1.0, 1.0, 1.0, 1.0),NEWLINE search=False):NEWLINE super(SSDLightHead, self).__init__(input_size, num_classes, in_channels, NEWLINE anchor_strides, basesize_ratio_range, anchor_ratios,NEWLINE target_means, target_stds)NEWLINE self.search = searchNEWLINE num_anchors = [len(ratios) * 2 + 2 for ratios in anchor_ratios]NEWLINE reg_convs = []NEWLINE cls_convs = []NEWLINE for i in range(len(in_channels)):NEWLINE reg_convs.append(NEWLINE conv_dw_head(in_channels[i], num_anchors[i] * 4)NEWLINE )NEWLINE cls_convs.append(NEWLINE conv_dw_head(in_channels[i], num_anchors[i] * num_classes)NEWLINE )NEWLINE self.reg_convs = nn.ModuleList(reg_convs)NEWLINE self.cls_convs = nn.ModuleList(cls_convs)NEWLINENEWLINE def init_weights(self):NEWLINE for m in self.modules():NEWLINE if isinstance(m, nn.Conv2d):NEWLINE normal_init(m, std=0.03)NEWLINE elif isinstance(m, nn.BatchNorm2d):NEWLINE constant_init(m, 1)NEWLINENEWLINE def forward(self, feats):NEWLINE if self.search:NEWLINE feats, net_sub_obj = featsNEWLINE cls_scores = []NEWLINE bbox_preds = []NEWLINE for feat, reg_conv, cls_conv in zip(feats, self.reg_convs,NEWLINE self.cls_convs):NEWLINE cls_scores.append(cls_conv(feat))NEWLINE bbox_preds.append(reg_conv(feat))NEWLINE if self.search:NEWLINE return (cls_scores, bbox_preds), net_sub_obj NEWLINE else:NEWLINE return cls_scores, bbox_preds |
# coding: utf-8NEWLINE# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) DepartmentNEWLINE# Distributed under the terms of "New BSD License", see the LICENSE file.NEWLINENEWLINEfrom __future__ import print_function, unicode_literalsNEWLINEimport numpy as npNEWLINEimport osNEWLINEfrom pyiron_base import stateNEWLINEimport mendeleevNEWLINEimport pandasNEWLINEfrom functools import lru_cacheNEWLINENEWLINE__author__ = "Joerg Neugebauer, Sudarsan Surendralal, Martin Boeckmann"NEWLINE__copyright__ = (NEWLINE "Copyright 2021, Max-Planck-Institut für Eisenforschung GmbH - "NEWLINE "Computational Materials Design (CM) Department"NEWLINE)NEWLINE__version__ = "1.0"NEWLINE__maintainer__ = "Sudarsan Surendralal"NEWLINE__email__ = "[email protected]"NEWLINE__status__ = "production"NEWLINE__date__ = "Sep 1, 2017"NEWLINENEWLINEpandas.options.mode.chained_assignment = NoneNEWLINENEWLINENEWLINE@lru_cache(maxsize=118)NEWLINEdef element(*args):NEWLINE return mendeleev.element(*args)NEWLINENEWLINENEWLINEclass ChemicalElement(object):NEWLINE """NEWLINE An Object which contains the element specific parametersNEWLINE """NEWLINENEWLINE def __init__(self, sub):NEWLINE """NEWLINE Constructor: assign PSE dictionary to objectNEWLINE """NEWLINE self._dataset = NoneNEWLINE self.sub = subNEWLINE self._mendeleev_element = NoneNEWLINE self._mendeleev_property_lst = NoneNEWLINE stringtypes = strNEWLINE if isinstance(self.sub, stringtypes):NEWLINE self._init_mendeleev(self.sub)NEWLINE elif "Parent" in self.sub.index and isinstance(self.sub.Parent, stringtypes):NEWLINE self._init_mendeleev(self.sub.Parent)NEWLINE elif len(self.sub) > 0:NEWLINE self._init_mendeleev(self.sub.Abbreviation)NEWLINENEWLINE self._mendeleev_translation_dict = {NEWLINE "AtomicNumber": "atomic_number",NEWLINE "AtomicRadius": "covalent_radius_cordero",NEWLINE "AtomicMass": "mass",NEWLINE "Color": "cpk_color",NEWLINE "CovalentRadius": "covalent_radius",NEWLINE "CrystalStructure": "lattice_structure",NEWLINE "Density": "density",NEWLINE "DiscoveryYear": "discovery_year",NEWLINE "ElectronAffinity": "electron_affinity",NEWLINE "Electronegativity": "electronegativity",NEWLINE "Group": "group_id",NEWLINE "Name": "name",NEWLINE "Period": "period",NEWLINE "StandardName": "name",NEWLINE "VanDerWaalsRadius": "vdw_radius",NEWLINE "MeltingPoint": "melting_point",NEWLINE }NEWLINE self.el = NoneNEWLINENEWLINE def _init_mendeleev(self, element_str):NEWLINE self._mendeleev_element = element(str(element_str))NEWLINE self._mendeleev_property_lst = [NEWLINE s for s in dir(self._mendeleev_element) if not s.startswith("_")NEWLINE ]NEWLINENEWLINE def __getattr__(self, item):NEWLINE if item in ["__array_struct__", "__array_interface__", "__array__"]:NEWLINE raise AttributeErrorNEWLINE return self[item]NEWLINENEWLINE def __getitem__(self, item):NEWLINE if item in self._mendeleev_translation_dict.keys():NEWLINE item = self._mendeleev_translation_dict[item]NEWLINE if item in self._mendeleev_property_lst:NEWLINE return getattr(self._mendeleev_element, item)NEWLINE if item in self.sub.index:NEWLINE return self.sub[item]NEWLINENEWLINE def __eq__(self, other):NEWLINE if isinstance(other, self.__class__):NEWLINE conditions = list()NEWLINE conditions.append(self.sub.to_dict() == other.sub.to_dict())NEWLINE return all(conditions)NEWLINE elif isinstance(other, (np.ndarray, list)):NEWLINE conditions = list()NEWLINE for sp in other:NEWLINE conditions.append(self.sub.to_dict() == sp.sub.to_dict())NEWLINE return any(conditions)NEWLINENEWLINE def __ne__(self, other):NEWLINE return not self.__eq__(other)NEWLINENEWLINE def __gt__(self, other):NEWLINE if self != other:NEWLINE if self["AtomicNumber"] != other["AtomicNumber"]:NEWLINE return self["AtomicNumber"] > other["AtomicNumber"]NEWLINE else:NEWLINE return self["Abbreviation"] > other["Abbreviation"]NEWLINE else:NEWLINE return FalseNEWLINENEWLINE def __ge__(self, other):NEWLINE if self != other:NEWLINE return self > otherNEWLINE else:NEWLINE return TrueNEWLINENEWLINE def __hash__(self):NEWLINE return hash(repr(self))NEWLINENEWLINE @propertyNEWLINE def tags(self):NEWLINE if "tags" not in self.sub.keys() or self.sub["tags"] is None:NEWLINE return dict()NEWLINE return self.sub["tags"]NEWLINENEWLINE def __dir__(self):NEWLINE return list(self.sub.index) + super(ChemicalElement, self).__dir__()NEWLINENEWLINE def __str__(self):NEWLINE return str([self._dataset, self.sub])NEWLINENEWLINE def add_tags(self, tag_dic):NEWLINE """NEWLINE Add tags to an existing element inside its specific panda series without overwriting the old tagsNEWLINENEWLINE Args:NEWLINE tag_dic (dict): dictionary containing e.g. key = "spin" value = "up",NEWLINE more than one tag can be added at onceNEWLINENEWLINE """NEWLINE (self.sub["tags"]).update(tag_dic)NEWLINENEWLINE def to_hdf(self, hdf):NEWLINE """NEWLINE saves the element with his parameters into his hdf5 job fileNEWLINE Args:NEWLINE hdf (Hdfio): Hdfio object which will be usedNEWLINE """NEWLINE with hdf.open(self.Abbreviation) as hdf_el: # "Symbol of the chemical element"NEWLINE # TODO: save all parameters that are different from the parent (e.g. modified mass)NEWLINE if self.Parent is not None:NEWLINE self._dataset = {"Parameter": ["Parent"], "Value": [self.Parent]}NEWLINE hdf_el["elementData"] = self._datasetNEWLINE with hdf_el.open(NEWLINE "tagData"NEWLINE ) as hdf_tag: # "Dictionary of element tag static"NEWLINE for key in self.tags.keys():NEWLINE hdf_tag[key] = self.tags[key]NEWLINENEWLINE def from_hdf(self, hdf):NEWLINE """NEWLINE loads an element with his parameters from the hdf5 job file and store it into its specific pandas seriesNEWLINE Args:NEWLINE hdf (Hdfio): Hdfio object which will be used to read a hdf5 fileNEWLINE """NEWLINE pse = PeriodicTable()NEWLINE elname = self.sub.nameNEWLINE with hdf.open(elname) as hdf_el:NEWLINE if "elementData" in hdf_el.list_nodes():NEWLINE element_data = hdf_el["elementData"]NEWLINE for key, val in zip(element_data["Parameter"], element_data["Value"]):NEWLINE if key in "Parent":NEWLINE self.sub = pse.dataframe.loc[val]NEWLINE self.sub["Parent"] = valNEWLINE self._init_mendeleev(val)NEWLINE else:NEWLINE self.sub["Parent"] = NoneNEWLINE self._init_mendeleev(elname)NEWLINE self.sub.name = elnameNEWLINE if "tagData" in hdf_el.list_groups():NEWLINE with hdf_el.open(NEWLINE "tagData"NEWLINE ) as hdf_tag: # "Dictionary of element tag static"NEWLINE tag_dic = {}NEWLINE for key in hdf_tag.list_nodes():NEWLINE tag_dic[key] = hdf_tag[key]NEWLINE self.sub["tags"] = tag_dicNEWLINENEWLINENEWLINEclass PeriodicTable(object):NEWLINE """NEWLINE An Object which stores an elementary table which can be modified for the current sessionNEWLINE """NEWLINENEWLINE def __init__(self, file_name=None): # PSE_dat_file = None):NEWLINE """NEWLINENEWLINE Args:NEWLINE file_name (str): Possibility to choose an source hdf5 fileNEWLINE """NEWLINE self.dataframe = self._get_periodic_table_df(file_name)NEWLINE if "Abbreviation" not in self.dataframe.columns.values:NEWLINE self.dataframe["Abbreviation"] = NoneNEWLINE if not all(self.dataframe["Abbreviation"].values):NEWLINE for item in self.dataframe.index.values:NEWLINE if self.dataframe["Abbreviation"][item] is None:NEWLINE self.dataframe["Abbreviation"][item] = itemNEWLINE self._parent_element = NoneNEWLINE self.el = NoneNEWLINENEWLINE def __getattr__(self, item):NEWLINE return self[item]NEWLINENEWLINE def __getitem__(self, item):NEWLINE if item in self.dataframe.columns.values:NEWLINE return self.dataframe[item]NEWLINE if item in self.dataframe.index.values:NEWLINE return self.dataframe.loc[item]NEWLINENEWLINE def from_hdf(self, hdf):NEWLINE """NEWLINE loads an element with his parameters from the hdf5 job file by creating an Object of the ChemicalElement type.NEWLINE The new element will be stored in the current periodic table.NEWLINE Changes in the tags will also be modified inside the periodic table.NEWLINENEWLINE Args:NEWLINE hdf (Hdfio): Hdfio object which will be used to read the data from a hdf5 fileNEWLINENEWLINE Returns:NEWLINENEWLINE """NEWLINE elements = hdf.list_groups() # ["elements"]NEWLINE for el in elements:NEWLINE sub = pandas.Series(dtype=object)NEWLINE new_element = ChemicalElement(sub)NEWLINE new_element.sub.name = elNEWLINE new_element.from_hdf(hdf)NEWLINE new_element.sub["Abbreviation"] = elNEWLINENEWLINE if "sub_tags" in new_element.tags:NEWLINE if not new_element.tags["sub_tags"]:NEWLINE del new_element.tags["sub_tags"]NEWLINENEWLINE if new_element.Parent is None:NEWLINE if not (el in self.dataframe.index.values):NEWLINE raise AssertionError()NEWLINE if len(new_element.sub["tags"]) > 0:NEWLINE raise ValueError("Element cannot get tag-assignment twice")NEWLINE if "tags" not in self.dataframe.keys():NEWLINE self.dataframe["tags"] = NoneNEWLINE self.dataframe["tags"][el] = new_element.tagsNEWLINE else:NEWLINE self.dataframe = pandas.concat(NEWLINE [self.dataframe, new_element.sub.to_frame().T]NEWLINE )NEWLINE self.dataframe["tags"] = self.dataframe["tags"].apply(NEWLINE lambda x: None if pandas.isnull(x) else xNEWLINE )NEWLINE self.dataframe["Parent"] = self.dataframe["Parent"].apply(NEWLINE lambda x: None if pandas.isnull(x) else xNEWLINE )NEWLINENEWLINE def element(self, arg, **qwargs):NEWLINE """NEWLINE The method searches through the periodic table. If the table contains the element,NEWLINE it will return an Object of the type ChemicalElement containing all parameters from the periodic table.NEWLINE The option **qwargs allows a direct modification of the tag-values during the creation processNEWLINE Args:NEWLINE arg (str, ChemicalElement): sort of elementNEWLINE **qwargs: e.g. a dictionary of tagsNEWLINENEWLINE Returns element (ChemicalElement): a element with all its properties (Abbreviation, AtomicMass, Weight, ...)NEWLINENEWLINE """NEWLINE stringtypes = strNEWLINE if isinstance(arg, stringtypes):NEWLINE if arg in self.dataframe.index.values:NEWLINE self.el = argNEWLINE else:NEWLINE raise KeyError(arg)NEWLINE elif isinstance(arg, int):NEWLINENEWLINE if arg in list(self.dataframe["AtomicNumber"]):NEWLINE index = list(self.dataframe["AtomicNumber"]).index(arg)NEWLINE self.el = self.dataframe.iloc[index].nameNEWLINE else:NEWLINE raise ValueError("type not defined: " + str(type(arg)))NEWLINE if len(qwargs.values()) > 0:NEWLINE if "tags" not in self.dataframe.columns.values:NEWLINE self.dataframe["tags"] = NoneNEWLINE self.dataframe["tags"][self.el] = qwargsNEWLINE element = self.dataframe.loc[self.el]NEWLINE # element['CovalentRadius'] /= 100NEWLINE return ChemicalElement(element)NEWLINENEWLINE def is_element(self, symbol):NEWLINE """NEWLINE Compares the Symbol with the Abbreviations of elements inside the periodic tableNEWLINE Args:NEWLINE symbol (str): name of element, strNEWLINENEWLINE Returns boolean: true for the same element, false otherwiseNEWLINENEWLINE """NEWLINE return symbol in self.dataframe["Abbreviation"]NEWLINENEWLINE def atomic_number_to_abbreviation(self, atom_no):NEWLINE """NEWLINENEWLINE Args:NEWLINE atom_no:NEWLINENEWLINE Returns:NEWLINENEWLINE """NEWLINE if not isinstance(atom_no, int):NEWLINE raise ValueError("type not defined: " + str(type(atom_no)))NEWLINENEWLINE return self.Abbreviation[NEWLINE np.nonzero(self.AtomicNumber.to_numpy() == atom_no)[0][0]NEWLINE ]NEWLINENEWLINE def add_element(NEWLINE self, parent_element, new_element, use_parent_potential=False, **qwargsNEWLINE ):NEWLINE """NEWLINE Add "additional" chemical elements to the Periodic Table. These can be used to distinguish between the variousNEWLINE potentials which may exist for a given species or to introduce artificial elements such as pseudohydrogen. ForNEWLINE this case set use_parent_potential = False and add in the directory containing the potential files a new fileNEWLINE which is derived from the name new element.NEWLINENEWLINE This function may be also used to provide additional information for the identical chemical element, e.g., toNEWLINE define a Fe_up and Fe_down to perform the correct symmetry search as well as initialization.NEWLINENEWLINE Args:NEWLINE parent_element (str): name of parent elementNEWLINE new_element (str): name of new elementNEWLINE use_parent_potential: True: use the potential from the parent speciesNEWLINE **qwargs: define tags and their values, e.g. spin = "up", relax = [True, True, True]NEWLINENEWLINE Returns: new element (ChemicalElement)NEWLINENEWLINE """NEWLINENEWLINE pandas.options.mode.chained_assignment = NoneNEWLINE parent_element_data_series = self.dataframe.loc[parent_element]NEWLINE parent_element_data_series["Abbreviation"] = new_elementNEWLINE parent_element_data_series["Parent"] = parent_elementNEWLINE parent_element_data_series.name = new_elementNEWLINE if new_element not in self.dataframe.T.columns:NEWLINE self.dataframe = pandas.concat(NEWLINE [self.dataframe, parent_element_data_series.to_frame().T],NEWLINE )NEWLINE else:NEWLINE self.dataframe.loc[new_element] = parent_element_data_seriesNEWLINE if use_parent_potential:NEWLINE self._parent_element = parent_elementNEWLINE return self.element(new_element, **qwargs)NEWLINENEWLINE @staticmethodNEWLINE @lru_cache(maxsize=1)NEWLINE def _get_periodic_table_df(file_name):NEWLINE """NEWLINENEWLINE Args:NEWLINE file_name:NEWLINENEWLINE Returns:NEWLINENEWLINE """NEWLINE if not file_name:NEWLINE for resource_path in state.settings.resource_paths:NEWLINE if os.path.exists(os.path.join(resource_path, "atomistics")):NEWLINE resource_path = os.path.join(resource_path, "atomistics")NEWLINE for path, folder_lst, file_lst in os.walk(resource_path):NEWLINE for periodic_table_file_name in {"periodic_table.csv"}:NEWLINE if (NEWLINE periodic_table_file_name in file_lstNEWLINE and periodic_table_file_name.endswith(".csv")NEWLINE ):NEWLINE return pandas.read_csv(NEWLINE os.path.join(path, periodic_table_file_name),NEWLINE index_col=0,NEWLINE )NEWLINE elif (NEWLINE periodic_table_file_name in file_lstNEWLINE and periodic_table_file_name.endswith(".h5")NEWLINE ):NEWLINE return pandas.read_hdf(NEWLINE os.path.join(path, periodic_table_file_name), mode="r"NEWLINE )NEWLINE raise ValueError("Was not able to locate a periodic table. ")NEWLINE else:NEWLINE if file_name.endswith(".h5"):NEWLINE return pandas.read_hdf(file_name, mode="r")NEWLINE elif file_name.endswith(".csv"):NEWLINE return pandas.read_csv(file_name, index_col=0)NEWLINE raise TypeError(NEWLINE "PeriodicTable file format not recognised: "NEWLINE + file_nameNEWLINE + " supported file formats are csv, h5."NEWLINE )NEWLINE |
import osNEWLINEimport shlexNEWLINEimport subprocessNEWLINEimport reNEWLINEfrom typing import Dict, NoReturnNEWLINENEWLINEdef run_shell_command(command: str): -> NoReturnNEWLINE subprocess.run(shlex.split(command))NEWLINENEWLINENEWLINEdef get_git_info(git_repo_address: str) -> Dict:NEWLINE """Returns the various parts of the git_repo_address as a dictionary.NEWLINENEWLINE Example:NEWLINENEWLINE get_git_info(git_repo_address="https://github.com/sugatoray/colab_git_ssh")NEWLINE """NEWLINE gitpatterns = {NEWLINE "ssh": "(git)@(.*):(.*)/(.*).git", NEWLINE "https": "(https)://(.*)/(.*)/(.*)"NEWLINE }NEWLINE if git_repo_address.startswith("git@"):NEWLINE git_protocol = "ssh"NEWLINE elif git_repo_address.startswith("https://"):NEWLINE git_protocol = "https"NEWLINE if git_protocol in ["ssh", "https"]:NEWLINE parts = re.findall(gitpatterns[git_protocol], git_repo_address)[0]NEWLINE git_info = dict(NEWLINE host = parts[1],NEWLINE owner = parts[2],NEWLINE repo = parts[3],NEWLINE protocol = git_protocol,NEWLINE address = git_repo_addressNEWLINE )NEWLINE return git_infoNEWLINE else:NEWLINE raise ValueError("Non standard git_repo_address provided.")NEWLINENEWLINENEWLINEdef git_clone_repo(git_repo_address: str=None, verbose=True) -> Dict:NEWLINE """Clones a repo by the given git_repo_address. Returns the git_info as a dict.NEWLINE Supports both SSH and HTTPS protocols.NEWLINE NEWLINE Example:NEWLINENEWLINE git_clone_repo(git_repo_address="https://github.com/sugatoray/colab_git_ssh")NEWLINE """NEWLINE if git_repo_address is None:NEWLINE git_repo_address = "https://github.com/sugatoray/colab_git_ssh"NEWLINE git_info = get_git_info(git_repo_address)NEWLINE if os.path.isdir(git_info["repo"]):NEWLINE #! rm -r test_privateNEWLINE command = f'rm -r {git_info["repo"]}'NEWLINE run_shell_command(command)NEWLINE # git_repo_address examples:NEWLINE # [email protected]:<git_username>/<git_repo_name>.gitNEWLINE # [email protected]:<git_username>/<git_repo_name>.gitNEWLINE # [email protected]:<git_username>/<git_repo_name>.gitNEWLINE # ! git clone $git_repo_addressNEWLINE run_shell_command(command=f'git clone {git_repo_address}')NEWLINE NEWLINE if verbose:NEWLINE # print(f"Cloned repo: {git_repo_address} " + emoji.emojize(":fire:") * 3)NEWLINE print(f"Cloned repo: {git_repo_address} " + "🔥🔥🔥")NEWLINE return git_infoNEWLINENEWLINENEWLINEdef get_githost(host: str="github.com") -> str:NEWLINE """Returns the git host for GitHub, GitLab, BitBucket.NEWLINENEWLINE Parameters:NEWLINENEWLINE host (str): {("gh", "github", "github.com"), NEWLINE ("gl", "gitlab", "gitlab.com"), NEWLINE ("bb", "bitbucket", "bitbucket.org")}.NEWLINENEWLINE (default: "github.com")NEWLINENEWLINE Example:NEWLINENEWLINE The folloing three will return: "github.com"NEWLINE get_githost(host="gh")NEWLINE get_githost(host="github")NEWLINE get_githost(host="github.com")NEWLINENEWLINE The folloing three will return: "gitlab.com"NEWLINE get_githost(host="gl")NEWLINE get_githost(host="gitlab")NEWLINE get_githost(host="gitlab.com")NEWLINENEWLINE The folloing three will return: "bitbucket.org"NEWLINE get_githost(host="bb")NEWLINE get_githost(host="bitbucket")NEWLINE get_githost(host="bitbucket.org")NEWLINENEWLINE """NEWLINE host = host.lower() NEWLINE if any(x in host for x in ["gh", "github", "github.com"]):NEWLINE host = "github.com"NEWLINE elif any(x in host for x in ["gl", "gitlab", "gitlab.com"]):NEWLINE host = "gitlab.com"NEWLINE elif any(x in host for x in ["bb", "bitbucket", "bitbucket.org"]):NEWLINE host = "bitbucket.org" NEWLINE NEWLINE return hostNEWLINENEWLINENEWLINEdef make_git_address(repo: str="repo", owner: str="owner", host: str="github.com", protocol: str="ssh") -> str:NEWLINE """Constructs git repo address from given components.NEWLINENEWLINE Parameters:NEWLINENEWLINE repo (str): git repository name. (default: "repo")NEWLINE owner (str): git repository owner-name. (default: "owner") NEWLINE host (str): git cloud host domain. (default: "github.com")NEWLINE protocol (str): {ssh, https}. (default: "ssh")NEWLINENEWLINE Example:NEWLINENEWLINE For this repository: https://github.com/sugatoray/colab_git_sshNEWLINENEWLINE repo = "colab_git_ssh"NEWLINE owner = "sugatoray"NEWLINE host = "github.com"NEWLINE protocol = "https"NEWLINENEWLINE For this repository: [email protected]:sugatoray/colab_git_ssh.gitNEWLINENEWLINE repo = "colab_git_ssh"NEWLINE owner = "sugatoray"NEWLINE host = "github.com"NEWLINE protocol = "ssh"NEWLINENEWLINE """NEWLINE host = get_githost(host) NEWLINE if protocol=="ssh":NEWLINE address = f"git@{host}:{owner}/{repo}.git"NEWLINE else:NEWLINE # protocol=="https"NEWLINE address = f"https://{host}/{owner}/{repo}"NEWLINE return addressNEWLINE |
from player import PlayerNEWLINEfrom Card import CardNEWLINEimport timeNEWLINEimport uuid,randomNEWLINEclass Game:NEWLINE id = 0NEWLINE last_action_time = 0NEWLINE turn = 0NEWLINE cards = []NEWLINE players = []NEWLINE action = ""NEWLINE reaction_card = ""NEWLINE reacting_player = ""NEWLINE challenging_player = ""NEWLINE state = "" #Challenging, Over, Acting, Revealing, StartingNEWLINE target_player = ""NEWLINE exchanging_cards = []NEWLINE NEWLINE def __init__(self,player_list,start_time):NEWLINE self.id = uuid.uuid4().time_lowNEWLINE self.last_action_time = start_timeNEWLINE self.state = "Starting"NEWLINE self.target_player = ""NEWLINE self.reaction = ""NEWLINE self.challenging_player = ""NEWLINE self.exchanging_cards = []NEWLINE for p in player_list:NEWLINE self.players.append(Player(p))NEWLINE for i in range(3):NEWLINE self.cards.append(Card('Duke', ['TAX','BLOCK_FOREIGN_AID']))NEWLINE self.cards.append(Card('Captain', ['STEAL','BLOCK_STEAL'])) #Block stealNEWLINE self.cards.append(Card('Ambassador', ['EXCHANGE','BLOCK_STEAL'])) #Block stealNEWLINE self.cards.append(Card('Assassin', ['ASSASINATE']))NEWLINE self.cards.append(Card('Contessa', ['BLOCK_ASSASIANTE'])) #Block assassinationiNEWLINENEWLINE def get_cards_for_exchange(self):NEWLINE cards = [ card for card in self.players[self.get_turn()].get_cards() if card.get_state() == "active" ] + self.get_two_random_card()NEWLINE self.exchanging_cards = cardsNEWLINENEWLINE self.players[self.get_turn()].clean_cards()NEWLINENEWLINE return cardsNEWLINE NEWLINE NEWLINE def get_challenging_player(self):NEWLINE return self.challenging_playerNEWLINE def get_exchanging_cards(self):NEWLINE return self.exchanging_cardsNEWLINENEWLINENEWLINE def get_two_random_card(self):NEWLINE random.shuffle(self.cards)NEWLINE random_cards = [NEWLINE self.cards.pop(),self.cards.pop()NEWLINE ]NEWLINE return random_cardsNEWLINENEWLINENEWLINE def check_action_is_exchange(self):NEWLINE if(self.action == "EXCHANGE"):NEWLINE return TrueNEWLINE return FalseNEWLINE NEWLINE def get_target_player(self):NEWLINE return self.target_playerNEWLINE NEWLINE def perform(self):NEWLINE if(self.action == "TAX"):NEWLINE self.players[self.get_turn()].tax()NEWLINE return None , FalseNEWLINE if(self.action == "STEAL"):NEWLINE profit = self.target_player.get_rubbed()NEWLINE self.players[self.get_turn()].set_coins(self.players[self.get_turn()].get_coins() + profit )NEWLINE return None , FalseNEWLINE if(self.action == "COUP"):NEWLINE card , is_dead = self.target_player.kill_one_card()NEWLINE return card , is_deadNEWLINE if(self.action == "ASSASINATE"):NEWLINE card , is_dead = self.target_player.kill_one_card()NEWLINE return card , is_deadNEWLINE if(self.action == "INCOME"):NEWLINE self.players[self.get_turn()].income()NEWLINE return None , FalseNEWLINENEWLINE return None , FalseNEWLINE NEWLINENEWLINE def get_reaction_card(self):NEWLINE return self.reaction_cardNEWLINENEWLINE NEWLINE def set_reaction_card(self , reaction_card):NEWLINE self.reaction_card = reaction_cardNEWLINENEWLINENEWLINE def get_turn_counter(self):NEWLINE return self.turnNEWLINENEWLINENEWLINE def set_target_player(self,target_player_chat_id):NEWLINE NEWLINE for player in self.players:NEWLINE if(player.get_id().message.chat_id == target_player_chat_id):NEWLINE self.target_player = playerNEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE NEWLINE def check_target_player_need(self):NEWLINE if(self.action in ["ASSASINATE","STEAL","COUP"]):NEWLINE return TrueNEWLINE else:NEWLINE return FalseNEWLINE def check_react_challenge(self):NEWLINE if(self.get_target_player().has_card(self.reaction_card)):NEWLINE card , is_dead = self.get_players()[self.get_turn()].kill_one_card()NEWLINE return False , card , is_deadNEWLINE else:NEWLINE card , is_dead = self.get_target_player().kill_one_card()NEWLINE return True , card , is_deadNEWLINENEWLINENEWLINE def check_challenge(self,player_chat_id):NEWLINE playing_player_index = self.get_turn()NEWLINE challenging_player_chat_id = player_chat_idNEWLINENEWLINE for player in self.players:NEWLINE c = player.get_id().message.chat_idNEWLINE if( c == challenging_player_chat_id):NEWLINE challenging_player = playerNEWLINE self.challenging_player = playerNEWLINE is_bluffing = self.players[playing_player_index].is_bluffing(self.action)NEWLINENEWLINE if(is_bluffing):NEWLINE card , is_dead = self.players[playing_player_index].kill_one_card()NEWLINE NEWLINE return True , card , is_dead NEWLINE else:NEWLINE card , is_dead = challenging_player.kill_one_card()NEWLINE return False , card , is_dead NEWLINENEWLINE def check_challenge_possibility(self):NEWLINE if(self.action in ['COUP','INCOME']):NEWLINE return FalseNEWLINE else:NEWLINE self.get_last_action_time = time.time()NEWLINE return TrueNEWLINENEWLINE def get_action(self):NEWLINE return self.actionNEWLINE NEWLINE def set_action(self,new_action):NEWLINE self.action = new_actionNEWLINE return 1NEWLINE NEWLINE def get_turn(self):NEWLINE return self.turn % len(self.players)NEWLINE NEWLINE def next_turn(self):NEWLINE self.target_player = ""NEWLINE self.action = ""NEWLINE self.reaction_card = ""NEWLINE self.reacting_player = ""NEWLINE self.state = "" #Challenging, Over, Acting, Revealing, StartingNEWLINE for i in range(self.turn+1,5000):NEWLINE if(self.players[i % len(self.players)].get_state()!= "DEAD"):NEWLINE self.turn = i NEWLINE breakNEWLINE return TrueNEWLINENEWLINE def start(self):NEWLINE random.shuffle(self.cards)NEWLINE for player in self.players:NEWLINE player.add_card(self.cards.pop())NEWLINE player.add_card(self.cards.pop())NEWLINE player.coins = 2NEWLINE turn = 0NEWLINE self.state = "Acting" NEWLINENEWLINE def get_living_players(self):NEWLINE NEWLINE return [player for player in self.players if player.state != "Dead" ]NEWLINE def get_players(self):NEWLINE return self.playersNEWLINE def get_last_action_time(self): NEWLINE return self.last_action_timeNEWLINE NEWLINE def get_state(self):NEWLINE return self.stateNEWLINENEWLINE def set_state(self,state):NEWLINE self.state = stateNEWLINE NEWLINE def set_last_action_time(self,time):NEWLINE self.last_action_time = time NEWLINE return 1NEWLINE NEWLINE def get_id(self):NEWLINE return self.idNEWLINE |
# Copyright 2018 Open Source Robotics Foundation, Inc.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEimport unittestNEWLINENEWLINEfrom rclpy.clock import ClockTypeNEWLINEfrom rclpy.duration import DurationNEWLINEfrom rclpy.time import TimeNEWLINENEWLINEfrom test_msgs.msg import BuiltinsNEWLINENEWLINENEWLINEclass TestTime(unittest.TestCase):NEWLINENEWLINE def test_time_construction(self):NEWLINE time = Time()NEWLINE assert time.nanoseconds == 0NEWLINENEWLINE time = Time(seconds=1, nanoseconds=5e8, clock_type=ClockType.SYSTEM_TIME)NEWLINE assert time.nanoseconds == 1500000000NEWLINE assert time.clock_type == ClockType.SYSTEM_TIMENEWLINENEWLINE with self.assertRaises(OverflowError):NEWLINE time = Time(nanoseconds=2**63)NEWLINE time = Time(nanoseconds=2**63 - 1)NEWLINE assert time.nanoseconds == 2**63 - 1NEWLINENEWLINE with self.assertRaises(ValueError):NEWLINE time = Time(seconds=-1)NEWLINE with self.assertRaises(ValueError):NEWLINE time = Time(nanoseconds=-1)NEWLINE with self.assertRaises(TypeError):NEWLINE time = Time(clock_type='SYSTEM_TIME')NEWLINENEWLINE def test_duration_construction(self):NEWLINE duration = Duration()NEWLINE assert duration.nanoseconds == 0NEWLINENEWLINE duration = Duration(seconds=1, nanoseconds=5e8)NEWLINE assert duration.nanoseconds == 1500000000NEWLINENEWLINE with self.assertRaises(OverflowError):NEWLINE duration = Duration(nanoseconds=2**63)NEWLINE duration = Duration(nanoseconds=2**63 - 1)NEWLINE assert duration.nanoseconds == 2**63 - 1NEWLINENEWLINE assert Duration(seconds=-1).nanoseconds == -1 * 1000 * 1000 * 1000NEWLINE assert Duration(nanoseconds=-1).nanoseconds == -1NEWLINENEWLINE assert Duration(seconds=-2**63 / 1e9).nanoseconds == -2**63NEWLINE with self.assertRaises(OverflowError):NEWLINE # Much smaller number because float to integer conversion of seconds is impreciseNEWLINE duration = Duration(seconds=-2**63 / 1e9 - 1)NEWLINENEWLINE assert Duration(nanoseconds=-2**63).nanoseconds == -2**63NEWLINE with self.assertRaises(OverflowError):NEWLINE Duration(nanoseconds=-2**63 - 1)NEWLINENEWLINE def test_time_operators(self):NEWLINE time1 = Time(nanoseconds=1, clock_type=ClockType.STEADY_TIME)NEWLINENEWLINE # Addition/subtraction of time and durationNEWLINE duration = Duration(nanoseconds=1)NEWLINE time2 = time1 + durationNEWLINE assert isinstance(time2, Time)NEWLINE assert time2.nanoseconds == 2NEWLINE assert time2.clock_type == ClockType.STEADY_TIMENEWLINENEWLINE time2 = duration + time1NEWLINE assert isinstance(time2, Time)NEWLINE assert time2.nanoseconds == 2NEWLINE assert time2.clock_type == ClockType.STEADY_TIMENEWLINENEWLINE time2 = time1 - durationNEWLINE assert isinstance(time2, Time)NEWLINE assert time2.nanoseconds == 0NEWLINE assert time2.clock_type == ClockType.STEADY_TIMENEWLINENEWLINE with self.assertRaises(OverflowError):NEWLINE Duration(nanoseconds=1) + Time(nanoseconds=2**63 - 1)NEWLINENEWLINE with self.assertRaises(ValueError):NEWLINE Time(nanoseconds=1) - Duration(nanoseconds=2)NEWLINENEWLINE # Subtraction of times with the same clock typeNEWLINE diff = time1 - time2NEWLINE assert isinstance(diff, Duration)NEWLINE assert diff.nanoseconds == 1NEWLINENEWLINE # Subtraction resulting in a negative durationNEWLINE assert (Time(nanoseconds=1) - Time(nanoseconds=2)).nanoseconds == -1NEWLINENEWLINE # Subtraction of times with different clock typesNEWLINE with self.assertRaises(TypeError):NEWLINE Time(nanoseconds=2, clock_type=ClockType.SYSTEM_TIME) - \NEWLINE Time(nanoseconds=1, clock_type=ClockType.STEADY_TIME)NEWLINENEWLINE # Invalid arithmetic combinationsNEWLINE with self.assertRaises(TypeError):NEWLINE time1 + time2NEWLINE with self.assertRaises(TypeError):NEWLINE duration - time1NEWLINENEWLINE def test_time_comparators(self):NEWLINE # Times with the same clock typeNEWLINE time1 = Time(nanoseconds=1)NEWLINE time2 = Time(nanoseconds=2)NEWLINE self.assertFalse(time1 == time2)NEWLINE self.assertTrue(time1 != time2)NEWLINE self.assertFalse(time1 > time2)NEWLINE self.assertFalse(time1 >= time2)NEWLINE self.assertTrue(time1 < time2)NEWLINE self.assertTrue(time1 <= time2)NEWLINENEWLINE time1 = Time(nanoseconds=5e9)NEWLINE time2 = Time(seconds=5)NEWLINE self.assertTrue(time1 == time2)NEWLINENEWLINE # Times with different clock typesNEWLINE time1 = Time(nanoseconds=1, clock_type=ClockType.SYSTEM_TIME)NEWLINE time2 = Time(nanoseconds=2, clock_type=ClockType.STEADY_TIME)NEWLINE with self.assertRaises(TypeError):NEWLINE time1 == time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 != time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 > time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 >= time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 < time2NEWLINE with self.assertRaises(TypeError):NEWLINE time1 <= time2NEWLINENEWLINE # Invalid combinationsNEWLINE time1 = Time(nanoseconds=1)NEWLINE with self.assertRaises(TypeError):NEWLINE time1 == 1NEWLINE duration = Duration()NEWLINE with self.assertRaises(TypeError):NEWLINE time1 == durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 != durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 > durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 >= durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 < durationNEWLINE with self.assertRaises(TypeError):NEWLINE time1 <= durationNEWLINENEWLINE def test_duration_comparators(self):NEWLINE duration1 = Duration(nanoseconds=1)NEWLINE duration2 = Duration(nanoseconds=2)NEWLINE self.assertFalse(duration1 == duration2)NEWLINE self.assertTrue(duration1 != duration2)NEWLINE self.assertFalse(duration1 > duration2)NEWLINE self.assertFalse(duration1 >= duration2)NEWLINE self.assertTrue(duration1 < duration2)NEWLINE self.assertTrue(duration1 <= duration2)NEWLINENEWLINE duration1 = Duration(nanoseconds=5e9)NEWLINE duration2 = Duration(seconds=5)NEWLINE self.assertTrue(duration1 == duration2)NEWLINENEWLINE # Invalid combinationsNEWLINE duration1 = Duration(nanoseconds=1)NEWLINE with self.assertRaises(TypeError):NEWLINE duration1 == 1NEWLINE time = Time()NEWLINE with self.assertRaises(TypeError):NEWLINE duration1 == timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 != timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 > timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 >= timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 < timeNEWLINE with self.assertRaises(TypeError):NEWLINE duration1 <= timeNEWLINENEWLINE def test_time_message_conversions(self):NEWLINE time1 = Time(nanoseconds=1, clock_type=ClockType.ROS_TIME)NEWLINE builtins_msg = Builtins()NEWLINE builtins_msg.time_value = time1.to_msg()NEWLINENEWLINE # Default clock type resulting from from_msg will be ROS timeNEWLINE time2 = Time.from_msg(builtins_msg.time_value)NEWLINE assert isinstance(time2, Time)NEWLINE assert time1 == time2NEWLINE # Clock type can be specified if appropriateNEWLINE time3 = Time.from_msg(builtins_msg.time_value, clock_type=ClockType.SYSTEM_TIME)NEWLINE assert time3.clock_type == ClockType.SYSTEM_TIMENEWLINENEWLINE def test_time_message_conversions_big_nanoseconds(self):NEWLINE time1 = Time(nanoseconds=1553575413247045598, clock_type=ClockType.ROS_TIME)NEWLINE builtins_msg = Builtins()NEWLINE builtins_msg.time_value = time1.to_msg()NEWLINENEWLINE # Default clock type resulting from from_msg will be ROS timeNEWLINE time2 = Time.from_msg(builtins_msg.time_value)NEWLINE assert isinstance(time2, Time)NEWLINE assert time1 == time2NEWLINENEWLINE def test_duration_message_conversions(self):NEWLINE duration = Duration(nanoseconds=1)NEWLINE builtins_msg = Builtins()NEWLINE builtins_msg.duration_value = duration.to_msg()NEWLINE duration2 = Duration.from_msg(builtins_msg.duration_value)NEWLINE assert isinstance(duration2, Duration)NEWLINE assert duration2.nanoseconds == 1NEWLINENEWLINE def test_seconds_nanoseconds(self):NEWLINE assert (1, int(5e8)) == Time(seconds=1, nanoseconds=5e8).seconds_nanoseconds()NEWLINE assert (1, int(5e8)) == Time(seconds=0, nanoseconds=15e8).seconds_nanoseconds()NEWLINE assert (0, 0) == Time().seconds_nanoseconds()NEWLINE |
from django.db import modelsNEWLINENEWLINE# Create your models here.NEWLINEclass Grade(models.Model):NEWLINE gno=models.CharField(max_length=20,primary_key=True)NEWLINE gname=models.CharField(max_length=20,unique=True)NEWLINE class Meta():NEWLINE db_table = 'grade'NEWLINENEWLINEclass Course(models.Model):NEWLINE cno=models.CharField(max_length=20,primary_key=True)NEWLINE cname=models.CharField(max_length=100)NEWLINE textBook=models.CharField(max_length=50)NEWLINE gradeCourses=models.ManyToManyField("Grade",through="TeachPlan")NEWLINE class Meta():NEWLINE db_table = 'course'NEWLINENEWLINEclass TeachPlan(models.Model):NEWLINE course = models.ForeignKey("Course", on_delete=models.CASCADE)NEWLINE grade = models.ForeignKey("Grade", on_delete=models.CASCADE)NEWLINE credit=models.FloatField()NEWLINE teach_date = models.DateField()NEWLINE checkType = models.CharField(max_length=50)NEWLINE class Meta():NEWLINE db_table = 'teachplan'NEWLINENEWLINEclass Teacher(models.Model):NEWLINE tno=models.CharField(max_length=20,primary_key=True)NEWLINE tname=models.CharField(max_length=50)NEWLINE gender=models.CharField(max_length=10)NEWLINE jobTitle=models.CharField(max_length=10)NEWLINE teachCourse=models.ManyToManyField("Course")NEWLINE class Meta():NEWLINE db_table = 'teacher'NEWLINENEWLINEclass Student(models.Model):NEWLINE sno=models.CharField(max_length=50,primary_key=True)NEWLINE sname=models.CharField(max_length=50)NEWLINE gender=models.CharField(max_length=10)NEWLINE studentCourse=models.ManyToManyField("Course",through="Achievement")NEWLINE class Meta():NEWLINE db_table = 'student'NEWLINENEWLINEclass Achievement(models.Model):NEWLINE course = models.ForeignKey("Course", on_delete=models.CASCADE)NEWLINE student = models.ForeignKey("Student", on_delete=models.CASCADE)NEWLINE score = models.FloatField()NEWLINE gain_date = models.DateField()NEWLINE class Meta():NEWLINE db_table = 'achievement'NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE |
import lossesNEWLINEimport torchNEWLINENEWLINENEWLINEdef build_loss(cfg):NEWLINE args = cfg.copy()NEWLINE name = args.pop('type')NEWLINE if hasattr(torch.nn, name):NEWLINE criterion = getattr(torch.nn, name)(**args)NEWLINE else:NEWLINE criterion = losses.__dict__[name](**args)NEWLINE return criterionNEWLINE |
"""NEWLINEPyTorch policy class used for SAC.NEWLINE"""NEWLINENEWLINEimport gymNEWLINEfrom gym.spaces import DiscreteNEWLINEimport loggingNEWLINEfrom typing import Dict, List, Optional, Tuple, Type, UnionNEWLINENEWLINEimport rayNEWLINEimport ray.experimental.tf_utilsNEWLINEfrom ray.rllib.agents.sac.sac_tf_policy import build_sac_model, \NEWLINE postprocess_trajectory, validate_spacesNEWLINEfrom ray.rllib.agents.dqn.dqn_tf_policy import PRIO_WEIGHTSNEWLINEfrom ray.rllib.models.modelv2 import ModelV2NEWLINEfrom ray.rllib.models.torch.torch_action_dist import \NEWLINE TorchDistributionWrapper, TorchDirichletNEWLINEfrom ray.rllib.policy.policy import PolicyNEWLINEfrom ray.rllib.policy.policy_template import build_policy_classNEWLINEfrom ray.rllib.policy.sample_batch import SampleBatchNEWLINEfrom ray.rllib.models.torch.torch_action_dist import (NEWLINE TorchCategorical, TorchSquashedGaussian, TorchDiagGaussian, TorchBeta)NEWLINEfrom ray.rllib.utils.framework import try_import_torchNEWLINEfrom ray.rllib.utils.spaces.simplex import SimplexNEWLINEfrom ray.rllib.utils.torch_ops import apply_grad_clipping, huber_lossNEWLINEfrom ray.rllib.utils.typing import LocalOptimizer, TensorType, \NEWLINE TrainerConfigDictNEWLINENEWLINEtorch, nn = try_import_torch()NEWLINEF = nn.functionalNEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINENEWLINEdef build_sac_model_and_action_dist(NEWLINE policy: Policy,NEWLINE obs_space: gym.spaces.Space,NEWLINE action_space: gym.spaces.Space,NEWLINE config: TrainerConfigDict) -> \NEWLINE Tuple[ModelV2, Type[TorchDistributionWrapper]]:NEWLINE """Constructs the necessary ModelV2 and action dist class for the Policy.NEWLINENEWLINE Args:NEWLINE policy (Policy): The TFPolicy that will use the models.NEWLINE obs_space (gym.spaces.Space): The observation space.NEWLINE action_space (gym.spaces.Space): The action space.NEWLINE config (TrainerConfigDict): The SAC trainer's config dict.NEWLINENEWLINE Returns:NEWLINE ModelV2: The ModelV2 to be used by the Policy. Note: An additionalNEWLINE target model will be created in this function and assigned toNEWLINE `policy.target_model`.NEWLINE """NEWLINE model = build_sac_model(policy, obs_space, action_space, config)NEWLINE action_dist_class = _get_dist_class(config, action_space)NEWLINE return model, action_dist_classNEWLINENEWLINENEWLINEdef _get_dist_class(config: TrainerConfigDict, action_space: gym.spaces.SpaceNEWLINE ) -> Type[TorchDistributionWrapper]:NEWLINE """Helper function to return a dist class based on config and action space.NEWLINENEWLINE Args:NEWLINE config (TrainerConfigDict): The Trainer's config dict.NEWLINE action_space (gym.spaces.Space): The action space used.NEWLINENEWLINE Returns:NEWLINE Type[TFActionDistribution]: A TF distribution class.NEWLINE """NEWLINE if isinstance(action_space, Discrete):NEWLINE return TorchCategoricalNEWLINE elif isinstance(action_space, Simplex):NEWLINE return TorchDirichletNEWLINE else:NEWLINE if config["normalize_actions"]:NEWLINE return TorchSquashedGaussian if \NEWLINE not config["_use_beta_distribution"] else TorchBetaNEWLINE else:NEWLINE return TorchDiagGaussianNEWLINENEWLINENEWLINEdef action_distribution_fn(NEWLINE policy: Policy,NEWLINE model: ModelV2,NEWLINE obs_batch: TensorType,NEWLINE *,NEWLINE state_batches: Optional[List[TensorType]] = None,NEWLINE seq_lens: Optional[TensorType] = None,NEWLINE prev_action_batch: Optional[TensorType] = None,NEWLINE prev_reward_batch=None,NEWLINE explore: Optional[bool] = None,NEWLINE timestep: Optional[int] = None,NEWLINE is_training: Optional[bool] = None) -> \NEWLINE Tuple[TensorType, Type[TorchDistributionWrapper], List[TensorType]]:NEWLINE """The action distribution function to be used the algorithm.NEWLINENEWLINE An action distribution function is used to customize the choice of actionNEWLINE distribution class and the resulting action distribution inputs (toNEWLINE parameterize the distribution object).NEWLINE After parameterizing the distribution, a `sample()` callNEWLINE will be made on it to generate actions.NEWLINENEWLINE Args:NEWLINE policy (Policy): The Policy being queried for actions and calling thisNEWLINE function.NEWLINE model (TorchModelV2): The SAC specific Model to use to generate theNEWLINE distribution inputs (see sac_tf|torch_model.py). Must support theNEWLINE `get_policy_output` method.NEWLINE obs_batch (TensorType): The observations to be used as inputs to theNEWLINE model.NEWLINE state_batches (Optional[List[TensorType]]): The list of internal stateNEWLINE tensor batches.NEWLINE seq_lens (Optional[TensorType]): The tensor of sequence lengths usedNEWLINE in RNNs.NEWLINE prev_action_batch (Optional[TensorType]): Optional batch of prevNEWLINE actions used by the model.NEWLINE prev_reward_batch (Optional[TensorType]): Optional batch of prevNEWLINE rewards used by the model.NEWLINE explore (Optional[bool]): Whether to activate exploration or not. IfNEWLINE None, use value of `config.explore`.NEWLINE timestep (Optional[int]): An optional timestep.NEWLINE is_training (Optional[bool]): An optional is-training flag.NEWLINENEWLINE Returns:NEWLINE Tuple[TensorType, Type[TorchDistributionWrapper], List[TensorType]]:NEWLINE The dist inputs, dist class, and a list of internal state outputsNEWLINE (in the RNN case).NEWLINE """NEWLINE # Get base-model output (w/o the SAC specific parts of the network).NEWLINE model_out, _ = model({NEWLINE "obs": obs_batch,NEWLINE "is_training": is_training,NEWLINE }, [], None)NEWLINE # Use the base output to get the policy outputs from the SAC model'sNEWLINE # policy components.NEWLINE distribution_inputs = model.get_policy_output(model_out)NEWLINE # Get a distribution class to be used with the just calculated dist-inputs.NEWLINE action_dist_class = _get_dist_class(policy.config, policy.action_space)NEWLINENEWLINE return distribution_inputs, action_dist_class, []NEWLINENEWLINENEWLINEdef actor_critic_loss(NEWLINE policy: Policy, model: ModelV2,NEWLINE dist_class: Type[TorchDistributionWrapper],NEWLINE train_batch: SampleBatch) -> Union[TensorType, List[TensorType]]:NEWLINE """Constructs the loss for the Soft Actor Critic.NEWLINENEWLINE Args:NEWLINE policy (Policy): The Policy to calculate the loss for.NEWLINE model (ModelV2): The Model to calculate the loss for.NEWLINE dist_class (Type[TorchDistributionWrapper]: The action distr. class.NEWLINE train_batch (SampleBatch): The training data.NEWLINENEWLINE Returns:NEWLINE Union[TensorType, List[TensorType]]: A single loss tensor or a listNEWLINE of loss tensors.NEWLINE """NEWLINE # Should be True only for debugging purposes (e.g. test cases)!NEWLINE deterministic = policy.config["_deterministic_loss"]NEWLINENEWLINE model_out_t, _ = model({NEWLINE "obs": train_batch[SampleBatch.CUR_OBS],NEWLINE "is_training": True,NEWLINE }, [], None)NEWLINENEWLINE model_out_tp1, _ = model({NEWLINE "obs": train_batch[SampleBatch.NEXT_OBS],NEWLINE "is_training": True,NEWLINE }, [], None)NEWLINENEWLINE target_model_out_tp1, _ = policy.target_model({NEWLINE "obs": train_batch[SampleBatch.NEXT_OBS],NEWLINE "is_training": True,NEWLINE }, [], None)NEWLINENEWLINE alpha = torch.exp(model.log_alpha)NEWLINENEWLINE # Discrete case.NEWLINE if model.discrete:NEWLINE # Get all action probs directly from pi and form their logp.NEWLINE log_pis_t = F.log_softmax(model.get_policy_output(model_out_t), dim=-1)NEWLINE policy_t = torch.exp(log_pis_t)NEWLINE log_pis_tp1 = F.log_softmax(model.get_policy_output(model_out_tp1), -1)NEWLINE policy_tp1 = torch.exp(log_pis_tp1)NEWLINE # Q-values.NEWLINE q_t = model.get_q_values(model_out_t)NEWLINE # Target Q-values.NEWLINE q_tp1 = policy.target_model.get_q_values(target_model_out_tp1)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t = model.get_twin_q_values(model_out_t)NEWLINE twin_q_tp1 = policy.target_model.get_twin_q_values(NEWLINE target_model_out_tp1)NEWLINE q_tp1 = torch.min(q_tp1, twin_q_tp1)NEWLINE q_tp1 -= alpha * log_pis_tp1NEWLINENEWLINE # Actually selected Q-values (from the actions batch).NEWLINE one_hot = F.one_hot(NEWLINE train_batch[SampleBatch.ACTIONS].long(),NEWLINE num_classes=q_t.size()[-1])NEWLINE q_t_selected = torch.sum(q_t * one_hot, dim=-1)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t_selected = torch.sum(twin_q_t * one_hot, dim=-1)NEWLINE # Discrete case: "Best" means weighted by the policy (prob) outputs.NEWLINE q_tp1_best = torch.sum(torch.mul(policy_tp1, q_tp1), dim=-1)NEWLINE q_tp1_best_masked = \NEWLINE (1.0 - train_batch[SampleBatch.DONES].float()) * \NEWLINE q_tp1_bestNEWLINE # Continuous actions case.NEWLINE else:NEWLINE # Sample single actions from distribution.NEWLINE action_dist_class = _get_dist_class(policy.config, policy.action_space)NEWLINE action_dist_t = action_dist_class(NEWLINE model.get_policy_output(model_out_t), policy.model)NEWLINE policy_t = action_dist_t.sample() if not deterministic else \NEWLINE action_dist_t.deterministic_sample()NEWLINE log_pis_t = torch.unsqueeze(action_dist_t.logp(policy_t), -1)NEWLINE action_dist_tp1 = action_dist_class(NEWLINE model.get_policy_output(model_out_tp1), policy.model)NEWLINE policy_tp1 = action_dist_tp1.sample() if not deterministic else \NEWLINE action_dist_tp1.deterministic_sample()NEWLINE log_pis_tp1 = torch.unsqueeze(action_dist_tp1.logp(policy_tp1), -1)NEWLINENEWLINE # Q-values for the actually selected actions.NEWLINE q_t = model.get_q_values(model_out_t, train_batch[SampleBatch.ACTIONS])NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t = model.get_twin_q_values(NEWLINE model_out_t, train_batch[SampleBatch.ACTIONS])NEWLINENEWLINE # Q-values for current policy in given current state.NEWLINE q_t_det_policy = model.get_q_values(model_out_t, policy_t)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t_det_policy = model.get_twin_q_values(NEWLINE model_out_t, policy_t)NEWLINE q_t_det_policy = torch.min(q_t_det_policy, twin_q_t_det_policy)NEWLINENEWLINE # Target q network evaluation.NEWLINE q_tp1 = policy.target_model.get_q_values(target_model_out_tp1,NEWLINE policy_tp1)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_tp1 = policy.target_model.get_twin_q_values(NEWLINE target_model_out_tp1, policy_tp1)NEWLINE # Take min over both twin-NNs.NEWLINE q_tp1 = torch.min(q_tp1, twin_q_tp1)NEWLINENEWLINE q_t_selected = torch.squeeze(q_t, dim=-1)NEWLINE if policy.config["twin_q"]:NEWLINE twin_q_t_selected = torch.squeeze(twin_q_t, dim=-1)NEWLINE q_tp1 -= alpha * log_pis_tp1NEWLINENEWLINE q_tp1_best = torch.squeeze(input=q_tp1, dim=-1)NEWLINE q_tp1_best_masked = (1.0 - train_batch[SampleBatch.DONES].float()) * \NEWLINE q_tp1_bestNEWLINENEWLINE # compute RHS of bellman equationNEWLINE q_t_selected_target = (NEWLINE train_batch[SampleBatch.REWARDS] +NEWLINE (policy.config["gamma"]**policy.config["n_step"]) * q_tp1_best_maskedNEWLINE ).detach()NEWLINENEWLINE # Compute the TD-error (potentially clipped).NEWLINE base_td_error = torch.abs(q_t_selected - q_t_selected_target)NEWLINE if policy.config["twin_q"]:NEWLINE twin_td_error = torch.abs(twin_q_t_selected - q_t_selected_target)NEWLINE td_error = 0.5 * (base_td_error + twin_td_error)NEWLINE else:NEWLINE td_error = base_td_errorNEWLINENEWLINE critic_loss = [NEWLINE torch.mean(train_batch[PRIO_WEIGHTS] * huber_loss(base_td_error))NEWLINE ]NEWLINE if policy.config["twin_q"]:NEWLINE critic_loss.append(NEWLINE torch.mean(train_batch[PRIO_WEIGHTS] * huber_loss(twin_td_error)))NEWLINENEWLINE # Alpha- and actor losses.NEWLINE # Note: In the papers, alpha is used directly, here we take the log.NEWLINE # Discrete case: Multiply the action probs as weights with the originalNEWLINE # loss terms (no expectations needed).NEWLINE if model.discrete:NEWLINE weighted_log_alpha_loss = policy_t.detach() * (NEWLINE -model.log_alpha * (log_pis_t + model.target_entropy).detach())NEWLINE # Sum up weighted terms and mean over all batch items.NEWLINE alpha_loss = torch.mean(torch.sum(weighted_log_alpha_loss, dim=-1))NEWLINE # Actor loss.NEWLINE actor_loss = torch.mean(NEWLINE torch.sum(NEWLINE torch.mul(NEWLINE # NOTE: No stop_grad around policy output hereNEWLINE # (compare with q_t_det_policy for continuous case).NEWLINE policy_t,NEWLINE alpha.detach() * log_pis_t - q_t.detach()),NEWLINE dim=-1))NEWLINE else:NEWLINE alpha_loss = -torch.mean(model.log_alpha *NEWLINE (log_pis_t + model.target_entropy).detach())NEWLINE # Note: Do not detach q_t_det_policy here b/c is depends partlyNEWLINE # on the policy vars (policy sample pushed through Q-net).NEWLINE # However, we must make sure `actor_loss` is not used to updateNEWLINE # the Q-net(s)' variables.NEWLINE actor_loss = torch.mean(alpha.detach() * log_pis_t - q_t_det_policy)NEWLINENEWLINE # Save for stats function.NEWLINE policy.q_t = q_tNEWLINE policy.policy_t = policy_tNEWLINE policy.log_pis_t = log_pis_tNEWLINE policy.td_error = td_errorNEWLINE policy.actor_loss = actor_lossNEWLINE policy.critic_loss = critic_lossNEWLINE policy.alpha_loss = alpha_lossNEWLINE policy.log_alpha_value = model.log_alphaNEWLINE policy.alpha_value = alphaNEWLINE policy.target_entropy = model.target_entropyNEWLINENEWLINE # Return all loss terms corresponding to our optimizers.NEWLINE return tuple([policy.actor_loss] + policy.critic_loss +NEWLINE [policy.alpha_loss])NEWLINENEWLINENEWLINEdef stats(policy: Policy, train_batch: SampleBatch) -> Dict[str, TensorType]:NEWLINE """Stats function for SAC. Returns a dict with important loss stats.NEWLINENEWLINE Args:NEWLINE policy (Policy): The Policy to generate stats for.NEWLINE train_batch (SampleBatch): The SampleBatch (already) used for training.NEWLINENEWLINE Returns:NEWLINE Dict[str, TensorType]: The stats dict.NEWLINE """NEWLINE return {NEWLINE "td_error": policy.td_error,NEWLINE "mean_td_error": torch.mean(policy.td_error),NEWLINE "actor_loss": torch.mean(policy.actor_loss),NEWLINE "critic_loss": torch.mean(torch.stack(policy.critic_loss)),NEWLINE "alpha_loss": torch.mean(policy.alpha_loss),NEWLINE "alpha_value": torch.mean(policy.alpha_value),NEWLINE "log_alpha_value": torch.mean(policy.log_alpha_value),NEWLINE "target_entropy": policy.target_entropy,NEWLINE "policy_t": torch.mean(policy.policy_t),NEWLINE "mean_q": torch.mean(policy.q_t),NEWLINE "max_q": torch.max(policy.q_t),NEWLINE "min_q": torch.min(policy.q_t),NEWLINE }NEWLINENEWLINENEWLINEdef optimizer_fn(policy: Policy, config: TrainerConfigDict) -> \NEWLINE Tuple[LocalOptimizer]:NEWLINE """Creates all necessary optimizers for SAC learning.NEWLINENEWLINE The 3 or 4 (twin_q=True) optimizers returned here correspond to theNEWLINE number of loss terms returned by the loss function.NEWLINENEWLINE Args:NEWLINE policy (Policy): The policy object to be trained.NEWLINE config (TrainerConfigDict): The Trainer's config dict.NEWLINENEWLINE Returns:NEWLINE Tuple[LocalOptimizer]: The local optimizers to use for policy training.NEWLINE """NEWLINE policy.actor_optim = torch.optim.Adam(NEWLINE params=policy.model.policy_variables(),NEWLINE lr=config["optimization"]["actor_learning_rate"],NEWLINE eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon defaultNEWLINE )NEWLINENEWLINE critic_split = len(policy.model.q_variables())NEWLINE if config["twin_q"]:NEWLINE critic_split //= 2NEWLINENEWLINE policy.critic_optims = [NEWLINE torch.optim.Adam(NEWLINE params=policy.model.q_variables()[:critic_split],NEWLINE lr=config["optimization"]["critic_learning_rate"],NEWLINE eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon defaultNEWLINE )NEWLINE ]NEWLINE if config["twin_q"]:NEWLINE policy.critic_optims.append(NEWLINE torch.optim.Adam(NEWLINE params=policy.model.q_variables()[critic_split:],NEWLINE lr=config["optimization"]["critic_learning_rate"],NEWLINE eps=1e-7, # to match tf.keras.optimizers.Adam's eps defaultNEWLINE ))NEWLINE policy.alpha_optim = torch.optim.Adam(NEWLINE params=[policy.model.log_alpha],NEWLINE lr=config["optimization"]["entropy_learning_rate"],NEWLINE eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon defaultNEWLINE )NEWLINENEWLINE return tuple([policy.actor_optim] + policy.critic_optims +NEWLINE [policy.alpha_optim])NEWLINENEWLINENEWLINEclass ComputeTDErrorMixin:NEWLINE """Mixin class calculating TD-error (part of critic loss) per batch item.NEWLINENEWLINE - Adds `policy.compute_td_error()` method for TD-error calculation from aNEWLINE batch of observations/actions/rewards/etc..NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE def compute_td_error(obs_t, act_t, rew_t, obs_tp1, done_mask,NEWLINE importance_weights):NEWLINE input_dict = self._lazy_tensor_dict({NEWLINE SampleBatch.CUR_OBS: obs_t,NEWLINE SampleBatch.ACTIONS: act_t,NEWLINE SampleBatch.REWARDS: rew_t,NEWLINE SampleBatch.NEXT_OBS: obs_tp1,NEWLINE SampleBatch.DONES: done_mask,NEWLINE PRIO_WEIGHTS: importance_weights,NEWLINE })NEWLINE # Do forward pass on loss to update td errors attributeNEWLINE # (one TD-error value per item in batch to update PR weights).NEWLINE actor_critic_loss(self, self.model, None, input_dict)NEWLINENEWLINE # `self.td_error` is set within actor_critic_loss call. ReturnNEWLINE # its updated value here.NEWLINE return self.td_errorNEWLINENEWLINE # Assign the method to policy (self) for later usage.NEWLINE self.compute_td_error = compute_td_errorNEWLINENEWLINENEWLINEclass TargetNetworkMixin:NEWLINE """Mixin class adding a method for (soft) target net(s) synchronizations.NEWLINENEWLINE - Adds the `update_target` method to the policy.NEWLINE Calling `update_target` updates all target Q-networks' weights from theirNEWLINE respective "main" Q-metworks, based on tau (smooth, partial updating).NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE # Hard initial update from Q-net(s) to target Q-net(s).NEWLINE self.update_target(tau=1.0)NEWLINENEWLINE def update_target(self, tau=None):NEWLINE # Update_target_fn will be called periodically to copy Q network toNEWLINE # target Q network, using (soft) tau-synching.NEWLINE tau = tau or self.config.get("tau")NEWLINE model_state_dict = self.model.state_dict()NEWLINE # Support partial (soft) synching.NEWLINE # If tau == 1.0: Full sync from Q-model to target Q-model.NEWLINE target_state_dict = self.target_model.state_dict()NEWLINE model_state_dict = {NEWLINE k: tau * model_state_dict[k] + (1 - tau) * vNEWLINE for k, v in target_state_dict.items()NEWLINE }NEWLINENEWLINE self.target_model.load_state_dict(model_state_dict)NEWLINENEWLINENEWLINEdef setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space,NEWLINE action_space: gym.spaces.Space,NEWLINE config: TrainerConfigDict) -> None:NEWLINE """Call mixin classes' constructors after Policy initialization.NEWLINENEWLINE - Moves the target model(s) to the GPU, if necessary.NEWLINE - Adds the `compute_td_error` method to the given policy.NEWLINE Calling `compute_td_error` with batch data will re-calculate the lossNEWLINE on that batch AND return the per-batch-item TD-error for prioritizedNEWLINE replay buffer record weight updating (in case a prioritized replay bufferNEWLINE is used).NEWLINE - Also adds the `update_target` method to the given policy.NEWLINE Calling `update_target` updates all target Q-networks' weights from theirNEWLINE respective "main" Q-metworks, based on tau (smooth, partial updating).NEWLINENEWLINE Args:NEWLINE policy (Policy): The Policy object.NEWLINE obs_space (gym.spaces.Space): The Policy's observation space.NEWLINE action_space (gym.spaces.Space): The Policy's action space.NEWLINE config (TrainerConfigDict): The Policy's config.NEWLINE """NEWLINE policy.target_model = policy.target_model.to(policy.device)NEWLINE policy.model.log_alpha = policy.model.log_alpha.to(policy.device)NEWLINE policy.model.target_entropy = policy.model.target_entropy.to(policy.device)NEWLINE ComputeTDErrorMixin.__init__(policy)NEWLINE TargetNetworkMixin.__init__(policy)NEWLINENEWLINENEWLINE# Build a child class of `TorchPolicy`, given the custom functions definedNEWLINE# above.NEWLINESACTorchPolicy = build_policy_class(NEWLINE name="SACTorchPolicy",NEWLINE framework="torch",NEWLINE loss_fn=actor_critic_loss,NEWLINE get_default_config=lambda: ray.rllib.agents.sac.sac.DEFAULT_CONFIG,NEWLINE stats_fn=stats,NEWLINE postprocess_fn=postprocess_trajectory,NEWLINE extra_grad_process_fn=apply_grad_clipping,NEWLINE optimizer_fn=optimizer_fn,NEWLINE validate_spaces=validate_spaces,NEWLINE before_loss_init=setup_late_mixins,NEWLINE make_model_and_action_dist=build_sac_model_and_action_dist,NEWLINE mixins=[TargetNetworkMixin, ComputeTDErrorMixin],NEWLINE action_distribution_fn=action_distribution_fn,NEWLINE)NEWLINE |
# Generated by Django 3.2.5 on 2021-07-18 23:06NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('login', '0001_initial'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='config',NEWLINE name='level',NEWLINE field=models.SmallIntegerField(),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='user',NEWLINE name='age',NEWLINE field=models.PositiveSmallIntegerField(blank=True),NEWLINE ),NEWLINE ]NEWLINE |
#!/usr/bin/env pythonNEWLINENEWLINE# Copyright (c) 2015 Google Inc. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINENEWLINE"""NEWLINEMake sure that we cause downstream modules to get built when we depend on theNEWLINEparent targets.NEWLINE"""NEWLINENEWLINEimport TestGypNEWLINENEWLINEtest = TestGyp.TestGyp()NEWLINENEWLINECHDIR = 'module-dep'NEWLINEtest.run_gyp('indirect-module-dependency.gyp', chdir=CHDIR)NEWLINEtest.build('indirect-module-dependency.gyp', 'an_exe', chdir=CHDIR)NEWLINEtest.built_file_must_exist(NEWLINE test.built_file_basename('a_module', test.LOADABLE_MODULE), chdir=CHDIR)NEWLINENEWLINEtest.pass_test()NEWLINE |
from django.db import modelsNEWLINENEWLINE# Create your models here.NEWLINEclass Grade(models.Model):NEWLINE gno=models.CharField(max_length=20,primary_key=True)NEWLINE gname=models.CharField(max_length=20,unique=True)NEWLINE class Meta():NEWLINE db_table = 'grade'NEWLINENEWLINEclass Course(models.Model):NEWLINE cno=models.CharField(max_length=20,primary_key=True)NEWLINE cname=models.CharField(max_length=100)NEWLINE textBook=models.CharField(max_length=50)NEWLINE gradeCourses=models.ManyToManyField("Grade",through="TeachPlan")NEWLINE class Meta():NEWLINE db_table = 'course'NEWLINENEWLINEclass TeachPlan(models.Model):NEWLINE course = models.ForeignKey("Course", on_delete=models.CASCADE)NEWLINE grade = models.ForeignKey("Grade", on_delete=models.CASCADE)NEWLINE credit=models.FloatField()NEWLINE teach_date = models.DateField()NEWLINE checkType = models.CharField(max_length=50)NEWLINE class Meta():NEWLINE db_table = 'teachplan'NEWLINENEWLINEclass Teacher(models.Model):NEWLINE tno=models.CharField(max_length=20,primary_key=True)NEWLINE tname=models.CharField(max_length=50)NEWLINE gender=models.CharField(max_length=10)NEWLINE jobTitle=models.CharField(max_length=10)NEWLINE teachCourse=models.ManyToManyField("Course")NEWLINE class Meta():NEWLINE db_table = 'teacher'NEWLINENEWLINEclass Student(models.Model):NEWLINE sno=models.CharField(max_length=50,primary_key=True)NEWLINE sname=models.CharField(max_length=50)NEWLINE gender=models.CharField(max_length=10)NEWLINE studentCourse=models.ManyToManyField("Course",through="Achievement")NEWLINE class Meta():NEWLINE db_table = 'student'NEWLINENEWLINEclass Achievement(models.Model):NEWLINE course = models.ForeignKey("Course", on_delete=models.CASCADE)NEWLINE student = models.ForeignKey("Student", on_delete=models.CASCADE)NEWLINE score = models.FloatField()NEWLINE gain_date = models.DateField()NEWLINE class Meta():NEWLINE db_table = 'achievement'NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE |
from app.business.blog.views import blog # noqaNEWLINE |
from time import timeNEWLINEfrom base64 import b16encodeNEWLINEfrom functools import partialNEWLINEfrom operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__NEWLINENEWLINEfrom six import (NEWLINE integer_types as _integer_types,NEWLINE text_type as _text_type)NEWLINENEWLINEfrom OpenSSL._util import (NEWLINE ffi as _ffi,NEWLINE lib as _lib,NEWLINE exception_from_error_queue as _exception_from_error_queue,NEWLINE byte_string as _byte_string,NEWLINE native as _native)NEWLINENEWLINEFILETYPE_PEM = _lib.SSL_FILETYPE_PEMNEWLINEFILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1NEWLINENEWLINE# TODO This was an API mistake. OpenSSL has no such constant.NEWLINEFILETYPE_TEXT = 2 ** 16 - 1NEWLINENEWLINETYPE_RSA = _lib.EVP_PKEY_RSANEWLINETYPE_DSA = _lib.EVP_PKEY_DSANEWLINENEWLINENEWLINEclass Error(Exception):NEWLINE """NEWLINE An error occurred in an `OpenSSL.crypto` API.NEWLINE """NEWLINENEWLINENEWLINE_raise_current_error = partial(_exception_from_error_queue, Error)NEWLINENEWLINEdef _untested_error(where):NEWLINE """NEWLINE An OpenSSL API failed somehow. Additionally, the failure which wasNEWLINE encountered isn't one that's exercised by the test suite so future behaviorNEWLINE of pyOpenSSL is now somewhat less predictable.NEWLINE """NEWLINE raise RuntimeError("Unknown %s failure" % (where,))NEWLINENEWLINENEWLINENEWLINEdef _new_mem_buf(buffer=None):NEWLINE """NEWLINE Allocate a new OpenSSL memory BIO.NEWLINENEWLINE Arrange for the garbage collector to clean it up automatically.NEWLINENEWLINE :param buffer: None or some bytes to use to put into the BIO so that theyNEWLINE can be read out.NEWLINE """NEWLINE if buffer is None:NEWLINE bio = _lib.BIO_new(_lib.BIO_s_mem())NEWLINE free = _lib.BIO_freeNEWLINE else:NEWLINE data = _ffi.new("char[]", buffer)NEWLINE bio = _lib.BIO_new_mem_buf(data, len(buffer))NEWLINE # Keep the memory alive as long as the bio is alive!NEWLINE def free(bio, ref=data):NEWLINE return _lib.BIO_free(bio)NEWLINENEWLINE if bio == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE bio = _ffi.gc(bio, free)NEWLINE return bioNEWLINENEWLINENEWLINENEWLINEdef _bio_to_string(bio):NEWLINE """NEWLINE Copy the contents of an OpenSSL BIO object into a Python byte string.NEWLINE """NEWLINE result_buffer = _ffi.new('char**')NEWLINE buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)NEWLINE return _ffi.buffer(result_buffer[0], buffer_length)[:]NEWLINENEWLINENEWLINENEWLINEdef _set_asn1_time(boundary, when):NEWLINE """NEWLINE The the time value of an ASN1 time object.NEWLINENEWLINE @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safelyNEWLINE castable to that type) which will have its value set.NEWLINE @param when: A string representation of the desired time value.NEWLINENEWLINE @raise TypeError: If C{when} is not a L{bytes} string.NEWLINE @raise ValueError: If C{when} does not represent a time in the requiredNEWLINE format.NEWLINE @raise RuntimeError: If the time value cannot be set for some otherNEWLINE (unspecified) reason.NEWLINE """NEWLINE if not isinstance(when, bytes):NEWLINE raise TypeError("when must be a byte string")NEWLINENEWLINE set_result = _lib.ASN1_GENERALIZEDTIME_set_string(NEWLINE _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)NEWLINE if set_result == 0:NEWLINE dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)NEWLINE _lib.ASN1_STRING_set(dummy, when, len(when))NEWLINE check_result = _lib.ASN1_GENERALIZEDTIME_check(NEWLINE _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))NEWLINE if not check_result:NEWLINE raise ValueError("Invalid string")NEWLINE else:NEWLINE _untested_error()NEWLINENEWLINENEWLINENEWLINEdef _get_asn1_time(timestamp):NEWLINE """NEWLINE Retrieve the time value of an ASN1 time object.NEWLINENEWLINE @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable toNEWLINE that type) from which the time value will be retrieved.NEWLINENEWLINE @return: The time value from C{timestamp} as a L{bytes} string in a certainNEWLINE format. Or C{None} if the object contains no time value.NEWLINE """NEWLINE string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)NEWLINE if _lib.ASN1_STRING_length(string_timestamp) == 0:NEWLINE return NoneNEWLINE elif _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME:NEWLINE return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))NEWLINE else:NEWLINE generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")NEWLINE _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)NEWLINE if generalized_timestamp[0] == _ffi.NULL:NEWLINE # This may happen:NEWLINE # - if timestamp was not an ASN1_TIMENEWLINE # - if allocating memory for the ASN1_GENERALIZEDTIME failedNEWLINE # - if a copy of the time data from timestamp cannot be made forNEWLINE # the newly allocated ASN1_GENERALIZEDTIMENEWLINE #NEWLINE # These are difficult to test. cffi enforces the ASN1_TIME type.NEWLINE # Memory allocation failures are a pain to triggerNEWLINE # deterministically.NEWLINE _untested_error("ASN1_TIME_to_generalizedtime")NEWLINE else:NEWLINE string_timestamp = _ffi.cast(NEWLINE "ASN1_STRING*", generalized_timestamp[0])NEWLINE string_data = _lib.ASN1_STRING_data(string_timestamp)NEWLINE string_result = _ffi.string(string_data)NEWLINE _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])NEWLINE return string_resultNEWLINENEWLINENEWLINENEWLINEclass PKey(object):NEWLINE _only_public = FalseNEWLINE _initialized = TrueNEWLINENEWLINE def __init__(self):NEWLINE pkey = _lib.EVP_PKEY_new()NEWLINE self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)NEWLINE self._initialized = FalseNEWLINENEWLINENEWLINE def generate_key(self, type, bits):NEWLINE """NEWLINE Generate a key of a given type, with a given number of a bitsNEWLINENEWLINE :param type: The key type (TYPE_RSA or TYPE_DSA)NEWLINE :param bits: The number of bitsNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(type, int):NEWLINE raise TypeError("type must be an integer")NEWLINENEWLINE if not isinstance(bits, int):NEWLINE raise TypeError("bits must be an integer")NEWLINENEWLINE # TODO Check error returnNEWLINE exponent = _lib.BN_new()NEWLINE exponent = _ffi.gc(exponent, _lib.BN_free)NEWLINE _lib.BN_set_word(exponent, _lib.RSA_F4)NEWLINENEWLINE if type == TYPE_RSA:NEWLINE if bits <= 0:NEWLINE raise ValueError("Invalid number of bits")NEWLINENEWLINE rsa = _lib.RSA_new()NEWLINENEWLINE result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)NEWLINE if result == 0:NEWLINE # TODO: The test for this case is commented out. DifferentNEWLINE # builds of OpenSSL appear to have different failure modes thatNEWLINE # make it hard to test. Visual inspection of the OpenSSLNEWLINE # source reveals that a return value of 0 signals an error.NEWLINE # Manual testing on a particular build of OpenSSL suggests thatNEWLINE # this is probably the appropriate way to handle those errors.NEWLINE _raise_current_error()NEWLINENEWLINE result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)NEWLINE if not result:NEWLINE # TODO: It appears as though this can fail if an engine is inNEWLINE # use which does not support RSA.NEWLINE _raise_current_error()NEWLINENEWLINE elif type == TYPE_DSA:NEWLINE dsa = _lib.DSA_generate_parameters(NEWLINE bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE if dsa == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE if not _lib.DSA_generate_key(dsa):NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE if not _lib.EVP_PKEY_assign_DSA(self._pkey, dsa):NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE else:NEWLINE raise Error("No such key type")NEWLINENEWLINE self._initialized = TrueNEWLINENEWLINENEWLINE def check(self):NEWLINE """NEWLINE Check the consistency of an RSA private key.NEWLINENEWLINE :return: True if key is consistent.NEWLINE :raise Error: if the key is inconsistent.NEWLINE :raise TypeError: if the key is of a type which cannot be checked.NEWLINE Only RSA keys can currently be checked.NEWLINE """NEWLINE if self._only_public:NEWLINE raise TypeError("public key only")NEWLINENEWLINE if _lib.EVP_PKEY_type(self._pkey.type) != _lib.EVP_PKEY_RSA:NEWLINE raise TypeError("key type unsupported")NEWLINENEWLINE rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)NEWLINE rsa = _ffi.gc(rsa, _lib.RSA_free)NEWLINE result = _lib.RSA_check_key(rsa)NEWLINE if result:NEWLINE return TrueNEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def type(self):NEWLINE """NEWLINE Returns the type of the keyNEWLINENEWLINE :return: The type of the key.NEWLINE """NEWLINE return self._pkey.typeNEWLINENEWLINENEWLINE def bits(self):NEWLINE """NEWLINE Returns the number of bits of the keyNEWLINENEWLINE :return: The number of bits of the key.NEWLINE """NEWLINE return _lib.EVP_PKEY_bits(self._pkey)NEWLINEPKeyType = PKeyNEWLINENEWLINENEWLINENEWLINEclass X509Name(object):NEWLINE def __init__(self, name):NEWLINE """NEWLINE Create a new X509Name, copying the given X509Name instance.NEWLINENEWLINE :param name: An X509Name object to copyNEWLINE """NEWLINE name = _lib.X509_NAME_dup(name._name)NEWLINE self._name = _ffi.gc(name, _lib.X509_NAME_free)NEWLINENEWLINENEWLINE def __setattr__(self, name, value):NEWLINE if name.startswith('_'):NEWLINE return super(X509Name, self).__setattr__(name, value)NEWLINENEWLINE # Note: we really do not want str subclasses here, so we do not useNEWLINE # isinstance.NEWLINE if type(name) is not str:NEWLINE raise TypeError("attribute name must be string, not '%.200s'" % (NEWLINE type(value).__name__,))NEWLINENEWLINE nid = _lib.OBJ_txt2nid(_byte_string(name))NEWLINE if nid == _lib.NID_undef:NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINE raise AttributeError("No such attribute")NEWLINENEWLINE # If there's an old entry for this NID, remove itNEWLINE for i in range(_lib.X509_NAME_entry_count(self._name)):NEWLINE ent = _lib.X509_NAME_get_entry(self._name, i)NEWLINE ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)NEWLINE ent_nid = _lib.OBJ_obj2nid(ent_obj)NEWLINE if nid == ent_nid:NEWLINE ent = _lib.X509_NAME_delete_entry(self._name, i)NEWLINE _lib.X509_NAME_ENTRY_free(ent)NEWLINE breakNEWLINENEWLINE if isinstance(value, _text_type):NEWLINE value = value.encode('utf-8')NEWLINENEWLINE add_result = _lib.X509_NAME_add_entry_by_NID(NEWLINE self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)NEWLINE if not add_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def __getattr__(self, name):NEWLINE """NEWLINE Find attribute. An X509Name object has the following attributes:NEWLINE countryName (alias C), stateOrProvince (alias ST), locality (alias L),NEWLINE organization (alias O), organizationalUnit (alias OU), commonName (aliasNEWLINE CN) and more...NEWLINE """NEWLINE nid = _lib.OBJ_txt2nid(_byte_string(name))NEWLINE if nid == _lib.NID_undef:NEWLINE # This is a bit weird. OBJ_txt2nid indicated failure, but it seemsNEWLINE # a lower level function, a2d_ASN1_OBJECT, also feels the need toNEWLINE # push something onto the error queue. If we don't clean that upNEWLINE # now, someone else will bump into it later and be quite confused.NEWLINE # See lp#314814.NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINE return super(X509Name, self).__getattr__(name)NEWLINENEWLINE entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)NEWLINE if entry_index == -1:NEWLINE return NoneNEWLINENEWLINE entry = _lib.X509_NAME_get_entry(self._name, entry_index)NEWLINE data = _lib.X509_NAME_ENTRY_get_data(entry)NEWLINENEWLINE result_buffer = _ffi.new("unsigned char**")NEWLINE data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)NEWLINE if data_length < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE try:NEWLINE result = _ffi.buffer(result_buffer[0], data_length)[:].decode('utf-8')NEWLINE finally:NEWLINE # XXX untestedNEWLINE _lib.OPENSSL_free(result_buffer[0])NEWLINE return resultNEWLINENEWLINENEWLINE def _cmp(op):NEWLINE def f(self, other):NEWLINE if not isinstance(other, X509Name):NEWLINE return NotImplementedNEWLINE result = _lib.X509_NAME_cmp(self._name, other._name)NEWLINE return op(result, 0)NEWLINE return fNEWLINENEWLINE __eq__ = _cmp(__eq__)NEWLINE __ne__ = _cmp(__ne__)NEWLINENEWLINE __lt__ = _cmp(__lt__)NEWLINE __le__ = _cmp(__le__)NEWLINENEWLINE __gt__ = _cmp(__gt__)NEWLINE __ge__ = _cmp(__ge__)NEWLINENEWLINE def __repr__(self):NEWLINE """NEWLINE String representation of an X509NameNEWLINE """NEWLINE result_buffer = _ffi.new("char[]", 512);NEWLINE format_result = _lib.X509_NAME_oneline(NEWLINE self._name, result_buffer, len(result_buffer))NEWLINENEWLINE if format_result == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return "<X509Name object '%s'>" % (NEWLINE _native(_ffi.string(result_buffer)),)NEWLINENEWLINENEWLINE def hash(self):NEWLINE """NEWLINE Return the hash value of this nameNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return _lib.X509_NAME_hash(self._name)NEWLINENEWLINENEWLINE def der(self):NEWLINE """NEWLINE Return the DER encoding of this nameNEWLINENEWLINE :return: A :py:class:`bytes` instance giving the DER encoded form ofNEWLINE this name.NEWLINE """NEWLINE result_buffer = _ffi.new('unsigned char**')NEWLINE encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)NEWLINE if encode_result < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE string_result = _ffi.buffer(result_buffer[0], encode_result)[:]NEWLINE _lib.OPENSSL_free(result_buffer[0])NEWLINE return string_resultNEWLINENEWLINENEWLINE def get_components(self):NEWLINE """NEWLINE Returns the split-up components of this name.NEWLINENEWLINE :return: List of tuples (name, value).NEWLINE """NEWLINE result = []NEWLINE for i in range(_lib.X509_NAME_entry_count(self._name)):NEWLINE ent = _lib.X509_NAME_get_entry(self._name, i)NEWLINENEWLINE fname = _lib.X509_NAME_ENTRY_get_object(ent)NEWLINE fval = _lib.X509_NAME_ENTRY_get_data(ent)NEWLINENEWLINE nid = _lib.OBJ_obj2nid(fname)NEWLINE name = _lib.OBJ_nid2sn(nid)NEWLINENEWLINE result.append((NEWLINE _ffi.string(name),NEWLINE _ffi.string(NEWLINE _lib.ASN1_STRING_data(fval),NEWLINE _lib.ASN1_STRING_length(fval))))NEWLINENEWLINE return resultNEWLINEX509NameType = X509NameNEWLINENEWLINENEWLINEclass X509Extension(object):NEWLINE def __init__(self, type_name, critical, value, subject=None, issuer=None):NEWLINE """NEWLINE :param typename: The name of the extension to create.NEWLINE :type typename: :py:data:`str`NEWLINENEWLINE :param critical: A flag indicating whether this is a critical extension.NEWLINENEWLINE :param value: The value of the extension.NEWLINE :type value: :py:data:`str`NEWLINENEWLINE :param subject: Optional X509 cert to use as subject.NEWLINE :type subject: :py:class:`X509`NEWLINENEWLINE :param issuer: Optional X509 cert to use as issuer.NEWLINE :type issuer: :py:class:`X509`NEWLINENEWLINE :return: The X509Extension objectNEWLINE """NEWLINE ctx = _ffi.new("X509V3_CTX*")NEWLINENEWLINE # A context is necessary for any extension which uses the r2i conversionNEWLINE # method. That is, X509V3_EXT_nconf may segfault if passed a NULL ctx.NEWLINE # Start off by initializing most of the fields to NULL.NEWLINE _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)NEWLINENEWLINE # We have no configuration database - but perhaps we should (someNEWLINE # extensions may require it).NEWLINE _lib.X509V3_set_ctx_nodb(ctx)NEWLINENEWLINE # Initialize the subject and issuer, if appropriate. ctx is a local,NEWLINE # and as far as I can tell none of the X509V3_* APIs invoked here stealNEWLINE # any references, so no need to mess with reference counts or duplicates.NEWLINE if issuer is not None:NEWLINE if not isinstance(issuer, X509):NEWLINE raise TypeError("issuer must be an X509 instance")NEWLINE ctx.issuer_cert = issuer._x509NEWLINE if subject is not None:NEWLINE if not isinstance(subject, X509):NEWLINE raise TypeError("subject must be an X509 instance")NEWLINE ctx.subject_cert = subject._x509NEWLINENEWLINE if critical:NEWLINE # There are other OpenSSL APIs which would let us pass in criticalNEWLINE # separately, but they're harder to use, and since value is alreadyNEWLINE # a pile of crappy junk smuggling a ton of utterly importantNEWLINE # structured data, what's the point of trying to avoid nasty stuffNEWLINE # with strings? (However, X509V3_EXT_i2d in particular seems like itNEWLINE # would be a better API to invoke. I do not know where to get theNEWLINE # ext_struc it desires for its last parameter, though.)NEWLINE value = b"critical," + valueNEWLINENEWLINE extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)NEWLINE if extension == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)NEWLINENEWLINENEWLINE @propertyNEWLINE def _nid(self):NEWLINE return _lib.OBJ_obj2nid(self._extension.object)NEWLINENEWLINE _prefixes = {NEWLINE _lib.GEN_EMAIL: "email",NEWLINE _lib.GEN_DNS: "DNS",NEWLINE _lib.GEN_URI: "URI",NEWLINE }NEWLINENEWLINE def _subjectAltNameString(self):NEWLINE method = _lib.X509V3_EXT_get(self._extension)NEWLINE if method == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE payload = self._extension.value.dataNEWLINE length = self._extension.value.lengthNEWLINENEWLINE payloadptr = _ffi.new("unsigned char**")NEWLINE payloadptr[0] = payloadNEWLINENEWLINE if method.it != _ffi.NULL:NEWLINE ptr = _lib.ASN1_ITEM_ptr(method.it)NEWLINE data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)NEWLINE names = _ffi.cast("GENERAL_NAMES*", data)NEWLINE else:NEWLINE names = _ffi.cast(NEWLINE "GENERAL_NAMES*",NEWLINE method.d2i(_ffi.NULL, payloadptr, length))NEWLINENEWLINE parts = []NEWLINE for i in range(_lib.sk_GENERAL_NAME_num(names)):NEWLINE name = _lib.sk_GENERAL_NAME_value(names, i)NEWLINE try:NEWLINE label = self._prefixes[name.type]NEWLINE except KeyError:NEWLINE bio = _new_mem_buf()NEWLINE _lib.GENERAL_NAME_print(bio, name)NEWLINE parts.append(_native(_bio_to_string(bio)))NEWLINE else:NEWLINE value = _native(NEWLINE _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])NEWLINE parts.append(label + ":" + value)NEWLINE return ", ".join(parts)NEWLINENEWLINENEWLINE def __str__(self):NEWLINE """NEWLINE :return: a nice text representation of the extensionNEWLINE """NEWLINE if _lib.NID_subject_alt_name == self._nid:NEWLINE return self._subjectAltNameString()NEWLINENEWLINE bio = _new_mem_buf()NEWLINE print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)NEWLINE if not print_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _native(_bio_to_string(bio))NEWLINENEWLINENEWLINE def get_critical(self):NEWLINE """NEWLINE Returns the critical field of the X509ExtensionNEWLINENEWLINE :return: The critical field.NEWLINE """NEWLINE return _lib.X509_EXTENSION_get_critical(self._extension)NEWLINENEWLINENEWLINE def get_short_name(self):NEWLINE """NEWLINE Returns the short version of the type name of the X509ExtensionNEWLINENEWLINE :return: The short type name.NEWLINE """NEWLINE obj = _lib.X509_EXTENSION_get_object(self._extension)NEWLINE nid = _lib.OBJ_obj2nid(obj)NEWLINE return _ffi.string(_lib.OBJ_nid2sn(nid))NEWLINENEWLINENEWLINE def get_data(self):NEWLINE """NEWLINE Returns the data of the X509ExtensionNEWLINENEWLINE :return: A :py:data:`str` giving the X509Extension's ASN.1 encoded data.NEWLINE """NEWLINE octet_result = _lib.X509_EXTENSION_get_data(self._extension)NEWLINE string_result = _ffi.cast('ASN1_STRING*', octet_result)NEWLINE char_result = _lib.ASN1_STRING_data(string_result)NEWLINE result_length = _lib.ASN1_STRING_length(string_result)NEWLINE return _ffi.buffer(char_result, result_length)[:]NEWLINENEWLINEX509ExtensionType = X509ExtensionNEWLINENEWLINENEWLINEclass X509Req(object):NEWLINE def __init__(self):NEWLINE req = _lib.X509_REQ_new()NEWLINE self._req = _ffi.gc(req, _lib.X509_REQ_free)NEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificate requestNEWLINENEWLINE :param pkey: The public key to useNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key from the certificate requestNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_version(self, version):NEWLINE """NEWLINE Set the version subfield (RFC 2459, section 4.1.2.1) of the certificateNEWLINE request.NEWLINENEWLINE :param version: The version numberNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.X509_REQ_set_version(self._req, version)NEWLINE if not set_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_version(self):NEWLINE """NEWLINE Get the version subfield (RFC 2459, section 4.1.2.1) of the certificateNEWLINE request.NEWLINENEWLINE :return: an integer giving the value of the version subfieldNEWLINE """NEWLINE return _lib.X509_REQ_get_version(self._req)NEWLINENEWLINENEWLINE def get_subject(self):NEWLINE """NEWLINE Create an X509Name object for the subject of the certificate requestNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE name = X509Name.__new__(X509Name)NEWLINE name._name = _lib.X509_REQ_get_subject_name(self._req)NEWLINE if name._name == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # The name is owned by the X509Req structure. As long as the X509NameNEWLINE # Python object is alive, keep the X509Req Python object alive.NEWLINE name._owner = selfNEWLINENEWLINE return nameNEWLINENEWLINENEWLINE def add_extensions(self, extensions):NEWLINE """NEWLINE Add extensions to the request.NEWLINENEWLINE :param extensions: a sequence of X509Extension objectsNEWLINE :return: NoneNEWLINE """NEWLINE stack = _lib.sk_X509_EXTENSION_new_null()NEWLINE if stack == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)NEWLINENEWLINE for ext in extensions:NEWLINE if not isinstance(ext, X509Extension):NEWLINE raise ValueError("One of the elements is not an X509Extension")NEWLINENEWLINE # TODO push can fail (here and elsewhere)NEWLINE _lib.sk_X509_EXTENSION_push(stack, ext._extension)NEWLINENEWLINE add_result = _lib.X509_REQ_add_extensions(self._req, stack)NEWLINE if not add_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate request using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if pkey._only_public:NEWLINE raise ValueError("Key has only public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)NEWLINE if not sign_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def verify(self, pkey):NEWLINE """NEWLINE Verifies a certificate request using the supplied public keyNEWLINENEWLINE :param key: a public keyNEWLINE :return: True if the signature is correct.NEWLINENEWLINE :raise OpenSSL.crypto.Error: If the signature is invalid or there is aNEWLINE problem verifying the signature.NEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE result = _lib.X509_REQ_verify(self._req, pkey._pkey)NEWLINE if result <= 0:NEWLINE _raise_current_error()NEWLINENEWLINE return resultNEWLINENEWLINENEWLINEX509ReqType = X509ReqNEWLINENEWLINENEWLINENEWLINEclass X509(object):NEWLINE def __init__(self):NEWLINE # TODO Allocation failure? And why not __new__ instead of __init__?NEWLINE x509 = _lib.X509_new()NEWLINE self._x509 = _ffi.gc(x509, _lib.X509_free)NEWLINENEWLINENEWLINE def set_version(self, version):NEWLINE """NEWLINE Set version number of the certificateNEWLINENEWLINE :param version: The version numberNEWLINE :type version: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(version, int):NEWLINE raise TypeError("version must be an integer")NEWLINENEWLINE _lib.X509_set_version(self._x509, version)NEWLINENEWLINENEWLINE def get_version(self):NEWLINE """NEWLINE Return version number of the certificateNEWLINENEWLINE :return: Version number as a Python integerNEWLINE """NEWLINE return _lib.X509_get_version(self._x509)NEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key of the certificateNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.X509_get_pubkey(self._x509)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificateNEWLINENEWLINE :param pkey: The public keyNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)NEWLINE if not set_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINENEWLINE if pkey._only_public:NEWLINE raise ValueError("Key only has public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if evp_md == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)NEWLINE if not sign_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_signature_algorithm(self):NEWLINE """NEWLINE Retrieve the signature algorithm used in the certificateNEWLINENEWLINE :return: A byte string giving the name of the signature algorithm used inNEWLINE the certificate.NEWLINE :raise ValueError: If the signature algorithm is undefined.NEWLINE """NEWLINE alg = self._x509.cert_info.signature.algorithmNEWLINE nid = _lib.OBJ_obj2nid(alg)NEWLINE if nid == _lib.NID_undef:NEWLINE raise ValueError("Undefined signature algorithm")NEWLINE return _ffi.string(_lib.OBJ_nid2ln(nid))NEWLINENEWLINENEWLINE def digest(self, digest_name):NEWLINE """NEWLINE Return the digest of the X509 object.NEWLINENEWLINE :param digest_name: The name of the digest algorithm to use.NEWLINE :type digest_name: :py:class:`bytes`NEWLINENEWLINE :return: The digest of the objectNEWLINE """NEWLINE digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))NEWLINE if digest == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)NEWLINE result_length = _ffi.new("unsigned int[]", 1)NEWLINE result_length[0] = len(result_buffer)NEWLINENEWLINE digest_result = _lib.X509_digest(NEWLINE self._x509, digest, result_buffer, result_length)NEWLINENEWLINE if not digest_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return b":".join([NEWLINE b16encode(ch).upper() for chNEWLINE in _ffi.buffer(result_buffer, result_length[0])])NEWLINENEWLINENEWLINE def subject_name_hash(self):NEWLINE """NEWLINE Return the hash of the X509 subject.NEWLINENEWLINE :return: The hash of the subject.NEWLINE """NEWLINE return _lib.X509_subject_name_hash(self._x509)NEWLINENEWLINENEWLINE def set_serial_number(self, serial):NEWLINE """NEWLINE Set serial number of the certificateNEWLINENEWLINE :param serial: The serial numberNEWLINE :type serial: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(serial, _integer_types):NEWLINE raise TypeError("serial must be an integer")NEWLINENEWLINE hex_serial = hex(serial)[2:]NEWLINE if not isinstance(hex_serial, bytes):NEWLINE hex_serial = hex_serial.encode('ascii')NEWLINENEWLINE bignum_serial = _ffi.new("BIGNUM**")NEWLINENEWLINE # BN_hex2bn stores the result in &bignum. Unless it doesn't feel likeNEWLINE # it. If bignum is still NULL after this call, then the return value isNEWLINE # actually the result. I hope. -exarkunNEWLINE small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)NEWLINENEWLINE if bignum_serial[0] == _ffi.NULL:NEWLINE set_result = _lib.ASN1_INTEGER_set(NEWLINE _lib.X509_get_serialNumber(self._x509), small_serial)NEWLINE if set_result:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINE else:NEWLINE asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)NEWLINE _lib.BN_free(bignum_serial[0])NEWLINE if asn1_serial == _ffi.NULL:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINE asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)NEWLINE set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)NEWLINE if not set_result:NEWLINE # TODO Not testedNEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_serial_number(self):NEWLINE """NEWLINE Return serial number of the certificateNEWLINENEWLINE :return: Serial number as a Python integerNEWLINE """NEWLINE asn1_serial = _lib.X509_get_serialNumber(self._x509)NEWLINE bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)NEWLINE try:NEWLINE hex_serial = _lib.BN_bn2hex(bignum_serial)NEWLINE try:NEWLINE hexstring_serial = _ffi.string(hex_serial)NEWLINE serial = int(hexstring_serial, 16)NEWLINE return serialNEWLINE finally:NEWLINE _lib.OPENSSL_free(hex_serial)NEWLINE finally:NEWLINE _lib.BN_free(bignum_serial)NEWLINENEWLINENEWLINE def gmtime_adj_notAfter(self, amount):NEWLINE """NEWLINE Adjust the time stamp for when the certificate stops being validNEWLINENEWLINE :param amount: The number of seconds by which to adjust the endingNEWLINE validity time.NEWLINE :type amount: :py:class:`int`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(amount, int):NEWLINE raise TypeError("amount must be an integer")NEWLINENEWLINE notAfter = _lib.X509_get_notAfter(self._x509)NEWLINE _lib.X509_gmtime_adj(notAfter, amount)NEWLINENEWLINENEWLINE def gmtime_adj_notBefore(self, amount):NEWLINE """NEWLINE Change the timestamp for when the certificate starts being valid to the currentNEWLINE time plus an offset.NEWLINENEWLINE :param amount: The number of seconds by which to adjust the starting validityNEWLINE time.NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(amount, int):NEWLINE raise TypeError("amount must be an integer")NEWLINENEWLINE notBefore = _lib.X509_get_notBefore(self._x509)NEWLINE _lib.X509_gmtime_adj(notBefore, amount)NEWLINENEWLINENEWLINE def has_expired(self):NEWLINE """NEWLINE Check whether the certificate has expired.NEWLINENEWLINE :return: True if the certificate has expired, false otherwiseNEWLINE """NEWLINE now = int(time())NEWLINE notAfter = _lib.X509_get_notAfter(self._x509)NEWLINE return _lib.ASN1_UTCTIME_cmp_time_t(NEWLINE _ffi.cast('ASN1_UTCTIME*', notAfter), now) < 0NEWLINENEWLINENEWLINE def _get_boundary_time(self, which):NEWLINE return _get_asn1_time(which(self._x509))NEWLINENEWLINENEWLINE def get_notBefore(self):NEWLINE """NEWLINE Retrieve the time stamp for when the certificate starts being validNEWLINENEWLINE :return: A string giving the timestamp, in the format::NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE or None if there is no value set.NEWLINE """NEWLINE return self._get_boundary_time(_lib.X509_get_notBefore)NEWLINENEWLINENEWLINE def _set_boundary_time(self, which, when):NEWLINE return _set_asn1_time(which(self._x509), when)NEWLINENEWLINENEWLINE def set_notBefore(self, when):NEWLINE """NEWLINE Set the time stamp for when the certificate starts being validNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE :type when: :py:class:`bytes`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_boundary_time(_lib.X509_get_notBefore, when)NEWLINENEWLINENEWLINE def get_notAfter(self):NEWLINE """NEWLINE Retrieve the time stamp for when the certificate stops being validNEWLINENEWLINE :return: A string giving the timestamp, in the format::NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE or None if there is no value set.NEWLINE """NEWLINE return self._get_boundary_time(_lib.X509_get_notAfter)NEWLINENEWLINENEWLINE def set_notAfter(self, when):NEWLINE """NEWLINE Set the time stamp for when the certificate stops being validNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE :type when: :py:class:`bytes`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_boundary_time(_lib.X509_get_notAfter, when)NEWLINENEWLINENEWLINE def _get_name(self, which):NEWLINE name = X509Name.__new__(X509Name)NEWLINE name._name = which(self._x509)NEWLINE if name._name == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # The name is owned by the X509 structure. As long as the X509NameNEWLINE # Python object is alive, keep the X509 Python object alive.NEWLINE name._owner = selfNEWLINENEWLINE return nameNEWLINENEWLINENEWLINE def _set_name(self, which, name):NEWLINE if not isinstance(name, X509Name):NEWLINE raise TypeError("name must be an X509Name")NEWLINE set_result = which(self._x509, name._name)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_issuer(self):NEWLINE """NEWLINE Create an X509Name object for the issuer of the certificateNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE return self._get_name(_lib.X509_get_issuer_name)NEWLINENEWLINENEWLINE def set_issuer(self, issuer):NEWLINE """NEWLINE Set the issuer of the certificateNEWLINENEWLINE :param issuer: The issuer nameNEWLINE :type issuer: :py:class:`X509Name`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return self._set_name(_lib.X509_set_issuer_name, issuer)NEWLINENEWLINENEWLINE def get_subject(self):NEWLINE """NEWLINE Create an X509Name object for the subject of the certificateNEWLINENEWLINE :return: An X509Name objectNEWLINE """NEWLINE return self._get_name(_lib.X509_get_subject_name)NEWLINENEWLINENEWLINE def set_subject(self, subject):NEWLINE """NEWLINE Set the subject of the certificateNEWLINENEWLINE :param subject: The subject nameNEWLINE :type subject: :py:class:`X509Name`NEWLINE :return: NoneNEWLINE """NEWLINE return self._set_name(_lib.X509_set_subject_name, subject)NEWLINENEWLINENEWLINE def get_extension_count(self):NEWLINE """NEWLINE Get the number of extensions on the certificate.NEWLINENEWLINE :return: The number of extensions as an integer.NEWLINE """NEWLINE return _lib.X509_get_ext_count(self._x509)NEWLINENEWLINENEWLINE def add_extensions(self, extensions):NEWLINE """NEWLINE Add extensions to the certificate.NEWLINENEWLINE :param extensions: a sequence of X509Extension objectsNEWLINE :return: NoneNEWLINE """NEWLINE for ext in extensions:NEWLINE if not isinstance(ext, X509Extension):NEWLINE raise ValueError("One of the elements is not an X509Extension")NEWLINENEWLINE add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)NEWLINE if not add_result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_extension(self, index):NEWLINE """NEWLINE Get a specific extension of the certificate by index.NEWLINENEWLINE :param index: The index of the extension to retrieve.NEWLINE :return: The X509Extension object at the specified index.NEWLINE """NEWLINE ext = X509Extension.__new__(X509Extension)NEWLINE ext._extension = _lib.X509_get_ext(self._x509, index)NEWLINE if ext._extension == _ffi.NULL:NEWLINE raise IndexError("extension index out of bounds")NEWLINENEWLINE extension = _lib.X509_EXTENSION_dup(ext._extension)NEWLINE ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)NEWLINE return extNEWLINENEWLINEX509Type = X509NEWLINENEWLINENEWLINENEWLINEclass X509Store(object):NEWLINE def __init__(self):NEWLINE store = _lib.X509_STORE_new()NEWLINE self._store = _ffi.gc(store, _lib.X509_STORE_free)NEWLINENEWLINENEWLINE def add_cert(self, cert):NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError()NEWLINENEWLINE result = _lib.X509_STORE_add_cert(self._store, cert._x509)NEWLINE if not result:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINEX509StoreType = X509StoreNEWLINENEWLINENEWLINENEWLINEdef load_certificate(type, buffer):NEWLINE """NEWLINE Load a certificate from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINENEWLINE :param buffer: The buffer the certificate is stored inNEWLINE :type buffer: :py:class:`bytes`NEWLINENEWLINE :return: The X509 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE x509 = _lib.d2i_X509_bio(bio, _ffi.NULL);NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if x509 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE cert = X509.__new__(X509)NEWLINE cert._x509 = _ffi.gc(x509, _lib.X509_free)NEWLINE return certNEWLINENEWLINENEWLINEdef dump_certificate(type, cert):NEWLINE """NEWLINE Dump a certificate to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, orNEWLINE FILETYPE_TEXT)NEWLINE :param cert: The certificate to dumpNEWLINE :return: The buffer with the dumped certificate inNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_X509(bio, cert._x509)NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_X509_bio(bio, cert._x509)NEWLINE elif type == FILETYPE_TEXT:NEWLINE result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "NEWLINE "FILETYPE_TEXT")NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef dump_privatekey(type, pkey, cipher=None, passphrase=None):NEWLINE """NEWLINE Dump a private key to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, orNEWLINE FILETYPE_TEXT)NEWLINE :param pkey: The PKey to dumpNEWLINE :param cipher: (optional) if encrypted PEM format, the cipher toNEWLINE useNEWLINE :param passphrase: (optional) if encrypted PEM format, this can be eitherNEWLINE the passphrase to use, or a callback for providing theNEWLINE passphrase.NEWLINE :return: The buffer with the dumped key inNEWLINE :rtype: :py:data:`str`NEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if cipher is not None:NEWLINE if passphrase is None:NEWLINE raise TypeError(NEWLINE "if a value is given for cipher "NEWLINE "one must also be given for passphrase")NEWLINE cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))NEWLINE if cipher_obj == _ffi.NULL:NEWLINE raise ValueError("Invalid cipher name")NEWLINE else:NEWLINE cipher_obj = _ffi.NULLNEWLINENEWLINE helper = _PassphraseHelper(type, passphrase)NEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_PrivateKey(NEWLINE bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,NEWLINE helper.callback, helper.callback_args)NEWLINE helper.raise_if_problem()NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)NEWLINE elif type == FILETYPE_TEXT:NEWLINE rsa = _lib.EVP_PKEY_get1_RSA(pkey._pkey)NEWLINE result_code = _lib.RSA_print(bio, rsa, 0)NEWLINE # TODO RSA_free(rsa)?NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "NEWLINE "FILETYPE_TEXT")NEWLINENEWLINE if result_code == 0:NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef _X509_REVOKED_dup(original):NEWLINE copy = _lib.X509_REVOKED_new()NEWLINE if copy == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE if original.serialNumber != _ffi.NULL:NEWLINE copy.serialNumber = _lib.ASN1_INTEGER_dup(original.serialNumber)NEWLINENEWLINE if original.revocationDate != _ffi.NULL:NEWLINE copy.revocationDate = _lib.M_ASN1_TIME_dup(original.revocationDate)NEWLINENEWLINE if original.extensions != _ffi.NULL:NEWLINE extension_stack = _lib.sk_X509_EXTENSION_new_null()NEWLINE for i in range(_lib.sk_X509_EXTENSION_num(original.extensions)):NEWLINE original_ext = _lib.sk_X509_EXTENSION_value(original.extensions, i)NEWLINE copy_ext = _lib.X509_EXTENSION_dup(original_ext)NEWLINE _lib.sk_X509_EXTENSION_push(extension_stack, copy_ext)NEWLINE copy.extensions = extension_stackNEWLINENEWLINE copy.sequence = original.sequenceNEWLINE return copyNEWLINENEWLINENEWLINENEWLINEclass Revoked(object):NEWLINE # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_NEWLINE # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matchesNEWLINE # OCSP_crl_reason_str. We use the latter, just like the command lineNEWLINE # program.NEWLINE _crl_reasons = [NEWLINE b"unspecified",NEWLINE b"keyCompromise",NEWLINE b"CACompromise",NEWLINE b"affiliationChanged",NEWLINE b"superseded",NEWLINE b"cessationOfOperation",NEWLINE b"certificateHold",NEWLINE # b"removeFromCRL",NEWLINE ]NEWLINENEWLINE def __init__(self):NEWLINE revoked = _lib.X509_REVOKED_new()NEWLINE self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)NEWLINENEWLINENEWLINE def set_serial(self, hex_str):NEWLINE """NEWLINE Set the serial number of a revoked Revoked structureNEWLINENEWLINE :param hex_str: The new serial number.NEWLINE :type hex_str: :py:data:`str`NEWLINE :return: NoneNEWLINE """NEWLINE bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)NEWLINE bignum_ptr = _ffi.new("BIGNUM**")NEWLINE bignum_ptr[0] = bignum_serialNEWLINE bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)NEWLINE if not bn_result:NEWLINE raise ValueError("bad hex string")NEWLINENEWLINE asn1_serial = _ffi.gc(NEWLINE _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),NEWLINE _lib.ASN1_INTEGER_free)NEWLINE _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)NEWLINENEWLINENEWLINE def get_serial(self):NEWLINE """NEWLINE Return the serial number of a Revoked structureNEWLINENEWLINE :return: The serial number as a stringNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE result = _lib.i2a_ASN1_INTEGER(bio, self._revoked.serialNumber)NEWLINE if result < 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINE def _delete_reason(self):NEWLINE stack = self._revoked.extensionsNEWLINE for i in range(_lib.sk_X509_EXTENSION_num(stack)):NEWLINE ext = _lib.sk_X509_EXTENSION_value(stack, i)NEWLINE if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:NEWLINE _lib.X509_EXTENSION_free(ext)NEWLINE _lib.sk_X509_EXTENSION_delete(stack, i)NEWLINE breakNEWLINENEWLINENEWLINE def set_reason(self, reason):NEWLINE """NEWLINE Set the reason of a Revoked object.NEWLINENEWLINE If :py:data:`reason` is :py:data:`None`, delete the reason instead.NEWLINENEWLINE :param reason: The reason string.NEWLINE :type reason: :py:class:`str` or :py:class:`NoneType`NEWLINE :return: NoneNEWLINE """NEWLINE if reason is None:NEWLINE self._delete_reason()NEWLINE elif not isinstance(reason, bytes):NEWLINE raise TypeError("reason must be None or a byte string")NEWLINE else:NEWLINE reason = reason.lower().replace(b' ', b'')NEWLINE reason_code = [r.lower() for r in self._crl_reasons].index(reason)NEWLINENEWLINE new_reason_ext = _lib.ASN1_ENUMERATED_new()NEWLINE if new_reason_ext == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)NEWLINENEWLINE set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)NEWLINE if set_result == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE self._delete_reason()NEWLINE add_result = _lib.X509_REVOKED_add1_ext_i2d(NEWLINE self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)NEWLINENEWLINE if not add_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def get_reason(self):NEWLINE """NEWLINE Return the reason of a Revoked object.NEWLINENEWLINE :return: The reason as a stringNEWLINE """NEWLINE extensions = self._revoked.extensionsNEWLINE for i in range(_lib.sk_X509_EXTENSION_num(extensions)):NEWLINE ext = _lib.sk_X509_EXTENSION_value(extensions, i)NEWLINE if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:NEWLINE bio = _new_mem_buf()NEWLINENEWLINE print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)NEWLINE if not print_result:NEWLINE print_result = _lib.M_ASN1_OCTET_STRING_print(bio, ext.value)NEWLINE if print_result == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINE def all_reasons(self):NEWLINE """NEWLINE Return a list of all the supported reason strings.NEWLINENEWLINE :return: A list of reason strings.NEWLINE """NEWLINE return self._crl_reasons[:]NEWLINENEWLINENEWLINE def set_rev_date(self, when):NEWLINE """NEWLINE Set the revocation timestampNEWLINENEWLINE :param when: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINENEWLINE :return: NoneNEWLINE """NEWLINE return _set_asn1_time(self._revoked.revocationDate, when)NEWLINENEWLINENEWLINE def get_rev_date(self):NEWLINE """NEWLINE Retrieve the revocation dateNEWLINENEWLINE :return: A string giving the timestamp, in the format:NEWLINENEWLINE YYYYMMDDhhmmssZNEWLINE YYYYMMDDhhmmss+hhmmNEWLINE YYYYMMDDhhmmss-hhmmNEWLINE """NEWLINE return _get_asn1_time(self._revoked.revocationDate)NEWLINENEWLINENEWLINENEWLINEclass CRL(object):NEWLINE def __init__(self):NEWLINE """NEWLINE Create a new empty CRL object.NEWLINE """NEWLINE crl = _lib.X509_CRL_new()NEWLINE self._crl = _ffi.gc(crl, _lib.X509_CRL_free)NEWLINENEWLINENEWLINE def get_revoked(self):NEWLINE """NEWLINE Return revoked portion of the CRL structure (by value not reference).NEWLINENEWLINE :return: A tuple of Revoked objects.NEWLINE """NEWLINE results = []NEWLINE revoked_stack = self._crl.crl.revokedNEWLINE for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):NEWLINE revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)NEWLINE revoked_copy = _X509_REVOKED_dup(revoked)NEWLINE pyrev = Revoked.__new__(Revoked)NEWLINE pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)NEWLINE results.append(pyrev)NEWLINE if results:NEWLINE return tuple(results)NEWLINENEWLINENEWLINE def add_revoked(self, revoked):NEWLINE """NEWLINE Add a revoked (by value not reference) to the CRL structureNEWLINENEWLINE :param revoked: The new revoked.NEWLINE :type revoked: :class:`X509`NEWLINENEWLINE :return: NoneNEWLINE """NEWLINE copy = _X509_REVOKED_dup(revoked._revoked)NEWLINE if copy == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)NEWLINE if add_result == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def export(self, cert, key, type=FILETYPE_PEM, days=100):NEWLINE """NEWLINE export a CRL as a stringNEWLINENEWLINE :param cert: Used to sign CRL.NEWLINE :type cert: :class:`X509`NEWLINENEWLINE :param key: Used to sign CRL.NEWLINE :type key: :class:`PKey`NEWLINENEWLINE :param type: The export format, either :py:data:`FILETYPE_PEM`, :py:data:`FILETYPE_ASN1`, or :py:data:`FILETYPE_TEXT`.NEWLINENEWLINE :param days: The number of days until the next update of this CRL.NEWLINE :type days: :py:data:`int`NEWLINENEWLINE :return: :py:data:`str`NEWLINE """NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("cert must be an X509 instance")NEWLINE if not isinstance(key, PKey):NEWLINE raise TypeError("key must be a PKey instance")NEWLINE if not isinstance(type, int):NEWLINE raise TypeError("type must be an integer")NEWLINENEWLINE bio = _lib.BIO_new(_lib.BIO_s_mem())NEWLINE if bio == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE # A scratch time object to give different values to different CRL fieldsNEWLINE sometime = _lib.ASN1_TIME_new()NEWLINE if sometime == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE _lib.X509_gmtime_adj(sometime, 0)NEWLINE _lib.X509_CRL_set_lastUpdate(self._crl, sometime)NEWLINENEWLINE _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)NEWLINE _lib.X509_CRL_set_nextUpdate(self._crl, sometime)NEWLINENEWLINE _lib.X509_CRL_set_issuer_name(self._crl, _lib.X509_get_subject_name(cert._x509))NEWLINENEWLINE sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, _lib.EVP_md5())NEWLINE if not sign_result:NEWLINE _raise_current_error()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE ret = _lib.PEM_write_bio_X509_CRL(bio, self._crl)NEWLINE elif type == FILETYPE_ASN1:NEWLINE ret = _lib.i2d_X509_CRL_bio(bio, self._crl)NEWLINE elif type == FILETYPE_TEXT:NEWLINE ret = _lib.X509_CRL_print(bio, self._crl)NEWLINE else:NEWLINE raise ValueError(NEWLINE "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")NEWLINENEWLINE if not ret:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINECRLType = CRLNEWLINENEWLINENEWLINENEWLINEclass PKCS7(object):NEWLINE def type_is_signed(self):NEWLINE """NEWLINE Check if this NID_pkcs7_signed objectNEWLINENEWLINE :return: True if the PKCS7 is of type signedNEWLINE """NEWLINE if _lib.PKCS7_type_is_signed(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_enveloped(self):NEWLINE """NEWLINE Check if this NID_pkcs7_enveloped objectNEWLINENEWLINE :returns: True if the PKCS7 is of type envelopedNEWLINE """NEWLINE if _lib.PKCS7_type_is_enveloped(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_signedAndEnveloped(self):NEWLINE """NEWLINE Check if this NID_pkcs7_signedAndEnveloped objectNEWLINENEWLINE :returns: True if the PKCS7 is of type signedAndEnvelopedNEWLINE """NEWLINE if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def type_is_data(self):NEWLINE """NEWLINE Check if this NID_pkcs7_data objectNEWLINENEWLINE :return: True if the PKCS7 is of type dataNEWLINE """NEWLINE if _lib.PKCS7_type_is_data(self._pkcs7):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def get_type_name(self):NEWLINE """NEWLINE Returns the type name of the PKCS7 structureNEWLINENEWLINE :return: A string with the typenameNEWLINE """NEWLINE nid = _lib.OBJ_obj2nid(self._pkcs7.type)NEWLINE string_type = _lib.OBJ_nid2sn(nid)NEWLINE return _ffi.string(string_type)NEWLINENEWLINEPKCS7Type = PKCS7NEWLINENEWLINENEWLINENEWLINEclass PKCS12(object):NEWLINE def __init__(self):NEWLINE self._pkey = NoneNEWLINE self._cert = NoneNEWLINE self._cacerts = NoneNEWLINE self._friendlyname = NoneNEWLINENEWLINENEWLINE def get_certificate(self):NEWLINE """NEWLINE Return certificate portion of the PKCS12 structureNEWLINENEWLINE :return: X509 object containing the certificateNEWLINE """NEWLINE return self._certNEWLINENEWLINENEWLINE def set_certificate(self, cert):NEWLINE """NEWLINE Replace the certificate portion of the PKCS12 structureNEWLINENEWLINE :param cert: The new certificate.NEWLINE :type cert: :py:class:`X509` or :py:data:`None`NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("cert must be an X509 instance")NEWLINE self._cert = certNEWLINENEWLINENEWLINE def get_privatekey(self):NEWLINE """NEWLINE Return private key portion of the PKCS12 structureNEWLINENEWLINE :returns: PKey object containing the private keyNEWLINE """NEWLINE return self._pkeyNEWLINENEWLINENEWLINE def set_privatekey(self, pkey):NEWLINE """NEWLINE Replace or set the certificate portion of the PKCS12 structureNEWLINENEWLINE :param pkey: The new private key.NEWLINE :type pkey: :py:class:`PKey`NEWLINE :return: NoneNEWLINE """NEWLINE if not isinstance(pkey, PKey):NEWLINE raise TypeError("pkey must be a PKey instance")NEWLINE self._pkey = pkeyNEWLINENEWLINENEWLINE def get_ca_certificates(self):NEWLINE """NEWLINE Return CA certificates within of the PKCS12 objectNEWLINENEWLINE :return: A newly created tuple containing the CA certificates in the chain,NEWLINE if any are present, or None if no CA certificates are present.NEWLINE """NEWLINE if self._cacerts is not None:NEWLINE return tuple(self._cacerts)NEWLINENEWLINENEWLINE def set_ca_certificates(self, cacerts):NEWLINE """NEWLINE Replace or set the CA certificates withing the PKCS12 object.NEWLINENEWLINE :param cacerts: The new CA certificates.NEWLINE :type cacerts: :py:data:`None` or an iterable of :py:class:`X509`NEWLINE :return: NoneNEWLINE """NEWLINE if cacerts is None:NEWLINE self._cacerts = NoneNEWLINE else:NEWLINE cacerts = list(cacerts)NEWLINE for cert in cacerts:NEWLINE if not isinstance(cert, X509):NEWLINE raise TypeError("iterable must only contain X509 instances")NEWLINE self._cacerts = cacertsNEWLINENEWLINENEWLINE def set_friendlyname(self, name):NEWLINE """NEWLINE Replace or set the certificate portion of the PKCS12 structureNEWLINENEWLINE :param name: The new friendly name.NEWLINE :type name: :py:class:`bytes`NEWLINE :return: NoneNEWLINE """NEWLINE if name is None:NEWLINE self._friendlyname = NoneNEWLINE elif not isinstance(name, bytes):NEWLINE raise TypeError("name must be a byte string or None (not %r)" % (name,))NEWLINE self._friendlyname = nameNEWLINENEWLINENEWLINE def get_friendlyname(self):NEWLINE """NEWLINE Return friendly name portion of the PKCS12 structureNEWLINENEWLINE :returns: String containing the friendlynameNEWLINE """NEWLINE return self._friendlynameNEWLINENEWLINENEWLINE def export(self, passphrase=None, iter=2048, maciter=1):NEWLINE """NEWLINE Dump a PKCS12 object as a string. See also "man PKCS12_create".NEWLINENEWLINE :param passphrase: used to encrypt the PKCS12NEWLINE :type passphrase: :py:data:`bytes`NEWLINENEWLINE :param iter: How many times to repeat the encryptionNEWLINE :type iter: :py:data:`int`NEWLINENEWLINE :param maciter: How many times to repeat the MACNEWLINE :type maciter: :py:data:`int`NEWLINENEWLINE :return: The string containing the PKCS12NEWLINE """NEWLINE if self._cacerts is None:NEWLINE cacerts = _ffi.NULLNEWLINE else:NEWLINE cacerts = _lib.sk_X509_new_null()NEWLINE cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)NEWLINE for cert in self._cacerts:NEWLINE _lib.sk_X509_push(cacerts, cert._x509)NEWLINENEWLINE if passphrase is None:NEWLINE passphrase = _ffi.NULLNEWLINENEWLINE friendlyname = self._friendlynameNEWLINE if friendlyname is None:NEWLINE friendlyname = _ffi.NULLNEWLINENEWLINE if self._pkey is None:NEWLINE pkey = _ffi.NULLNEWLINE else:NEWLINE pkey = self._pkey._pkeyNEWLINENEWLINE if self._cert is None:NEWLINE cert = _ffi.NULLNEWLINE else:NEWLINE cert = self._cert._x509NEWLINENEWLINE pkcs12 = _lib.PKCS12_create(NEWLINE passphrase, friendlyname, pkey, cert, cacerts,NEWLINE _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,NEWLINE _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,NEWLINE iter, maciter, 0)NEWLINE if pkcs12 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)NEWLINENEWLINE bio = _new_mem_buf()NEWLINE _lib.i2d_PKCS12_bio(bio, pkcs12)NEWLINE return _bio_to_string(bio)NEWLINENEWLINEPKCS12Type = PKCS12NEWLINENEWLINENEWLINENEWLINEclass NetscapeSPKI(object):NEWLINE def __init__(self):NEWLINE spki = _lib.NETSCAPE_SPKI_new()NEWLINE self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)NEWLINENEWLINENEWLINE def sign(self, pkey, digest):NEWLINE """NEWLINE Sign the certificate request using the supplied key and digestNEWLINENEWLINE :param pkey: The key to sign withNEWLINE :param digest: The message digest to useNEWLINE :return: NoneNEWLINE """NEWLINE if pkey._only_public:NEWLINE raise ValueError("Key has only public part")NEWLINENEWLINE if not pkey._initialized:NEWLINE raise ValueError("Key is uninitialized")NEWLINENEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE sign_result = _lib.NETSCAPE_SPKI_sign(self._spki, pkey._pkey, digest_obj)NEWLINE if not sign_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINENEWLINE def verify(self, key):NEWLINE """NEWLINE Verifies a certificate request using the supplied public keyNEWLINENEWLINE :param key: a public keyNEWLINE :return: True if the signature is correct.NEWLINE :raise OpenSSL.crypto.Error: If the signature is invalid or there is aNEWLINE problem verifying the signature.NEWLINE """NEWLINE answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)NEWLINE if answer <= 0:NEWLINE _raise_current_error()NEWLINE return TrueNEWLINENEWLINENEWLINE def b64_encode(self):NEWLINE """NEWLINE Generate a base64 encoded string from an SPKINEWLINENEWLINE :return: The base64 encoded stringNEWLINE """NEWLINE encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)NEWLINE result = _ffi.string(encoded)NEWLINE _lib.CRYPTO_free(encoded)NEWLINE return resultNEWLINENEWLINENEWLINE def get_pubkey(self):NEWLINE """NEWLINE Get the public key of the certificateNEWLINENEWLINE :return: The public keyNEWLINE """NEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)NEWLINE if pkey._pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)NEWLINE pkey._only_public = TrueNEWLINE return pkeyNEWLINENEWLINENEWLINE def set_pubkey(self, pkey):NEWLINE """NEWLINE Set the public key of the certificateNEWLINENEWLINE :param pkey: The public keyNEWLINE :return: NoneNEWLINE """NEWLINE set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)NEWLINE if not set_result:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENetscapeSPKIType = NetscapeSPKINEWLINENEWLINENEWLINEclass _PassphraseHelper(object):NEWLINE def __init__(self, type, passphrase, more_args=False, truncate=False):NEWLINE if type != FILETYPE_PEM and passphrase is not None:NEWLINE raise ValueError("only FILETYPE_PEM key format supports encryption")NEWLINE self._passphrase = passphraseNEWLINE self._more_args = more_argsNEWLINE self._truncate = truncateNEWLINE self._problems = []NEWLINENEWLINENEWLINE @propertyNEWLINE def callback(self):NEWLINE if self._passphrase is None:NEWLINE return _ffi.NULLNEWLINE elif isinstance(self._passphrase, bytes):NEWLINE return _ffi.NULLNEWLINE elif callable(self._passphrase):NEWLINE return _ffi.callback("pem_password_cb", self._read_passphrase)NEWLINE else:NEWLINE raise TypeError("Last argument must be string or callable")NEWLINENEWLINENEWLINE @propertyNEWLINE def callback_args(self):NEWLINE if self._passphrase is None:NEWLINE return _ffi.NULLNEWLINE elif isinstance(self._passphrase, bytes):NEWLINE return self._passphraseNEWLINE elif callable(self._passphrase):NEWLINE return _ffi.NULLNEWLINE else:NEWLINE raise TypeError("Last argument must be string or callable")NEWLINENEWLINENEWLINE def raise_if_problem(self, exceptionType=Error):NEWLINE try:NEWLINE _exception_from_error_queue(exceptionType)NEWLINE except exceptionType as e:NEWLINE from_queue = eNEWLINE if self._problems:NEWLINE raise self._problems[0]NEWLINE return from_queueNEWLINENEWLINENEWLINE def _read_passphrase(self, buf, size, rwflag, userdata):NEWLINE try:NEWLINE if self._more_args:NEWLINE result = self._passphrase(size, rwflag, userdata)NEWLINE else:NEWLINE result = self._passphrase(rwflag)NEWLINE if not isinstance(result, bytes):NEWLINE raise ValueError("String expected")NEWLINE if len(result) > size:NEWLINE if self._truncate:NEWLINE result = result[:size]NEWLINE else:NEWLINE raise ValueError("passphrase returned by callback is too long")NEWLINE for i in range(len(result)):NEWLINE buf[i] = result[i:i + 1]NEWLINE return len(result)NEWLINE except Exception as e:NEWLINE self._problems.append(e)NEWLINE return 0NEWLINENEWLINENEWLINENEWLINEdef load_privatekey(type, buffer, passphrase=None):NEWLINE """NEWLINE Load a private key from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the key is stored inNEWLINE :param passphrase: (optional) if encrypted PEM format, this can beNEWLINE either the passphrase to use, or a callback forNEWLINE providing the passphrase.NEWLINENEWLINE :return: The PKey objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE helper = _PassphraseHelper(type, passphrase)NEWLINE if type == FILETYPE_PEM:NEWLINE evp_pkey = _lib.PEM_read_bio_PrivateKey(NEWLINE bio, _ffi.NULL, helper.callback, helper.callback_args)NEWLINE helper.raise_if_problem()NEWLINE elif type == FILETYPE_ASN1:NEWLINE evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if evp_pkey == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE pkey = PKey.__new__(PKey)NEWLINE pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)NEWLINE return pkeyNEWLINENEWLINENEWLINENEWLINEdef dump_certificate_request(type, req):NEWLINE """NEWLINE Dump a certificate request to a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param req: The certificate request to dumpNEWLINE :return: The buffer with the dumped certificate request inNEWLINE """NEWLINE bio = _new_mem_buf()NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)NEWLINE elif type == FILETYPE_ASN1:NEWLINE result_code = _lib.i2d_X509_REQ_bio(bio, req._req)NEWLINE elif type == FILETYPE_TEXT:NEWLINE result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")NEWLINENEWLINE if result_code == 0:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _bio_to_string(bio)NEWLINENEWLINENEWLINENEWLINEdef load_certificate_request(type, buffer):NEWLINE """NEWLINE Load a certificate request from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the certificate request is stored inNEWLINE :return: The X509Req objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if req == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE x509req = X509Req.__new__(X509Req)NEWLINE x509req._req = _ffi.gc(req, _lib.X509_REQ_free)NEWLINE return x509reqNEWLINENEWLINENEWLINENEWLINEdef sign(pkey, data, digest):NEWLINE """NEWLINE Sign data with a digestNEWLINENEWLINE :param pkey: Pkey to sign withNEWLINE :param data: data to be signedNEWLINE :param digest: message digest to useNEWLINE :return: signatureNEWLINE """NEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE md_ctx = _ffi.new("EVP_MD_CTX*")NEWLINE md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)NEWLINENEWLINE _lib.EVP_SignInit(md_ctx, digest_obj)NEWLINE _lib.EVP_SignUpdate(md_ctx, data, len(data))NEWLINENEWLINE signature_buffer = _ffi.new("unsigned char[]", 512)NEWLINE signature_length = _ffi.new("unsigned int*")NEWLINE signature_length[0] = len(signature_buffer)NEWLINE final_result = _lib.EVP_SignFinal(NEWLINE md_ctx, signature_buffer, signature_length, pkey._pkey)NEWLINENEWLINE if final_result != 1:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINENEWLINE return _ffi.buffer(signature_buffer, signature_length[0])[:]NEWLINENEWLINENEWLINENEWLINEdef verify(cert, signature, data, digest):NEWLINE """NEWLINE Verify a signatureNEWLINENEWLINE :param cert: signing certificate (X509 object)NEWLINE :param signature: signature returned by sign functionNEWLINE :param data: data to be verifiedNEWLINE :param digest: message digest to useNEWLINE :return: None if the signature is correct, raise exception otherwiseNEWLINE """NEWLINE digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))NEWLINE if digest_obj == _ffi.NULL:NEWLINE raise ValueError("No such digest method")NEWLINENEWLINE pkey = _lib.X509_get_pubkey(cert._x509)NEWLINE if pkey == _ffi.NULL:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)NEWLINENEWLINE md_ctx = _ffi.new("EVP_MD_CTX*")NEWLINE md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)NEWLINENEWLINE _lib.EVP_VerifyInit(md_ctx, digest_obj)NEWLINE _lib.EVP_VerifyUpdate(md_ctx, data, len(data))NEWLINE verify_result = _lib.EVP_VerifyFinal(md_ctx, signature, len(signature), pkey)NEWLINENEWLINE if verify_result != 1:NEWLINE _raise_current_error()NEWLINENEWLINENEWLINENEWLINEdef load_crl(type, buffer):NEWLINE """NEWLINE Load a certificate revocation list from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)NEWLINE :param buffer: The buffer the CRL is stored inNEWLINENEWLINE :return: The PKey objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)NEWLINE else:NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if crl == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE result = CRL.__new__(CRL)NEWLINE result._crl = crlNEWLINE return resultNEWLINENEWLINENEWLINENEWLINEdef load_pkcs7_data(type, buffer):NEWLINE """NEWLINE Load pkcs7 data from a bufferNEWLINENEWLINE :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)NEWLINE :param buffer: The buffer with the pkcs7 data.NEWLINE :return: The PKCS7 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE if type == FILETYPE_PEM:NEWLINE pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)NEWLINE elif type == FILETYPE_ASN1:NEWLINE passNEWLINE else:NEWLINE # TODO: This is untested.NEWLINE _raise_current_error()NEWLINE raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")NEWLINENEWLINE if pkcs7 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINENEWLINE pypkcs7 = PKCS7.__new__(PKCS7)NEWLINE pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)NEWLINE return pypkcs7NEWLINENEWLINENEWLINENEWLINEdef load_pkcs12(buffer, passphrase):NEWLINE """NEWLINE Load a PKCS12 object from a bufferNEWLINENEWLINE :param buffer: The buffer the certificate is stored inNEWLINE :param passphrase: (Optional) The password to decrypt the PKCS12 lumpNEWLINE :returns: The PKCS12 objectNEWLINE """NEWLINE if isinstance(buffer, _text_type):NEWLINE buffer = buffer.encode("ascii")NEWLINENEWLINE bio = _new_mem_buf(buffer)NEWLINENEWLINE p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)NEWLINE if p12 == _ffi.NULL:NEWLINE _raise_current_error()NEWLINE p12 = _ffi.gc(p12, _lib.PKCS12_free)NEWLINENEWLINE pkey = _ffi.new("EVP_PKEY**")NEWLINE cert = _ffi.new("X509**")NEWLINE cacerts = _ffi.new("Cryptography_STACK_OF_X509**")NEWLINENEWLINE parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)NEWLINE if not parse_result:NEWLINE _raise_current_error()NEWLINENEWLINE cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)NEWLINENEWLINE # openssl 1.0.0 sometimes leaves an X509_check_private_key error in theNEWLINE # queue for no particular reason. This error isn't interesting to anyoneNEWLINE # outside this function. It's not even interesting to us. Get rid of it.NEWLINE try:NEWLINE _raise_current_error()NEWLINE except Error:NEWLINE passNEWLINENEWLINE if pkey[0] == _ffi.NULL:NEWLINE pykey = NoneNEWLINE else:NEWLINE pykey = PKey.__new__(PKey)NEWLINE pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)NEWLINENEWLINE if cert[0] == _ffi.NULL:NEWLINE pycert = NoneNEWLINE friendlyname = NoneNEWLINE else:NEWLINE pycert = X509.__new__(X509)NEWLINE pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)NEWLINENEWLINE friendlyname_length = _ffi.new("int*")NEWLINE friendlyname_buffer = _lib.X509_alias_get0(cert[0], friendlyname_length)NEWLINE friendlyname = _ffi.buffer(friendlyname_buffer, friendlyname_length[0])[:]NEWLINE if friendlyname_buffer == _ffi.NULL:NEWLINE friendlyname = NoneNEWLINENEWLINE pycacerts = []NEWLINE for i in range(_lib.sk_X509_num(cacerts)):NEWLINE pycacert = X509.__new__(X509)NEWLINE pycacert._x509 = _lib.sk_X509_value(cacerts, i)NEWLINE pycacerts.append(pycacert)NEWLINE if not pycacerts:NEWLINE pycacerts = NoneNEWLINENEWLINE pkcs12 = PKCS12.__new__(PKCS12)NEWLINE pkcs12._pkey = pykeyNEWLINE pkcs12._cert = pycertNEWLINE pkcs12._cacerts = pycacertsNEWLINE pkcs12._friendlyname = friendlynameNEWLINE return pkcs12NEWLINENEWLINENEWLINEdef _initialize_openssl_threads(get_ident, Lock):NEWLINE import _sslNEWLINE returnNEWLINENEWLINE locks = list(Lock() for n in range(_lib.CRYPTO_num_locks()))NEWLINENEWLINE def locking_function(mode, index, filename, line):NEWLINE if mode & _lib.CRYPTO_LOCK:NEWLINE locks[index].acquire()NEWLINE else:NEWLINE locks[index].release()NEWLINENEWLINE _lib.CRYPTO_set_id_callback(NEWLINE _ffi.callback("unsigned long (*)(void)", get_ident))NEWLINENEWLINE _lib.CRYPTO_set_locking_callback(NEWLINE _ffi.callback(NEWLINE "void (*)(int, int, const char*, int)", locking_function))NEWLINENEWLINENEWLINEtry:NEWLINE from thread import get_identNEWLINE from threading import LockNEWLINEexcept ImportError:NEWLINE passNEWLINEelse:NEWLINE _initialize_openssl_threads(get_ident, Lock)NEWLINE del get_ident, LockNEWLINENEWLINE# There are no direct unit tests for this initialization. It is testedNEWLINE# indirectly since it is necessary for functions like dump_privatekey whenNEWLINE# using encryption.NEWLINE#NEWLINE# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphraseNEWLINE# and some other similar tests may fail without this (though they may not ifNEWLINE# the Python runtime has already done some initialization of the underlyingNEWLINE# OpenSSL library (and is linked against the same one that cryptography isNEWLINE# using)).NEWLINE_lib.OpenSSL_add_all_algorithms()NEWLINENEWLINE# This is similar but exercised mainly by exception_from_error_queue. It callsNEWLINE# both ERR_load_crypto_strings() and ERR_load_SSL_strings().NEWLINE_lib.SSL_load_error_strings()NEWLINE |
from game.combat.effects.moveeffect.basemoveeffect import BaseMoveEffectNEWLINEfrom game.combat.effects.partialeffect.applystatuseffect import ApplyStatusNEWLINEfrom game.combat.effects import statuseffectNEWLINENEWLINENEWLINEclass Confusion(BaseMoveEffect):NEWLINE def after_action(self):NEWLINE if self.scene.board.random_roll(self.move.chance):NEWLINE ApplyStatus(self.scene, statuseffect.CONFUSION, self.move.user, self.move.target).apply()NEWLINE return True, False, FalseNEWLINE |
NEWLINE# This file helps to compute a version number in source trees obtained fromNEWLINE# git-archive tarball (such as those provided by githubs download-from-tagNEWLINE# feature). Distribution tarballs (built by setup.py sdist) and buildNEWLINE# directories (produced by setup.py build) will contain a much shorter fileNEWLINE# that just contains the computed version number.NEWLINENEWLINE# This file is released into the public domain. Generated byNEWLINE# versioneer-0.18 (https://github.com/warner/python-versioneer)NEWLINENEWLINE"""Git implementation of _version.py."""NEWLINENEWLINEimport errnoNEWLINEimport osNEWLINEimport reNEWLINEimport subprocessNEWLINEimport sysNEWLINENEWLINENEWLINEdef get_keywords():NEWLINE """Get the keywords needed to look up the version information."""NEWLINE # these strings will be replaced by git during git-archive.NEWLINE # setup.py/versioneer.py will grep for the variable names, so they mustNEWLINE # each be defined on a line of their own. _version.py will just callNEWLINE # get_keywords().NEWLINE git_refnames = "$Format:%d$"NEWLINE git_full = "$Format:%H$"NEWLINE git_date = "$Format:%ci$"NEWLINE keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}NEWLINE return keywordsNEWLINENEWLINENEWLINEclass VersioneerConfig:NEWLINE """Container for Versioneer configuration parameters."""NEWLINENEWLINENEWLINEdef get_config():NEWLINE """Create, populate and return the VersioneerConfig() object."""NEWLINE # these strings are filled in when 'setup.py versioneer' createsNEWLINE # _version.pyNEWLINE cfg = VersioneerConfig()NEWLINE cfg.VCS = "git"NEWLINE cfg.style = ""NEWLINE cfg.tag_prefix = ""NEWLINE cfg.parentdir_prefix = "magic-wormhole-mailbox-server"NEWLINE cfg.versionfile_source = "src/wormhole_mailbox_server/_version.py"NEWLINE cfg.verbose = FalseNEWLINE return cfgNEWLINENEWLINENEWLINEclass NotThisMethod(Exception):NEWLINE """Exception raised if a method is not valid for the current scenario."""NEWLINENEWLINENEWLINELONG_VERSION_PY = {}NEWLINEHANDLERS = {}NEWLINENEWLINENEWLINEdef register_vcs_handler(vcs, method): # decoratorNEWLINE """Decorator to mark a method as the handler for a particular VCS."""NEWLINE def decorate(f):NEWLINE """Store f in HANDLERS[vcs][method]."""NEWLINE if vcs not in HANDLERS:NEWLINE HANDLERS[vcs] = {}NEWLINE HANDLERS[vcs][method] = fNEWLINE return fNEWLINE return decorateNEWLINENEWLINENEWLINEdef run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,NEWLINE env=None):NEWLINE """Call the given command(s)."""NEWLINE assert isinstance(commands, list)NEWLINE p = NoneNEWLINE for c in commands:NEWLINE try:NEWLINE dispcmd = str([c] + args)NEWLINE # remember shell=False, so use git.cmd on windows, not just gitNEWLINE p = subprocess.Popen([c] + args, cwd=cwd, env=env,NEWLINE stdout=subprocess.PIPE,NEWLINE stderr=(subprocess.PIPE if hide_stderrNEWLINE else None))NEWLINE breakNEWLINE except EnvironmentError:NEWLINE e = sys.exc_info()[1]NEWLINE if e.errno == errno.ENOENT:NEWLINE continueNEWLINE if verbose:NEWLINE print("unable to run %s" % dispcmd)NEWLINE print(e)NEWLINE return None, NoneNEWLINE else:NEWLINE if verbose:NEWLINE print("unable to find command, tried %s" % (commands,))NEWLINE return None, NoneNEWLINE stdout = p.communicate()[0].strip()NEWLINE if sys.version_info[0] >= 3:NEWLINE stdout = stdout.decode()NEWLINE if p.returncode != 0:NEWLINE if verbose:NEWLINE print("unable to run %s (error)" % dispcmd)NEWLINE print("stdout was %s" % stdout)NEWLINE return None, p.returncodeNEWLINE return stdout, p.returncodeNEWLINENEWLINENEWLINEdef versions_from_parentdir(parentdir_prefix, root, verbose):NEWLINE """Try to determine the version from the parent directory name.NEWLINENEWLINE Source tarballs conventionally unpack into a directory that includes bothNEWLINE the project name and a version string. We will also support searching upNEWLINE two directory levels for an appropriately named parent directoryNEWLINE """NEWLINE rootdirs = []NEWLINENEWLINE for i in range(3):NEWLINE dirname = os.path.basename(root)NEWLINE if dirname.startswith(parentdir_prefix):NEWLINE return {"version": dirname[len(parentdir_prefix):],NEWLINE "full-revisionid": None,NEWLINE "dirty": False, "error": None, "date": None}NEWLINE else:NEWLINE rootdirs.append(root)NEWLINE root = os.path.dirname(root) # up a levelNEWLINENEWLINE if verbose:NEWLINE print("Tried directories %s but none started with prefix %s" %NEWLINE (str(rootdirs), parentdir_prefix))NEWLINE raise NotThisMethod("rootdir doesn't start with parentdir_prefix")NEWLINENEWLINENEWLINE@register_vcs_handler("git", "get_keywords")NEWLINEdef git_get_keywords(versionfile_abs):NEWLINE """Extract version information from the given file."""NEWLINE # the code embedded in _version.py can just fetch the value of theseNEWLINE # keywords. When used from setup.py, we don't want to import _version.py,NEWLINE # so we do it with a regexp instead. This function is not used fromNEWLINE # _version.py.NEWLINE keywords = {}NEWLINE try:NEWLINE f = open(versionfile_abs, "r")NEWLINE for line in f.readlines():NEWLINE if line.strip().startswith("git_refnames ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["refnames"] = mo.group(1)NEWLINE if line.strip().startswith("git_full ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["full"] = mo.group(1)NEWLINE if line.strip().startswith("git_date ="):NEWLINE mo = re.search(r'=\s*"(.*)"', line)NEWLINE if mo:NEWLINE keywords["date"] = mo.group(1)NEWLINE f.close()NEWLINE except EnvironmentError:NEWLINE passNEWLINE return keywordsNEWLINENEWLINENEWLINE@register_vcs_handler("git", "keywords")NEWLINEdef git_versions_from_keywords(keywords, tag_prefix, verbose):NEWLINE """Get version information from git keywords."""NEWLINE if not keywords:NEWLINE raise NotThisMethod("no keywords at all, weird")NEWLINE date = keywords.get("date")NEWLINE if date is not None:NEWLINE # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliantNEWLINE # datestamp. However we prefer "%ci" (which expands to an "ISO-8601NEWLINE # -like" string, which we must then edit to make compliant), becauseNEWLINE # it's been around since git-1.5.3, and it's too difficult toNEWLINE # discover which version we're using, or to work around using anNEWLINE # older one.NEWLINE date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)NEWLINE refnames = keywords["refnames"].strip()NEWLINE if refnames.startswith("$Format"):NEWLINE if verbose:NEWLINE print("keywords are unexpanded, not using")NEWLINE raise NotThisMethod("unexpanded keywords, not a git-archive tarball")NEWLINE refs = set([r.strip() for r in refnames.strip("()").split(",")])NEWLINE # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead ofNEWLINE # just "foo-1.0". If we see a "tag: " prefix, prefer those.NEWLINE TAG = "tag: "NEWLINE tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])NEWLINE if not tags:NEWLINE # Either we're using git < 1.8.3, or there really are no tags. We useNEWLINE # a heuristic: assume all version tags have a digit. The old git %dNEWLINE # expansion behaves like git log --decorate=short and strips out theNEWLINE # refs/heads/ and refs/tags/ prefixes that would let us distinguishNEWLINE # between branches and tags. By ignoring refnames without digits, weNEWLINE # filter out many common branch names like "release" andNEWLINE # "stabilization", as well as "HEAD" and "master".NEWLINE tags = set([r for r in refs if re.search(r'\d', r)])NEWLINE if verbose:NEWLINE print("discarding '%s', no digits" % ",".join(refs - tags))NEWLINE if verbose:NEWLINE print("likely tags: %s" % ",".join(sorted(tags)))NEWLINE for ref in sorted(tags):NEWLINE # sorting will prefer e.g. "2.0" over "2.0rc1"NEWLINE if ref.startswith(tag_prefix):NEWLINE r = ref[len(tag_prefix):]NEWLINE if verbose:NEWLINE print("picking %s" % r)NEWLINE return {"version": r,NEWLINE "full-revisionid": keywords["full"].strip(),NEWLINE "dirty": False, "error": None,NEWLINE "date": date}NEWLINE # no suitable tags, so version is "0+unknown", but full hex is still thereNEWLINE if verbose:NEWLINE print("no suitable tags, using unknown + full revision id")NEWLINE return {"version": "0+unknown",NEWLINE "full-revisionid": keywords["full"].strip(),NEWLINE "dirty": False, "error": "no suitable tags", "date": None}NEWLINENEWLINENEWLINE@register_vcs_handler("git", "pieces_from_vcs")NEWLINEdef git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):NEWLINE """Get version from 'git describe' in the root of the source tree.NEWLINENEWLINE This only gets called if the git-archive 'subst' keywords were *not*NEWLINE expanded, and _version.py hasn't already been rewritten with a shortNEWLINE version string, meaning we're inside a checked out source tree.NEWLINE """NEWLINE GITS = ["git"]NEWLINE if sys.platform == "win32":NEWLINE GITS = ["git.cmd", "git.exe"]NEWLINENEWLINE out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,NEWLINE hide_stderr=True)NEWLINE if rc != 0:NEWLINE if verbose:NEWLINE print("Directory %s not under git control" % root)NEWLINE raise NotThisMethod("'git rev-parse --git-dir' returned error")NEWLINENEWLINE # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]NEWLINE # if there isn't one, this yields HEX[-dirty] (no NUM)NEWLINE describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",NEWLINE "--always", "--long",NEWLINE "--match", "%s*" % tag_prefix],NEWLINE cwd=root)NEWLINE # --long was added in git-1.5.5NEWLINE if describe_out is None:NEWLINE raise NotThisMethod("'git describe' failed")NEWLINE describe_out = describe_out.strip()NEWLINE full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)NEWLINE if full_out is None:NEWLINE raise NotThisMethod("'git rev-parse' failed")NEWLINE full_out = full_out.strip()NEWLINENEWLINE pieces = {}NEWLINE pieces["long"] = full_outNEWLINE pieces["short"] = full_out[:7] # maybe improved laterNEWLINE pieces["error"] = NoneNEWLINENEWLINE # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]NEWLINE # TAG might have hyphens.NEWLINE git_describe = describe_outNEWLINENEWLINE # look for -dirty suffixNEWLINE dirty = git_describe.endswith("-dirty")NEWLINE pieces["dirty"] = dirtyNEWLINE if dirty:NEWLINE git_describe = git_describe[:git_describe.rindex("-dirty")]NEWLINENEWLINE # now we have TAG-NUM-gHEX or HEXNEWLINENEWLINE if "-" in git_describe:NEWLINE # TAG-NUM-gHEXNEWLINE mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)NEWLINE if not mo:NEWLINE # unparseable. Maybe git-describe is misbehaving?NEWLINE pieces["error"] = ("unable to parse git-describe output: '%s'"NEWLINE % describe_out)NEWLINE return piecesNEWLINENEWLINE # tagNEWLINE full_tag = mo.group(1)NEWLINE if not full_tag.startswith(tag_prefix):NEWLINE if verbose:NEWLINE fmt = "tag '%s' doesn't start with prefix '%s'"NEWLINE print(fmt % (full_tag, tag_prefix))NEWLINE pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"NEWLINE % (full_tag, tag_prefix))NEWLINE return piecesNEWLINE pieces["closest-tag"] = full_tag[len(tag_prefix):]NEWLINENEWLINE # distance: number of commits since tagNEWLINE pieces["distance"] = int(mo.group(2))NEWLINENEWLINE # commit: short hex revision IDNEWLINE pieces["short"] = mo.group(3)NEWLINENEWLINE else:NEWLINE # HEX: no tagsNEWLINE pieces["closest-tag"] = NoneNEWLINE count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"],NEWLINE cwd=root)NEWLINE pieces["distance"] = int(count_out) # total number of commitsNEWLINENEWLINE # commit date: see ISO-8601 comment in git_versions_from_keywords()NEWLINE date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"],NEWLINE cwd=root)[0].strip()NEWLINE pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)NEWLINENEWLINE return piecesNEWLINENEWLINENEWLINEdef plus_or_dot(pieces):NEWLINE """Return a + if we don't already have one, else return a ."""NEWLINE if "+" in pieces.get("closest-tag", ""):NEWLINE return "."NEWLINE return "+"NEWLINENEWLINENEWLINEdef render_pep440(pieces):NEWLINE """Build up version string, with post-release "local version identifier".NEWLINENEWLINE Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if youNEWLINE get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirtyNEWLINENEWLINE Exceptions:NEWLINE 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += plus_or_dot(pieces)NEWLINE rendered += "%d.g%s" % (pieces["distance"], pieces["short"])NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dirty"NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0+untagged.%d.g%s" % (pieces["distance"],NEWLINE pieces["short"])NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_pre(pieces):NEWLINE """TAG[.post.devDISTANCE] -- No -dirty.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. 0.post.devDISTANCENEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"]:NEWLINE rendered += ".post.dev%d" % pieces["distance"]NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post.dev%d" % pieces["distance"]NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_post(pieces):NEWLINE """TAG[.postDISTANCE[.dev0]+gHEX] .NEWLINENEWLINE The ".dev0" means dirty. Note that .dev0 sorts backwardsNEWLINE (a dirty tree will appear "older" than the corresponding clean one),NEWLINE but you shouldn't be releasing software with -dirty anyways.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. 0.postDISTANCE[.dev0]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += ".post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE rendered += plus_or_dot(pieces)NEWLINE rendered += "g%s" % pieces["short"]NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE rendered += "+g%s" % pieces["short"]NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_pep440_old(pieces):NEWLINE """TAG[.postDISTANCE[.dev0]] .NEWLINENEWLINE The ".dev0" means dirty.NEWLINENEWLINE Eexceptions:NEWLINE 1: no tags. 0.postDISTANCE[.dev0]NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"] or pieces["dirty"]:NEWLINE rendered += ".post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE else:NEWLINE # exception #1NEWLINE rendered = "0.post%d" % pieces["distance"]NEWLINE if pieces["dirty"]:NEWLINE rendered += ".dev0"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_git_describe(pieces):NEWLINE """TAG[-DISTANCE-gHEX][-dirty].NEWLINENEWLINE Like 'git describe --tags --dirty --always'.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. HEX[-dirty] (note: no 'g' prefix)NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE if pieces["distance"]:NEWLINE rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])NEWLINE else:NEWLINE # exception #1NEWLINE rendered = pieces["short"]NEWLINE if pieces["dirty"]:NEWLINE rendered += "-dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render_git_describe_long(pieces):NEWLINE """TAG-DISTANCE-gHEX[-dirty].NEWLINENEWLINE Like 'git describe --tags --dirty --always -long'.NEWLINE The distance/hash is unconditional.NEWLINENEWLINE Exceptions:NEWLINE 1: no tags. HEX[-dirty] (note: no 'g' prefix)NEWLINE """NEWLINE if pieces["closest-tag"]:NEWLINE rendered = pieces["closest-tag"]NEWLINE rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])NEWLINE else:NEWLINE # exception #1NEWLINE rendered = pieces["short"]NEWLINE if pieces["dirty"]:NEWLINE rendered += "-dirty"NEWLINE return renderedNEWLINENEWLINENEWLINEdef render(pieces, style):NEWLINE """Render the given version pieces into the requested style."""NEWLINE if pieces["error"]:NEWLINE return {"version": "unknown",NEWLINE "full-revisionid": pieces.get("long"),NEWLINE "dirty": None,NEWLINE "error": pieces["error"],NEWLINE "date": None}NEWLINENEWLINE if not style or style == "default":NEWLINE style = "pep440" # the defaultNEWLINENEWLINE if style == "pep440":NEWLINE rendered = render_pep440(pieces)NEWLINE elif style == "pep440-pre":NEWLINE rendered = render_pep440_pre(pieces)NEWLINE elif style == "pep440-post":NEWLINE rendered = render_pep440_post(pieces)NEWLINE elif style == "pep440-old":NEWLINE rendered = render_pep440_old(pieces)NEWLINE elif style == "git-describe":NEWLINE rendered = render_git_describe(pieces)NEWLINE elif style == "git-describe-long":NEWLINE rendered = render_git_describe_long(pieces)NEWLINE else:NEWLINE raise ValueError("unknown style '%s'" % style)NEWLINENEWLINE return {"version": rendered, "full-revisionid": pieces["long"],NEWLINE "dirty": pieces["dirty"], "error": None,NEWLINE "date": pieces.get("date")}NEWLINENEWLINENEWLINEdef get_versions():NEWLINE """Get version information or return default if unable to do so."""NEWLINE # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we haveNEWLINE # __file__, we can work backwards from there to the root. SomeNEWLINE # py2exe/bbfreeze/non-CPython implementations don't do __file__, in whichNEWLINE # case we can only use expanded keywords.NEWLINENEWLINE cfg = get_config()NEWLINE verbose = cfg.verboseNEWLINENEWLINE try:NEWLINE return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,NEWLINE verbose)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE try:NEWLINE root = os.path.realpath(__file__)NEWLINE # versionfile_source is the relative path from the top of the sourceNEWLINE # tree (where the .git directory might live) to this file. InvertNEWLINE # this to find the root from __file__.NEWLINE for i in cfg.versionfile_source.split('/'):NEWLINE root = os.path.dirname(root)NEWLINE except NameError:NEWLINE return {"version": "0+unknown", "full-revisionid": None,NEWLINE "dirty": None,NEWLINE "error": "unable to find root of source tree",NEWLINE "date": None}NEWLINENEWLINE try:NEWLINE pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)NEWLINE return render(pieces, cfg.style)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE try:NEWLINE if cfg.parentdir_prefix:NEWLINE return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)NEWLINE except NotThisMethod:NEWLINE passNEWLINENEWLINE return {"version": "0+unknown", "full-revisionid": None,NEWLINE "dirty": None,NEWLINE "error": "unable to compute version", "date": None}NEWLINE |
# coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root forNEWLINE# license information.NEWLINE#NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code isNEWLINE# regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEfrom msrest.paging import PagedNEWLINENEWLINENEWLINEclass UserPaged(Paged):NEWLINE """NEWLINE A paging container for iterating over a list of :class:`User <azure.graphrbac.models.User>` objectNEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'next_link': {'key': 'odata\\.nextLink', 'type': 'str'},NEWLINE 'current_page': {'key': 'value', 'type': '[User]'}NEWLINE }NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINENEWLINE super(UserPaged, self).__init__(*args, **kwargs)NEWLINE |
import torchNEWLINENEWLINE#from tinydfa import DFA, DFALayer, FeedbackPointsHandlingNEWLINEfrom tinydfa.light_dfa import DFA, DFALayerNEWLINENEWLINENEWLINEclass VeryTinyNeRFModel(torch.nn.Module):NEWLINE r"""Define a "very tiny" NeRF model comprising three fully connected layers.NEWLINE """NEWLINENEWLINE def __init__(self, filter_size=128, num_encoding_functions=6, use_viewdirs=True):NEWLINE super(VeryTinyNeRFModel, self).__init__()NEWLINE self.num_encoding_functions = num_encoding_functionsNEWLINE self.xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE if use_viewdirs is True:NEWLINE self.viewdir_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE else:NEWLINE self.viewdir_encoding_dims = 0NEWLINE # Input layer (default: 65 -> 128)NEWLINE self.layer1 = torch.nn.Linear(NEWLINE self.xyz_encoding_dims + self.viewdir_encoding_dims, filter_sizeNEWLINE )NEWLINE # Layer 2 (default: 128 -> 128)NEWLINE self.layer2 = torch.nn.Linear(filter_size, filter_size)NEWLINE # Layer 3 (default: 128 -> 4)NEWLINE self.layer3 = torch.nn.Linear(filter_size, 4)NEWLINE # Short hand for torch.nn.functional.reluNEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE x = self.relu(self.layer1(x))NEWLINE x = self.relu(self.layer2(x))NEWLINE x = self.layer3(x)NEWLINE return xNEWLINENEWLINENEWLINEclass MultiHeadNeRFModel(torch.nn.Module):NEWLINE r"""Define a "multi-head" NeRF model (radiance and RGB colors are predicted byNEWLINE separate heads).NEWLINE """NEWLINENEWLINE def __init__(self, hidden_size=128, num_encoding_functions=6, use_viewdirs=True):NEWLINE super(MultiHeadNeRFModel, self).__init__()NEWLINE self.num_encoding_functions = num_encoding_functionsNEWLINE self.xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE if use_viewdirs is True:NEWLINE self.viewdir_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINE else:NEWLINE self.viewdir_encoding_dims = 0NEWLINE # Input layer (default: 39 -> 128)NEWLINE self.layer1 = torch.nn.Linear(self.xyz_encoding_dims, hidden_size)NEWLINE # Layer 2 (default: 128 -> 128)NEWLINE self.layer2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE # Layer 3_1 (default: 128 -> 1): Predicts radiance ("sigma")NEWLINE self.layer3_1 = torch.nn.Linear(hidden_size, 1)NEWLINE # Layer 3_2 (default: 128 -> 1): Predicts a feature vector (used for color)NEWLINE self.layer3_2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINENEWLINE # Layer 4 (default: 39 + 128 -> 128)NEWLINE self.layer4 = torch.nn.Linear(NEWLINE self.viewdir_encoding_dims + hidden_size, hidden_sizeNEWLINE )NEWLINE # Layer 5 (default: 128 -> 128)NEWLINE self.layer5 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE # Layer 6 (default: 128 -> 3): Predicts RGB colorNEWLINE self.layer6 = torch.nn.Linear(hidden_size, 3)NEWLINENEWLINE # Short hand for torch.nn.functional.reluNEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE x, view = x[..., : self.xyz_encoding_dims], x[..., self.xyz_encoding_dims :]NEWLINE x = self.relu(self.layer1(x))NEWLINE x = self.relu(self.layer2(x))NEWLINE sigma = self.layer3_1(x)NEWLINE feat = self.relu(self.layer3_2(x))NEWLINE x = torch.cat((feat, view), dim=-1)NEWLINE x = self.relu(self.layer4(x))NEWLINE x = self.relu(self.layer5(x))NEWLINE x = self.layer6(x)NEWLINE return torch.cat((x, sigma), dim=-1)NEWLINENEWLINENEWLINEclass ReplicateNeRFModel(torch.nn.Module):NEWLINE r"""NeRF model that follows the figure (from the supp. material of NeRF) toNEWLINE every last detail. (ofc, with some flexibility)NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE hidden_size=256,NEWLINE num_layers=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE ):NEWLINE super(ReplicateNeRFModel, self).__init__()NEWLINE # xyz_encoding_dims = 3 + 3 * 2 * num_encoding_functionsNEWLINENEWLINE self.dim_xyz = (3 if include_input_xyz else 0) + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = (3 if include_input_dir else 0) + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size)NEWLINE self.layer2 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE self.layer3 = torch.nn.Linear(hidden_size, hidden_size)NEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1)NEWLINENEWLINE self.layer4 = torch.nn.Linear(hidden_size + self.dim_dir, hidden_size // 2)NEWLINE self.layer5 = torch.nn.Linear(hidden_size // 2, hidden_size // 2)NEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3)NEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE xyz, direction = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE x_ = self.relu(self.layer1(xyz))NEWLINE x_ = self.relu(self.layer2(x_))NEWLINE feat = self.layer3(x_)NEWLINE alpha = self.fc_alpha(x_)NEWLINE y_ = self.relu(self.layer4(torch.cat((feat, direction), dim=-1)))NEWLINE y_ = self.relu(self.layer5(y_))NEWLINE rgb = self.fc_rgb(y_)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINENEWLINENEWLINEclass PaperNeRFModel(torch.nn.Module):NEWLINE r"""Implements the NeRF model as described in Fig. 7 (appendix) of theNEWLINE arXiv submission (v0). """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE num_layers=8,NEWLINE hidden_size=256,NEWLINE skip_connect_every=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE use_viewdirs=True,NEWLINE ):NEWLINE super(PaperNeRFModel, self).__init__()NEWLINENEWLINE include_input_xyz = 3 if include_input_xyz else 0NEWLINE include_input_dir = 3 if include_input_dir else 0NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE self.use_viewdirs = use_viewdirsNEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz, 256))NEWLINE for i in range(1, 8):NEWLINE if i == 4:NEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz + 256, 256))NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(256, 256))NEWLINE self.fc_feat = torch.nn.Linear(256, 256)NEWLINE self.fc_alpha = torch.nn.Linear(256, 1)NEWLINENEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE self.layers_dir.append(torch.nn.Linear(256 + self.dim_dir, 128))NEWLINE for i in range(3):NEWLINE self.layers_dir.append(torch.nn.Linear(128, 128))NEWLINE self.fc_rgb = torch.nn.Linear(128, 3)NEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE xyz, dirs = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE for i in range(8):NEWLINE if i == 4:NEWLINE x = self.layers_xyz[i](torch.cat((xyz, x), -1))NEWLINE else:NEWLINE x = self.layers_xyz[i](x)NEWLINE x = self.relu(x)NEWLINE feat = self.fc_feat(x)NEWLINE alpha = self.fc_alpha(feat)NEWLINE if self.use_viewdirs:NEWLINE x = self.layers_dir[0](torch.cat((feat, dirs), -1))NEWLINE else:NEWLINE x = self.layers_dir[0](feat)NEWLINE x = self.relu(x)NEWLINE for i in range(1, 3):NEWLINE x = self.layers_dir[i](x)NEWLINE x = self.relu(x)NEWLINE rgb = self.fc_rgb(x)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINENEWLINENEWLINEclass FlexibleNeRFModel(torch.nn.Module):NEWLINE def __init__(NEWLINE self,NEWLINE num_layers=4,NEWLINE hidden_size=128,NEWLINE skip_connect_every=4,NEWLINE num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4,NEWLINE include_input_xyz=True,NEWLINE include_input_dir=True,NEWLINE use_viewdirs=True,NEWLINE ):NEWLINE super(FlexibleNeRFModel, self).__init__()NEWLINENEWLINE include_input_xyz = 3 if include_input_xyz else 0NEWLINE include_input_dir = 3 if include_input_dir else 0NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyzNEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINE self.skip_connect_every = skip_connect_everyNEWLINE if not use_viewdirs:NEWLINE self.dim_dir = 0NEWLINENEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size)NEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE for i in range(num_layers - 1):NEWLINE if i % self.skip_connect_every == 0 and i > 0 and i != num_layers - 1:NEWLINE self.layers_xyz.append(NEWLINE torch.nn.Linear(self.dim_xyz + hidden_size, hidden_size)NEWLINE )NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(hidden_size, hidden_size))NEWLINENEWLINE self.use_viewdirs = use_viewdirsNEWLINE if self.use_viewdirs:NEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE # This deviates from the original paper, and follows the code release instead.NEWLINE self.layers_dir.append(NEWLINE torch.nn.Linear(self.dim_dir + hidden_size, hidden_size // 2)NEWLINE )NEWLINENEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1)NEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3)NEWLINE self.fc_feat = torch.nn.Linear(hidden_size, hidden_size)NEWLINE else:NEWLINE self.fc_out = torch.nn.Linear(hidden_size, 4)NEWLINENEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE def forward(self, x):NEWLINE if self.use_viewdirs:NEWLINE xyz, view = x[..., : self.dim_xyz], x[..., self.dim_xyz :]NEWLINE else:NEWLINE xyz = x[..., : self.dim_xyz]NEWLINE x = self.layer1(xyz) # Missing a ReLU (?)NEWLINE for i in range(len(self.layers_xyz)):NEWLINE if (NEWLINE i % self.skip_connect_every == 0NEWLINE and i > 0NEWLINE and i != len(self.linear_layers) - 1NEWLINE ):NEWLINE x = torch.cat((x, xyz), dim=-1)NEWLINE x = self.relu(self.layers_xyz[i](x))NEWLINE if self.use_viewdirs:NEWLINE feat = self.relu(self.fc_feat(x))NEWLINE alpha = self.fc_alpha(x)NEWLINE x = torch.cat((feat, view), dim=-1)NEWLINE for l in self.layers_dir:NEWLINE x = self.relu(l(x))NEWLINE rgb = self.fc_rgb(x)NEWLINE return torch.cat((rgb, alpha), dim=-1)NEWLINE else:NEWLINE return self.fc_out(x)NEWLINENEWLINENEWLINEclass DFAFlexibleNeRFModel(torch.nn.Module):NEWLINE def __init__(self, num_layers=4, hidden_size=128, skip_connect_every=4, num_encoding_fn_xyz=6,NEWLINE num_encoding_fn_dir=4, include_input_xyz=True, include_input_dir=True, use_viewdirs=True,):NEWLINE super(DFAFlexibleNeRFModel, self).__init__()NEWLINENEWLINE # Determine the inputs:NEWLINE include_input_xyz = 3 if include_input_xyz else 0 # Add raw xyz coordinatesNEWLINE include_input_dir = 3 if include_input_dir else 0 # Add raw viewing angle (specularity)NEWLINE self.dim_xyz = include_input_xyz + 2 * 3 * num_encoding_fn_xyz # Total xyz input: raw? + embeddingNEWLINENEWLINE self.use_viewdirs = use_viewdirs # Are we using view direction? (specularity)NEWLINE if not self.use_viewdirs:NEWLINE self.dim_dir = 0NEWLINE else:NEWLINE self.dim_dir = include_input_dir + 2 * 3 * num_encoding_fn_dirNEWLINENEWLINE # Network layersNEWLINE self.layer1 = torch.nn.Linear(self.dim_xyz, hidden_size) # Input layerNEWLINE self.dfa1 = DFALayer(name='dfa1')NEWLINE # First stack of layers, using only xyz coordinates:NEWLINE self.layers_xyz = torch.nn.ModuleList()NEWLINE self.dfa_xyz = torch.nn.ModuleList()NEWLINE self.skip_connect_every = skip_connect_everyNEWLINE for i in range(num_layers - 1):NEWLINE if i % self.skip_connect_every == 0 and i > 0 and i != num_layers - 1:NEWLINE # Handle skip-connection.NEWLINE self.layers_xyz.append(torch.nn.Linear(self.dim_xyz + hidden_size, hidden_size))NEWLINE else:NEWLINE self.layers_xyz.append(torch.nn.Linear(hidden_size, hidden_size))NEWLINE self.dfa_xyz.append(DFALayer(name=f'dfa_xyz{i}'))NEWLINENEWLINENEWLINE if self.use_viewdirs:NEWLINE self.fc_alpha = torch.nn.Linear(hidden_size, 1) # Transparency output at top of xyz stackNEWLINENEWLINE self.fc_feat = torch.nn.Linear(hidden_size, hidden_size) # Link between angle stack and xyz stackNEWLINE self.dfa_feat = DFALayer(name='dfa_feat')NEWLINENEWLINE # Second stack of layers, using viewing angle:NEWLINE self.layers_dir = torch.nn.ModuleList()NEWLINE # This deviates from the original paper, and follows the code release instead.NEWLINE self.layers_dir.append(NEWLINE torch.nn.Linear(self.dim_dir + hidden_size, hidden_size // 2)NEWLINE )NEWLINE self.dfa_dir = DFALayer(name='dfa_dir')NEWLINENEWLINE self.fc_rgb = torch.nn.Linear(hidden_size // 2, 3) # RGB color output, at top of viewing angle stackNEWLINE else:NEWLINE # If not using viewing angle, go straight to (transparency, r, g, b) output:NEWLINE self.fc_out = torch.nn.Linear(hidden_size, 4)NEWLINENEWLINE self.relu = torch.nn.functional.reluNEWLINENEWLINE self.dfa_layers = [self.dfa1, *self.dfa_xyz, self.dfa_feat, self.dfa_dir]NEWLINE self.dfa = DFA(self.dfa_layers) #feedback_points_handling=FeedbackPointsHandling.MINIBATCH)NEWLINENEWLINE def forward(self, x):NEWLINE # Separate the xyz and viewing angle embeddingsNEWLINE if self.use_viewdirs:NEWLINE xyz, view = x[..., :self.dim_xyz], x[..., self.dim_xyz:]NEWLINE else:NEWLINE xyz = x[..., :self.dim_xyz]NEWLINENEWLINE x = self.dfa1(self.relu(self.layer1(xyz))) # Go through first layerNEWLINE # Go through xyz stack:NEWLINE for i in range(len(self.layers_xyz)):NEWLINE if (i % self.skip_connect_every == 0 and i > 0 and i != len(self.linear_layers) - 1):NEWLINE # Handle skip connectionNEWLINE x = torch.cat((x, xyz), dim=-1)NEWLINE x = self.dfa_xyz[i](self.relu(self.layers_xyz[i](x))) # Go through layerNEWLINENEWLINE if self.use_viewdirs:NEWLINE alpha = self.fc_alpha(x) # Output alpha (transparency value)NEWLINE # Prepare for viewing angle stack:NEWLINE feat = self.dfa_feat(self.relu(self.fc_feat(x))) # Link between xyz/viewing angle stackNEWLINE x = torch.cat((feat, view), dim=-1) # Add viewing angle informationNEWLINE for l in self.layers_dir:NEWLINE # Go through viewing angle stack (proper):NEWLINE x = self.dfa_dir(self.relu(l(x)))NEWLINE rgb = self.fc_rgb(x) # Output rgb valueNEWLINE return self.dfa(torch.cat((rgb, alpha), dim=-1))NEWLINE else:NEWLINE return self.dfa(self.fc_out(x))NEWLINE |
# -*- coding: utf-8 -*-NEWLINEfrom hashlib import sha256NEWLINENEWLINEfrom .sha1 import SHA1NEWLINENEWLINENEWLINEdef hmac(key, message, hash_class):NEWLINE block_size = hash_class().block_sizeNEWLINENEWLINE if len(key) > block_size:NEWLINE key = hash_class(key).digest()NEWLINE key = key.ljust(block_size, b"\x00")NEWLINENEWLINE mac = message.encode() if isinstance(message, str) else messageNEWLINE for pad_byte in b"\x5c", b"\x36":NEWLINE prefix = bytes(kb ^ pb for kb, pb in zip(key, pad_byte * block_size))NEWLINE mac = hash_class(prefix + mac).digest()NEWLINENEWLINE return macNEWLINENEWLINENEWLINEdef hmac_sha1(key, message):NEWLINE return hmac(key, message, SHA1)NEWLINENEWLINENEWLINEdef hmac_sha256(key, message):NEWLINE return hmac(key, message, sha256)NEWLINE |
# Copyright 2019 The Vitess Authors.NEWLINE# NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE# NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE# NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""Kubernetes environment."""NEWLINENEWLINEimport getpassNEWLINEimport jsonNEWLINEimport loggingNEWLINEimport osNEWLINEimport subprocessNEWLINEimport timeNEWLINENEWLINEfrom sandbox import kubernetes_componentsNEWLINEfrom vtproto import topodata_pb2NEWLINEfrom vtdb import vtgate_clientNEWLINEimport base_environmentNEWLINEimport protocols_flavorNEWLINEimport vtctl_helperNEWLINENEWLINENEWLINEclass K8sEnvironment(base_environment.BaseEnvironment):NEWLINE """Environment for kubernetes clusters on Google Compute Engine."""NEWLINENEWLINE def __init__(self):NEWLINE super(K8sEnvironment, self).__init__()NEWLINENEWLINE def use_named(self, instance_name):NEWLINE # Check to make sure kubectl existsNEWLINE try:NEWLINE subprocess.check_output(['kubectl'])NEWLINE except OSError:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'kubectl not found, please install by visiting kubernetes.io or 'NEWLINE 'running gcloud components update kubectl if using compute engine.')NEWLINENEWLINE vtctld_ip = kubernetes_components.get_forwarded_ip(NEWLINE 'vtctld', instance_name)NEWLINE self.vtctl_addr = '%s:15999' % vtctld_ipNEWLINENEWLINE self.vtctl_helper = vtctl_helper.VtctlHelper('grpc', self.vtctl_addr)NEWLINE self.cluster_name = instance_nameNEWLINENEWLINE keyspaces = self.vtctl_helper.execute_vtctl_command(['GetKeyspaces'])NEWLINE self.mobs = filter(None, keyspaces.split('\n'))NEWLINE self.keyspaces = self.mobsNEWLINENEWLINE if not self.keyspaces:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'Invalid environment, no keyspaces found')NEWLINENEWLINE self.num_shards = []NEWLINE self.shards = []NEWLINENEWLINE for keyspace in self.keyspaces:NEWLINE shards = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['FindAllShardsInKeyspace', keyspace]))NEWLINE self.shards.append(shards)NEWLINE self.num_shards.append(len(shards))NEWLINENEWLINE # This assumes that all keyspaces use the same set of cellsNEWLINE self.cells = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['GetShard', '%s/%s' % (self.keyspaces[0], self.shards[0].keys()[0])]NEWLINE ))['cells']NEWLINENEWLINE self.primary_cells = self.cellsNEWLINE self.replica_instances = []NEWLINE self.rdonly_instances = []NEWLINENEWLINE # This assumes that all cells are equivalent for k8s environments.NEWLINE all_tablets_in_a_cell = self.vtctl_helper.execute_vtctl_command(NEWLINE ['ListAllTablets', self.cells[0]])NEWLINE all_tablets_in_a_cell = [x.split(' ') for x inNEWLINE filter(None, all_tablets_in_a_cell.split('\n'))]NEWLINENEWLINE for index, keyspace in enumerate(self.keyspaces):NEWLINE keyspace_tablets_in_cell = [NEWLINE tablet for tablet in all_tablets_in_a_cell if tablet[1] == keyspace]NEWLINE replica_tablets_in_cell = [NEWLINE tablet for tablet in keyspace_tablets_in_cellNEWLINE if tablet[3] == 'master' or tablet[3] == 'replica']NEWLINE replica_instances = len(replica_tablets_in_cell) / self.num_shards[index]NEWLINE self.replica_instances.append(replica_instances)NEWLINE self.rdonly_instances.append(NEWLINE (len(keyspace_tablets_in_cell) / self.num_shards[index]) -NEWLINE replica_instances)NEWLINENEWLINE # Converts keyspace name and alias to number of instancesNEWLINE self.keyspace_alias_to_num_instances_dict = {}NEWLINE for index, keyspace in enumerate(self.keyspaces):NEWLINE self.keyspace_alias_to_num_instances_dict[keyspace] = {NEWLINE 'replica': int(self.replica_instances[index]),NEWLINE 'rdonly': int(self.rdonly_instances[index])NEWLINE }NEWLINENEWLINE self.vtgate_addrs = {}NEWLINE for cell in self.cells:NEWLINE vtgate_ip = kubernetes_components.get_forwarded_ip(NEWLINE 'vtgate-%s' % cell, instance_name)NEWLINE self.vtgate_addrs[cell] = '%s:15991' % vtgate_ipNEWLINE super(K8sEnvironment, self).use_named(instance_name)NEWLINENEWLINE def create(self, **kwargs):NEWLINE self.create_gke_cluster = (NEWLINE kwargs.get('create_gke_cluster', 'false').lower() != 'false')NEWLINE if self.create_gke_cluster and 'GKE_NUM_NODES' not in kwargs:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'Must specify GKE_NUM_NODES')NEWLINE if 'GKE_CLUSTER_NAME' not in kwargs:NEWLINE kwargs['GKE_CLUSTER_NAME'] = getpass.getuser()NEWLINE if 'VITESS_NAME' not in kwargs:NEWLINE kwargs['VITESS_NAME'] = getpass.getuser()NEWLINE kwargs['TEST_MODE'] = '1'NEWLINE self.script_dir = os.path.join(os.environ['VTROOT'], 'examples/kubernetes')NEWLINE try:NEWLINE subprocess.check_output(['gcloud', 'config', 'list'])NEWLINE except OSError:NEWLINE raise base_environment.VitessEnvironmentError(NEWLINE 'gcloud not found, please install by visiting cloud.google.com')NEWLINE if 'project' in kwargs:NEWLINE logging.info('Setting project to %s', kwargs['project'])NEWLINE subprocess.check_output(NEWLINE ['gcloud', 'config', 'set', 'project', kwargs['project']])NEWLINE project_name_json = json.loads(subprocess.check_output(NEWLINE ['gcloud', 'config', 'list', 'project', '--format', 'json']))NEWLINE project_name = project_name_json['core']['project']NEWLINE logging.info('Current project name: %s', project_name)NEWLINE for k, v in kwargs.iteritems():NEWLINE os.environ[k] = vNEWLINE if self.create_gke_cluster:NEWLINE cluster_up_txt = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'cluster-up.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(cluster_up_txt)NEWLINE vitess_up_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'vitess-up.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(vitess_up_output)NEWLINE self.use_named(kwargs['VITESS_NAME'])NEWLINENEWLINE def destroy(self):NEWLINE vitess_down_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'vitess-down.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(vitess_down_output)NEWLINE if self.create_gke_cluster:NEWLINE cluster_down_output = subprocess.check_output(NEWLINE [os.path.join(self.script_dir, 'cluster-down.sh')],NEWLINE cwd=self.script_dir, stderr=subprocess.STDOUT)NEWLINE logging.info(cluster_down_output)NEWLINENEWLINE def get_vtgate_conn(self, cell):NEWLINE return vtgate_client.connect(NEWLINE protocols_flavor.protocols_flavor().vtgate_python_protocol(),NEWLINE self.vtgate_addrs[cell], 60)NEWLINENEWLINE def restart_mysql_task(self, tablet_name, task_name, is_alloc=False):NEWLINE # Delete the whole pod, which deletes mysql + vttablet tasks.NEWLINE os.system('kubectl delete pod %s --namespace=%s' % (NEWLINE self.get_tablet_pod_name(tablet_name), self.cluster_name))NEWLINE return 0NEWLINENEWLINE def wait_for_good_failover_status(NEWLINE self, keyspace, shard_name, failover_completion_timeout_s=60):NEWLINE return 0NEWLINENEWLINE def poll_for_varz(self, tablet_name, varz, timeout=60.0,NEWLINE condition_fn=None, converter=str, condition_msg=None):NEWLINE """Polls for varz to exist, or match specific conditions, within a timeout.NEWLINENEWLINE Args:NEWLINE tablet_name: the name of the process that we're trying to poll vars from.NEWLINE varz: name of the vars to fetch from varzNEWLINE timeout: number of seconds that we should attempt to poll for.NEWLINE condition_fn: a function that takes the var as input, and returns a truthyNEWLINE value if it matches the success conditions.NEWLINE converter: function to convert varz valueNEWLINE condition_msg: string describing the conditions that we're polling for,NEWLINE used for error messaging.NEWLINENEWLINE Raises:NEWLINE VitessEnvironmentError: Raised if the varz conditions aren't met withinNEWLINE the given timeout.NEWLINENEWLINE Returns:NEWLINE dict of requested varz.NEWLINE """NEWLINE start_time = time.time()NEWLINE while True:NEWLINE if (time.time() - start_time) >= timeout:NEWLINE timeout_error_msg = 'Timed out polling for varz.'NEWLINE if condition_fn and condition_msg:NEWLINE timeout_error_msg += ' Condition "%s" not met.' % condition_msgNEWLINE raise base_environment.VitessEnvironmentError(timeout_error_msg)NEWLINE hostname = self.get_tablet_ip_port(tablet_name)NEWLINE host_varz = subprocess.check_output([NEWLINE 'kubectl', 'exec', '-ti', self.get_tablet_pod_name(tablet_name),NEWLINE '--namespace=%s' % self.cluster_name,NEWLINE 'curl', '%s/debug/vars' % hostname])NEWLINE if not host_varz:NEWLINE continueNEWLINE host_varz = json.loads(host_varz)NEWLINE if condition_fn is None or condition_fn(host_varz):NEWLINE return host_varzNEWLINENEWLINE def wait_for_healthy_tablets(self):NEWLINE return 0NEWLINENEWLINE def get_tablet_pod_name(self, tablet_name):NEWLINE tablet_info = json.loads(self.vtctl_helper.execute_vtctl_command(NEWLINE ['GetTablet', tablet_name]))NEWLINE # Hostname is <pod_name>.vttabletNEWLINE return tablet_info['hostname'].split('.')[0]NEWLINENEWLINE def get_tablet_task_number(self, tablet_name):NEWLINE # Tablet pod name under StatefulSet isNEWLINE # "<cell>-<keyspace>-<shard_number>-<tablet_type>-<task_number>"NEWLINE # Example: test1-foo-0-replica-0.NEWLINE return int(self.get_tablet_pod_name(tablet_name).split('-')[-1])NEWLINENEWLINE def automatic_reparent_available(self):NEWLINE """Checks if the environment can automatically reparent."""NEWLINE p1 = subprocess.Popen(NEWLINE ['kubectl', 'get', 'pods', '--namespace=%s' % self.cluster_name],NEWLINE stdout=subprocess.PIPE)NEWLINE p2 = subprocess.Popen(NEWLINE ['grep', 'orchestrator'], stdin=p1.stdout, stdout=subprocess.PIPE)NEWLINE output = p2.communicate()[0]NEWLINE return bool(output)NEWLINENEWLINE def internal_reparent(self, keyspace, shard_name, new_master_uid,NEWLINE emergency=False):NEWLINE reparent_command = (NEWLINE 'EmergencyReparentShard' if emergency else 'PlannedReparentShard')NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE [reparent_command, '-keyspace_shard', '%s/%s' % (keyspace, shard_name),NEWLINE '-new_master', new_master_uid])NEWLINE self.vtctl_helper.execute_vtctl_command(['RebuildKeyspaceGraph', keyspace])NEWLINE return 0, 'No output'NEWLINENEWLINE def backup(self, tablet_name):NEWLINE logging.info('Backing up tablet %s', tablet_name)NEWLINE self.vtctl_helper.execute_vtctl_command(['Backup', tablet_name])NEWLINENEWLINE def drain_tablet(self, tablet_name, duration_s=600):NEWLINE self.vtctl_helper.execute_vtctl_command(['StopSlave', tablet_name])NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE ['ChangeSlaveType', tablet_name, 'drained'])NEWLINENEWLINE def is_tablet_drained(self, tablet_name):NEWLINE return self.get_tablet_type(tablet_name) == topodata_pb2.DRAINEDNEWLINENEWLINE def undrain_tablet(self, tablet_name):NEWLINE self.vtctl_helper.execute_vtctl_command(NEWLINE ['ChangeSlaveType', tablet_name, 'replica'])NEWLINE self.vtctl_helper.execute_vtctl_command(['StartSlave', tablet_name])NEWLINENEWLINE def is_tablet_undrained(self, tablet_name):NEWLINE return not self.is_tablet_drained(tablet_name)NEWLINENEWLINE def get_tablet_query_total_count(self, tablet_name):NEWLINE return self.poll_for_varz(NEWLINE tablet_name, ['Queries'])['Queries']['TotalCount']NEWLINENEWLINE |
# -*- coding: utf-8 -*-NEWLINENEWLINE# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:NEWLINE# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-codeNEWLINENEWLINEfrom ccxt.async_support.base.exchange import ExchangeNEWLINEimport base64NEWLINEfrom ccxt.base.errors import ExchangeErrorNEWLINEfrom ccxt.base.errors import ArgumentsRequiredNEWLINENEWLINENEWLINEclass luno (Exchange):NEWLINENEWLINE def describe(self):NEWLINE return self.deep_extend(super(luno, self).describe(), {NEWLINE 'id': 'luno',NEWLINE 'name': 'luno',NEWLINE 'countries': ['GB', 'SG', 'ZA'],NEWLINE 'rateLimit': 1000,NEWLINE 'version': '1',NEWLINE 'has': {NEWLINE 'CORS': False,NEWLINE 'fetchTickers': True,NEWLINE 'fetchOrder': True,NEWLINE 'fetchOrders': True,NEWLINE 'fetchOpenOrders': True,NEWLINE 'fetchClosedOrders': True,NEWLINE 'fetchMyTrades': True,NEWLINE 'fetchTradingFees': True,NEWLINE },NEWLINE 'urls': {NEWLINE 'logo': 'https://user-images.githubusercontent.com/1294454/27766607-8c1a69d8-5ede-11e7-930c-540b5eb9be24.jpg',NEWLINE 'api': 'https://api.mybitx.com/api',NEWLINE 'www': 'https://www.luno.com',NEWLINE 'doc': [NEWLINE 'https://www.luno.com/en/api',NEWLINE 'https://npmjs.org/package/bitx',NEWLINE 'https://github.com/bausmeier/node-bitx',NEWLINE ],NEWLINE },NEWLINE 'api': {NEWLINE 'public': {NEWLINE 'get': [NEWLINE 'orderbook',NEWLINE 'orderbook_top',NEWLINE 'ticker',NEWLINE 'tickers',NEWLINE 'trades',NEWLINE ],NEWLINE },NEWLINE 'private': {NEWLINE 'get': [NEWLINE 'accounts/{id}/pending',NEWLINE 'accounts/{id}/transactions',NEWLINE 'balance',NEWLINE 'fee_info',NEWLINE 'funding_address',NEWLINE 'listorders',NEWLINE 'listtrades',NEWLINE 'orders/{id}',NEWLINE 'quotes/{id}',NEWLINE 'withdrawals',NEWLINE 'withdrawals/{id}',NEWLINE ],NEWLINE 'post': [NEWLINE 'accounts',NEWLINE 'postorder',NEWLINE 'marketorder',NEWLINE 'stoporder',NEWLINE 'funding_address',NEWLINE 'withdrawals',NEWLINE 'send',NEWLINE 'quotes',NEWLINE 'oauth2/grant',NEWLINE ],NEWLINE 'put': [NEWLINE 'quotes/{id}',NEWLINE ],NEWLINE 'delete': [NEWLINE 'quotes/{id}',NEWLINE 'withdrawals/{id}',NEWLINE ],NEWLINE },NEWLINE },NEWLINE })NEWLINENEWLINE async def fetch_markets(self, params={}):NEWLINE markets = await self.publicGetTickers()NEWLINE result = []NEWLINE for p in range(0, len(markets['tickers'])):NEWLINE market = markets['tickers'][p]NEWLINE id = market['pair']NEWLINE base = id[0:3]NEWLINE quote = id[3:6]NEWLINE base = self.common_currency_code(base)NEWLINE quote = self.common_currency_code(quote)NEWLINE symbol = base + '/' + quoteNEWLINE result.append({NEWLINE 'id': id,NEWLINE 'symbol': symbol,NEWLINE 'base': base,NEWLINE 'quote': quote,NEWLINE 'info': market,NEWLINE })NEWLINE return resultNEWLINENEWLINE async def fetch_balance(self, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.privateGetBalance()NEWLINE wallets = response['balance']NEWLINE result = {'info': response}NEWLINE for b in range(0, len(wallets)):NEWLINE wallet = wallets[b]NEWLINE currency = self.common_currency_code(wallet['asset'])NEWLINE reserved = float(wallet['reserved'])NEWLINE unconfirmed = float(wallet['unconfirmed'])NEWLINE balance = float(wallet['balance'])NEWLINE account = {NEWLINE 'free': 0.0,NEWLINE 'used': self.sum(reserved, unconfirmed),NEWLINE 'total': self.sum(balance, unconfirmed),NEWLINE }NEWLINE account['free'] = account['total'] - account['used']NEWLINE result[currency] = accountNEWLINE return self.parse_balance(result)NEWLINENEWLINE async def fetch_order_book(self, symbol, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE method = 'publicGetOrderbook'NEWLINE if limit is not None:NEWLINE if limit <= 100:NEWLINE method += 'Top' # get just the top of the orderbook when limit is lowNEWLINE orderbook = await getattr(self, method)(self.extend({NEWLINE 'pair': self.market_id(symbol),NEWLINE }, params))NEWLINE timestamp = orderbook['timestamp']NEWLINE return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'volume')NEWLINENEWLINE def parse_order(self, order, market=None):NEWLINE timestamp = order['creation_timestamp']NEWLINE status = 'open' if (order['state'] == 'PENDING') else 'closed'NEWLINE side = 'sell' if (order['type'] == 'ASK') else 'buy'NEWLINE if market is None:NEWLINE market = self.find_market(order['pair'])NEWLINE symbol = market['symbol']NEWLINE price = self.safe_float(order, 'limit_price')NEWLINE amount = self.safe_float(order, 'limit_volume')NEWLINE quoteFee = self.safe_float(order, 'fee_counter')NEWLINE baseFee = self.safe_float(order, 'fee_base')NEWLINE filled = self.safe_float(order, 'base')NEWLINE cost = self.safe_float(order, 'counter')NEWLINE remaining = NoneNEWLINE if amount is not None:NEWLINE if filled is not None:NEWLINE remaining = max(0, amount - filled)NEWLINE fee = {'currency': None}NEWLINE if quoteFee:NEWLINE fee['side'] = 'quote'NEWLINE fee['cost'] = quoteFeeNEWLINE else:NEWLINE fee['side'] = 'base'NEWLINE fee['cost'] = baseFeeNEWLINE return {NEWLINE 'id': order['order_id'],NEWLINE 'datetime': self.iso8601(timestamp),NEWLINE 'timestamp': timestamp,NEWLINE 'lastTradeTimestamp': None,NEWLINE 'status': status,NEWLINE 'symbol': symbol,NEWLINE 'type': None,NEWLINE 'side': side,NEWLINE 'price': price,NEWLINE 'amount': amount,NEWLINE 'filled': filled,NEWLINE 'cost': cost,NEWLINE 'remaining': remaining,NEWLINE 'trades': None,NEWLINE 'fee': fee,NEWLINE 'info': order,NEWLINE }NEWLINENEWLINE async def fetch_order(self, id, symbol=None, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.privateGetOrdersId(self.extend({NEWLINE 'id': id,NEWLINE }, params))NEWLINE return self.parse_order(response)NEWLINENEWLINE async def fetch_orders_by_state(self, state=None, symbol=None, since=None, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE request = {}NEWLINE market = NoneNEWLINE if state is not None:NEWLINE request['state'] = stateNEWLINE if symbol is not None:NEWLINE market = self.market(symbol)NEWLINE request['pair'] = market['id']NEWLINE response = await self.privateGetListorders(self.extend(request, params))NEWLINE orders = self.safe_value(response, 'orders', [])NEWLINE return self.parse_orders(orders, market, since, limit)NEWLINENEWLINE async def fetch_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE return await self.fetch_orders_by_state(None, symbol, since, limit, params)NEWLINENEWLINE async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE return await self.fetch_orders_by_state('PENDING', symbol, since, limit, params)NEWLINENEWLINE async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):NEWLINE return await self.fetch_orders_by_state('COMPLETE', symbol, since, limit, params)NEWLINENEWLINE def parse_ticker(self, ticker, market=None):NEWLINE timestamp = ticker['timestamp']NEWLINE symbol = NoneNEWLINE if market:NEWLINE symbol = market['symbol']NEWLINE last = self.safe_float(ticker, 'last_trade')NEWLINE return {NEWLINE 'symbol': symbol,NEWLINE 'timestamp': timestamp,NEWLINE 'datetime': self.iso8601(timestamp),NEWLINE 'high': None,NEWLINE 'low': None,NEWLINE 'bid': self.safe_float(ticker, 'bid'),NEWLINE 'bidVolume': None,NEWLINE 'ask': self.safe_float(ticker, 'ask'),NEWLINE 'askVolume': None,NEWLINE 'vwap': None,NEWLINE 'open': None,NEWLINE 'close': last,NEWLINE 'last': last,NEWLINE 'previousClose': None,NEWLINE 'change': None,NEWLINE 'percentage': None,NEWLINE 'average': None,NEWLINE 'baseVolume': self.safe_float(ticker, 'rolling_24_hour_volume'),NEWLINE 'quoteVolume': None,NEWLINE 'info': ticker,NEWLINE }NEWLINENEWLINE async def fetch_tickers(self, symbols=None, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.publicGetTickers(params)NEWLINE tickers = self.index_by(response['tickers'], 'pair')NEWLINE ids = list(tickers.keys())NEWLINE result = {}NEWLINE for i in range(0, len(ids)):NEWLINE id = ids[i]NEWLINE market = self.markets_by_id[id]NEWLINE symbol = market['symbol']NEWLINE ticker = tickers[id]NEWLINE result[symbol] = self.parse_ticker(ticker, market)NEWLINE return resultNEWLINENEWLINE async def fetch_ticker(self, symbol, params={}):NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE ticker = await self.publicGetTicker(self.extend({NEWLINE 'pair': market['id'],NEWLINE }, params))NEWLINE return self.parse_ticker(ticker, market)NEWLINENEWLINE def parse_trade(self, trade, market):NEWLINE # For public trade data(is_buy is True) indicates 'buy' side but for private trade dataNEWLINE # is_buy indicates maker or taker. The value of "type"(ASK/BID) indicate sell/buy side.NEWLINE # Private trade data includes ID field which public trade data does not.NEWLINE order = self.safe_string(trade, 'order_id')NEWLINE takerOrMaker = NoneNEWLINE side = NoneNEWLINE if order is not None:NEWLINE side = 'sell' if (trade['type'] == 'ASK') else 'buy'NEWLINE if side == 'sell' and trade['is_buy']:NEWLINE takerOrMaker = 'maker'NEWLINE elif side == 'buy' and not trade['is_buy']:NEWLINE takerOrMaker = 'maker'NEWLINE else:NEWLINE takerOrMaker = 'taker'NEWLINE else:NEWLINE side = 'buy' if (trade['is_buy']) else 'sell'NEWLINE feeBase = self.safe_float(trade, 'fee_base')NEWLINE feeCounter = self.safe_float(trade, 'fee_counter')NEWLINE feeCurrency = NoneNEWLINE feeCost = NoneNEWLINE if feeBase is not None:NEWLINE if feeBase != 0.0:NEWLINE feeCurrency = market['base']NEWLINE feeCost = feeBaseNEWLINE elif feeCounter is not None:NEWLINE if feeCounter != 0.0:NEWLINE feeCurrency = market['quote']NEWLINE feeCost = feeCounterNEWLINE return {NEWLINE 'info': trade,NEWLINE 'id': None,NEWLINE 'timestamp': trade['timestamp'],NEWLINE 'datetime': self.iso8601(trade['timestamp']),NEWLINE 'symbol': market['symbol'],NEWLINE 'order': order,NEWLINE 'type': None,NEWLINE 'side': side,NEWLINE 'takerOrMaker': takerOrMaker,NEWLINE 'price': self.safe_float(trade, 'price'),NEWLINE 'amount': self.safe_float(trade, 'volume'),NEWLINE # Does not include potential fee costsNEWLINE 'cost': self.safe_float(trade, 'counter'),NEWLINE 'fee': {NEWLINE 'cost': feeCost,NEWLINE 'currency': feeCurrency,NEWLINE },NEWLINE }NEWLINENEWLINE async def fetch_trades(self, symbol, since=None, limit=None, params={}):NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE request = {NEWLINE 'pair': market['id'],NEWLINE }NEWLINE if since is not None:NEWLINE request['since'] = sinceNEWLINE response = await self.publicGetTrades(self.extend(request, params))NEWLINE trades = self.safe_value(response, 'trades', [])NEWLINE return self.parse_trades(trades, market, since, limit)NEWLINENEWLINE async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):NEWLINE if symbol is None:NEWLINE raise ArgumentsRequired(self.id + ' fetchMyTrades requires a symbol argument')NEWLINE await self.load_markets()NEWLINE market = self.market(symbol)NEWLINE request = {NEWLINE 'pair': market['id'],NEWLINE }NEWLINE if since is not None:NEWLINE request['since'] = sinceNEWLINE if limit is not None:NEWLINE request['limit'] = limitNEWLINE response = await self.privateGetListtrades(self.extend(request, params))NEWLINE trades = self.safe_value(response, 'trades', [])NEWLINE return self.parse_trades(trades, market, since, limit)NEWLINENEWLINE async def fetch_trading_fees(self, params={}):NEWLINE await self.load_markets()NEWLINE response = await self.privateGetFeeInfo(params)NEWLINE return {NEWLINE 'info': response,NEWLINE 'maker': self.safe_float(response, 'maker_fee'),NEWLINE 'taker': self.safe_float(response, 'taker_fee'),NEWLINE }NEWLINENEWLINE async def create_order(self, symbol, type, side, amount, price=None, params={}):NEWLINE await self.load_markets()NEWLINE method = 'privatePost'NEWLINE order = {'pair': self.market_id(symbol)}NEWLINE if type == 'market':NEWLINE method += 'Marketorder'NEWLINE order['type'] = side.upper()NEWLINE if side == 'buy':NEWLINE order['counter_volume'] = amountNEWLINE else:NEWLINE order['base_volume'] = amountNEWLINE else:NEWLINE method += 'Postorder'NEWLINE order['volume'] = amountNEWLINE order['price'] = priceNEWLINE if side == 'buy':NEWLINE order['type'] = 'BID'NEWLINE else:NEWLINE order['type'] = 'ASK'NEWLINE response = await getattr(self, method)(self.extend(order, params))NEWLINE return {NEWLINE 'info': response,NEWLINE 'id': response['order_id'],NEWLINE }NEWLINENEWLINE async def cancel_order(self, id, symbol=None, params={}):NEWLINE await self.load_markets()NEWLINE return await self.privatePostStoporder({'order_id': id})NEWLINENEWLINE def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):NEWLINE url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)NEWLINE query = self.omit(params, self.extract_params(path))NEWLINE if query:NEWLINE url += '?' + self.urlencode(query)NEWLINE if api == 'private':NEWLINE self.check_required_credentials()NEWLINE auth = self.encode(self.apiKey + ':' + self.secret)NEWLINE auth = base64.b64encode(auth)NEWLINE headers = {'Authorization': 'Basic ' + self.decode(auth)}NEWLINE return {'url': url, 'method': method, 'body': body, 'headers': headers}NEWLINENEWLINE async def request(self, path, api='public', method='GET', params={}, headers=None, body=None):NEWLINE response = await self.fetch2(path, api, method, params, headers, body)NEWLINE if 'error' in response:NEWLINE raise ExchangeError(self.id + ' ' + self.json(response))NEWLINE return responseNEWLINE |
#! /usr/bin/python3NEWLINENEWLINE"""Create and parse 'send'-type messages."""NEWLINENEWLINEimport structNEWLINEimport jsonNEWLINEimport loggingNEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINEfrom ... import (config, exceptions, util, message_type)NEWLINENEWLINEFORMAT = '>QQ'NEWLINELENGTH = 8 + 8NEWLINEID = 0NEWLINENEWLINEdef unpack(db, message, block_index):NEWLINE # Only used for `unpack` API call at the moment.NEWLINE try:NEWLINE asset_id, quantity = struct.unpack(FORMAT, message)NEWLINE asset = util.get_asset_name(db, asset_id, block_index)NEWLINENEWLINE except struct.error:NEWLINE raise exceptions.UnpackError('could not unpack')NEWLINENEWLINE except AssetNameError:NEWLINE raise exceptions.UnpackError('asset id invalid')NEWLINENEWLINE unpacked = {NEWLINE 'asset': asset,NEWLINE 'quantity': quantityNEWLINE }NEWLINE return unpackedNEWLINENEWLINEdef validate (db, source, destination, asset, quantity, block_index):NEWLINE problems = []NEWLINENEWLINE if asset == config.BTC: problems.append('cannot send bitcoins') # Only for parsing.NEWLINENEWLINE if not isinstance(quantity, int):NEWLINE problems.append('quantity must be in satoshis')NEWLINE return problemsNEWLINENEWLINE if quantity < 0:NEWLINE problems.append('negative quantity')NEWLINENEWLINE # For SQLite3NEWLINE if quantity > config.MAX_INT:NEWLINE problems.append('integer overflow')NEWLINENEWLINE if util.enabled('send_destination_required'): # Protocol change.NEWLINE if not destination:NEWLINE problems.append('destination is required')NEWLINENEWLINE if util.enabled('options_require_memo'):NEWLINE # Check destination address optionsNEWLINENEWLINE cursor = db.cursor()NEWLINE results = cursor.execute('SELECT options FROM addresses WHERE address=?', (destination,))NEWLINE if results:NEWLINE result = results.fetchone()NEWLINE if result and util.active_options(result['options'], config.ADDRESS_OPTION_REQUIRE_MEMO):NEWLINE problems.append('destination requires memo')NEWLINE cursor.close()NEWLINENEWLINE return problemsNEWLINENEWLINEdef compose (db, source, destination, asset, quantity):NEWLINE cursor = db.cursor()NEWLINENEWLINE # Just send BTC?NEWLINE if asset == config.BTC:NEWLINE return (source, [(destination, quantity)], None)NEWLINENEWLINE # resolve subassetsNEWLINE asset = util.resolve_subasset_longname(db, asset)NEWLINENEWLINE #quantity must be in int satoshi (not float, string, etc)NEWLINE if not isinstance(quantity, int):NEWLINE raise exceptions.ComposeError('quantity must be an int (in satoshi)')NEWLINENEWLINE # Only for outgoing (incoming will overburn).NEWLINE balances = list(cursor.execute('''SELECT * FROM balances WHERE (address = ? AND asset = ?)''', (source, asset)))NEWLINE if not balances or balances[0]['quantity'] < quantity:NEWLINE raise exceptions.ComposeError('insufficient funds')NEWLINENEWLINE block_index = util.CURRENT_BLOCK_INDEXNEWLINENEWLINE problems = validate(db, source, destination, asset, quantity, block_index)NEWLINE if problems: raise exceptions.ComposeError(problems)NEWLINENEWLINE asset_id = util.get_asset_id(db, asset, block_index)NEWLINE data = message_type.pack(ID)NEWLINE data += struct.pack(FORMAT, asset_id, quantity)NEWLINENEWLINE cursor.close()NEWLINE return (source, [(destination, None)], data)NEWLINENEWLINEdef parse (db, tx, message):NEWLINE cursor = db.cursor()NEWLINENEWLINE # Unpack message.NEWLINE try:NEWLINE if len(message) != LENGTH:NEWLINE raise exceptions.UnpackErrorNEWLINE asset_id, quantity = struct.unpack(FORMAT, message)NEWLINE asset = util.get_asset_name(db, asset_id, tx['block_index'])NEWLINE status = 'valid'NEWLINE except (exceptions.UnpackError, exceptions.AssetNameError, struct.error) as e:NEWLINE asset, quantity = None, NoneNEWLINE status = 'invalid: could not unpack'NEWLINENEWLINE if status == 'valid':NEWLINE # OversendNEWLINE cursor.execute('''SELECT * FROM balances \NEWLINE WHERE (address = ? AND asset = ?)''', (tx['source'], asset))NEWLINE balances = cursor.fetchall()NEWLINE if not balances:NEWLINE status = 'invalid: insufficient funds'NEWLINE elif balances[0]['quantity'] < quantity:NEWLINE quantity = min(balances[0]['quantity'], quantity)NEWLINENEWLINE # For SQLite3NEWLINE if quantity:NEWLINE quantity = min(quantity, config.MAX_INT)NEWLINENEWLINE if status == 'valid':NEWLINE problems = validate(db, tx['source'], tx['destination'], asset, quantity, tx['block_index'])NEWLINE if problems: status = 'invalid: ' + '; '.join(problems)NEWLINENEWLINE if status == 'valid':NEWLINE util.debit(db, tx['source'], asset, quantity, action='send', event=tx['tx_hash'])NEWLINE util.credit(db, tx['destination'], asset, quantity, action='send', event=tx['tx_hash'])NEWLINENEWLINE # Add parsed transaction to message-type–specific table.NEWLINE bindings = {NEWLINE 'tx_index': tx['tx_index'],NEWLINE 'tx_hash': tx['tx_hash'],NEWLINE 'block_index': tx['block_index'],NEWLINE 'source': tx['source'],NEWLINE 'destination': tx['destination'],NEWLINE 'asset': asset,NEWLINE 'quantity': quantity,NEWLINE 'status': status,NEWLINE }NEWLINE if "integer overflow" not in status and "quantity must be in satoshis" not in status:NEWLINE sql = 'insert into sends (tx_index, tx_hash, block_index, source, destination, asset, quantity, status, memo) values(:tx_index, :tx_hash, :block_index, :source, :destination, :asset, :quantity, :status, NULL)'NEWLINE cursor.execute(sql, bindings)NEWLINE else:NEWLINE logger.warn("Not storing [send] tx [%s]: %s" % (tx['tx_hash'], status))NEWLINE logger.debug("Bindings: %s" % (json.dumps(bindings), ))NEWLINENEWLINENEWLINE cursor.close()NEWLINENEWLINE# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4NEWLINE |
from neo.Prompt.Commands.Invoke import InvokeContract, InvokeWithTokenVerificationScriptNEWLINEfrom neo.Core.Fixed8 import Fixed8NEWLINEfrom neo.Core.UInt160 import UInt160NEWLINEfrom neo.Network.common import blocking_prompt as promptNEWLINEfrom decimal import DecimalNEWLINEfrom neo.Core.TX.TransactionAttribute import TransactionAttributeNEWLINEimport binasciiNEWLINEfrom neo.Prompt.CommandBase import CommandBase, CommandDesc, ParameterDescNEWLINEfrom neo.Prompt.PromptData import PromptDataNEWLINEfrom neo.Prompt import Utils as PromptUtilsNEWLINEfrom neo.Implementations.Wallets.peewee.Models import NEP5Token as ModelNEP5TokenNEWLINEfrom neo.Implementations.Notifications.NotificationDB import NotificationDBNEWLINEfrom neo.Core.TX.TransactionAttribute import TransactionAttributeUsageNEWLINEfrom neo.Core.Utils import isValidPublicAddressNEWLINEimport peeweeNEWLINEimport tracebackNEWLINEfrom neo.Prompt.PromptPrinter import prompt_print as printNEWLINEfrom neo.logging import log_managerNEWLINENEWLINElogger = log_manager.getLogger()NEWLINENEWLINENEWLINEclass CommandWalletToken(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINE self.register_sub_command(CommandTokenDelete())NEWLINE self.register_sub_command(CommandTokenSend())NEWLINE self.register_sub_command(CommandTokenSendFrom())NEWLINE self.register_sub_command(CommandTokenHistory())NEWLINE self.register_sub_command(CommandTokenApprove())NEWLINE self.register_sub_command(CommandTokenAllowance())NEWLINE self.register_sub_command(CommandTokenMint())NEWLINE self.register_sub_command(CommandTokenRegister())NEWLINENEWLINE def command_desc(self):NEWLINE return CommandDesc('token', 'various token operations')NEWLINENEWLINE def execute(self, arguments):NEWLINE item = PromptUtils.get_arg(arguments)NEWLINENEWLINE if not item:NEWLINE print(f"run `{self.command_desc().command} help` to see supported queries")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE return self.execute_sub_command(item, arguments[1:])NEWLINE except KeyError:NEWLINE print(f"{item} is an invalid parameter")NEWLINE return FalseNEWLINENEWLINENEWLINEclass CommandTokenDelete(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 1:NEWLINE print("Please specify the required parameter")NEWLINE return FalseNEWLINENEWLINE hash_string = arguments[0]NEWLINE try:NEWLINE script_hash = UInt160.ParseString(hash_string)NEWLINE except Exception:NEWLINE # because UInt160 throws a generic exception. Should be fixed in the futureNEWLINE print("Invalid script hash")NEWLINE return FalseNEWLINENEWLINE # try to find token and collect some dataNEWLINE try:NEWLINE token = ModelNEP5Token.get(ContractHash=script_hash)NEWLINE except peewee.DoesNotExist:NEWLINE print(f"Could not find a token with script_hash {arguments[0]}")NEWLINE return FalseNEWLINENEWLINE success = wallet.DeleteNEP5Token(script_hash)NEWLINE if success:NEWLINE print(f"Token {token.Symbol} with script_hash {arguments[0]} deleted")NEWLINE else:NEWLINE # probably unreachable to due token check earlier. Better safe than sorrowNEWLINE print(f"Could not find a token with script_hash {arguments[0]}")NEWLINENEWLINE return successNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('contract', 'token contract hash (script hash)')NEWLINE return CommandDesc('delete', 'remove a token from the wallet', [p1])NEWLINENEWLINENEWLINEclass CommandTokenSend(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE if len(arguments) > 6:NEWLINE # the 5th and 6th arguments are optionalNEWLINE print("Too many parameters supplied. Please check your command")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINE arguments, user_tx_attributes = PromptUtils.get_tx_attr_from_args(arguments)NEWLINENEWLINE token = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE fee = priority_feeNEWLINE if fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE success = token_send(wallet, token, from_addr, to_addr, amount, fee=fee, user_tx_attributes=user_tx_attributes)NEWLINE except ValueError as e:NEWLINE # occurs if arguments are invalidNEWLINE print(str(e))NEWLINE success = FalseNEWLINENEWLINE return successNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('token', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE p6 = ParameterDesc('--tx-attr', f"a list of transaction attributes to attach to the transaction\n\n"NEWLINE f"{' ':>17} See: http://docs.neo.org/en-us/network/network-protocol.html section 4 for a description of possible attributes\n\n" # noqa: E128 ignore indentationNEWLINE f"{' ':>17} Example:\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": <value>,\"data\":\"<remark>\"}}, ...]\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": 0x90,\"data\":\"my brief description\"}}]\n", optional=True)NEWLINENEWLINE return CommandDesc('send', 'send a token from the wallet', [p1, p2, p3, p4, p5, p6])NEWLINENEWLINENEWLINEclass CommandTokenSendFrom(CommandBase):NEWLINE """NEWLINE This command is for old style NEP-5 tokens before the proposal got amended to remove this optional command.NEWLINE """NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token, tx, fee, results = test_token_send_from(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError as e:NEWLINE # invalid arguments or bad allowanceNEWLINE print(str(e))NEWLINE return FalseNEWLINE except Exception as e:NEWLINE # we act as the final capturing placeNEWLINE print("Something really unexpected happened")NEWLINE logger.error(traceback.format_exc())NEWLINE return FalseNEWLINENEWLINE if tx is not None and results is not None:NEWLINE vm_result = results[0].GetBigInteger()NEWLINE if vm_result == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("Transfer of %s %s from %s to %s" % (NEWLINE string_from_amount(token, amount), token.symbol, from_addr, to_addr))NEWLINE print("Transfer fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Transfer Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Transaction cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print(f"Could not transfer tokens. Virtual machine returned: {vm_result}")NEWLINE return FalseNEWLINENEWLINE print(f"Could not transfer tokens. An unknown error occurred resulting in no Transaction object or VM output.")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('token', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINENEWLINE return CommandDesc('sendfrom', 'send a token on behalf of another account (requires approval)', [p1, p2, p3, p4, p5])NEWLINENEWLINENEWLINEclass CommandTokenHistory(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 1:NEWLINE print("Please specify the required parameter")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token, events = token_history(wallet, arguments[0])NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE if events:NEWLINE addresses = wallet.AddressesNEWLINE print("-----------------------------------------------------------")NEWLINE print("Recent transaction history (last = more recent):")NEWLINE for event in events:NEWLINE if event.Type != 'transfer':NEWLINE continueNEWLINE if event.AddressFrom in addresses:NEWLINE print(f"[{event.AddressFrom}]: Sent {string_from_amount(token, event.Amount)}"NEWLINE f" {token.symbol} to {event.AddressTo}")NEWLINE if event.AddressTo in addresses:NEWLINE print(f"[{event.AddressTo}]: Received {string_from_amount(token, event.Amount)}"NEWLINE f" {token.symbol} from {event.AddressFrom}")NEWLINE print("-----------------------------------------------------------")NEWLINE else:NEWLINE print("History contains no transactions")NEWLINE return TrueNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE return CommandDesc('history', 'show transaction history', [p1])NEWLINENEWLINENEWLINEclass CommandTokenApprove(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 4:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE amount = float(arguments[3])NEWLINE except ValueError:NEWLINE print(f"{arguments[3]} is not a valid amount")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE decimal_amount = amount_from_string(token, amount)NEWLINENEWLINE tx, fee, results = token.Approve(wallet, from_addr, to_addr, decimal_amount)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if results[0].GetBigInteger() == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print(f"Approve allowance of {amount} {token.symbol} from {from_addr} to {to_addr}")NEWLINE print(f"Invocation fee: {fee.value / Fixed8.D}")NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Allowance approval cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("Failed to approve tokens. Make sure you are entitled for approving.")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINE p4 = ParameterDesc('amount', 'number of tokens to send')NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINENEWLINE return CommandDesc('approve', 'approve an allowance', [p1, p2, p3, p4, p5])NEWLINENEWLINE def handle_help(self, arguments):NEWLINE super().handle_help(arguments)NEWLINE print(NEWLINE "\nThis is an optional NEP-5 command (now legacy).\nFor more information see https://github.com/neo-project/proposals/blob/c357f5965afc2155615b6b96c7d15da688f81982/nep-5.mediawiki#approve_optional")NEWLINENEWLINENEWLINEclass CommandTokenAllowance(CommandBase):NEWLINENEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) != 3:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE token_str = arguments[0]NEWLINE from_addr = arguments[1]NEWLINE to_addr = arguments[2]NEWLINENEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE try:NEWLINE allowance = token_get_allowance(wallet, token_str, from_addr, to_addr)NEWLINE print(f"{token.symbol} allowance for {from_addr} from {to_addr} : {allowance} ")NEWLINE return TrueNEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('from_addr', 'address to send token from')NEWLINE p3 = ParameterDesc('to_addr', 'address to send token to')NEWLINENEWLINE return CommandDesc('allowance', 'get the amount an account can transfer from another acount', [p1, p2, p3])NEWLINENEWLINENEWLINEclass CommandTokenMint(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 2:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE if len(arguments) > 6:NEWLINE # the 3rd and 4th argument are for attaching neo/gas, 5th for attaching a fee, 6th for attaching attributesNEWLINE print("Too many parameters supplied. Please check your command")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINE arguments, invoke_attrs = PromptUtils.get_tx_attr_from_args(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE to_addr = arguments[1]NEWLINE if not isValidPublicAddress(to_addr):NEWLINE print(f"{to_addr} is not a valid address")NEWLINE return FalseNEWLINENEWLINE remaining_args = arguments[2:]NEWLINE asset_attachments = []NEWLINE for optional in remaining_args:NEWLINE _, neo_to_attach, gas_to_attach = PromptUtils.get_asset_attachments([optional])NEWLINENEWLINE if "attach-neo" in optional:NEWLINE if not neo_to_attach:NEWLINE print(f"Could not parse value from --attach-neo. Value must be an integer")NEWLINE return FalseNEWLINE else:NEWLINE asset_attachments.append(optional)NEWLINENEWLINE if "attach-gas" in optional:NEWLINE if not gas_to_attach:NEWLINE print(f"Could not parse value from --attach-gas")NEWLINE return FalseNEWLINE else:NEWLINE asset_attachments.append(optional)NEWLINENEWLINE fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE fee = priority_feeNEWLINE if fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE return token_mint(token, wallet, to_addr, asset_attachments=asset_attachments, fee=fee, invoke_attrs=invoke_attrs)NEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('to_addr', 'address to mint tokens to')NEWLINE p3 = ParameterDesc('--attach-neo', 'amount of neo to attach to the transaction', optional=True)NEWLINE p4 = ParameterDesc('--attach-gas', 'amount of gas to attach to the transaction', optional=True)NEWLINE p5 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE p6 = ParameterDesc('--tx-attr', f"a list of transaction attributes to attach to the transaction\n\n"NEWLINE f"{' ':>17} See: http://docs.neo.org/en-us/network/network-protocol.html section 4 for a description of possible attributes\n\n" # noqa: E128 ignore indentationNEWLINE f"{' ':>17} Example:\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": <value>,\"data\":\"<remark>\"}}, ...]\n"NEWLINE f"{' ':>20} --tx-attr=[{{\"usage\": 0x90,\"data\":\"my brief description\"}}]\n", optional=True)NEWLINENEWLINE return CommandDesc('mint', 'mint tokens from a contract', [p1, p2, p3, p4, p5, p6])NEWLINENEWLINENEWLINEclass CommandTokenRegister(CommandBase):NEWLINE def __init__(self):NEWLINE super().__init__()NEWLINENEWLINE def execute(self, arguments):NEWLINE wallet = PromptData.WalletNEWLINENEWLINE if len(arguments) < 2:NEWLINE print("Please specify the required parameters")NEWLINE return FalseNEWLINENEWLINE arguments, priority_fee = PromptUtils.get_fee(arguments)NEWLINENEWLINE token_str = arguments[0]NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError as e:NEWLINE print(str(e))NEWLINE return FalseNEWLINENEWLINE register_addr = arguments[1:]NEWLINE addr_list = []NEWLINE for addr in register_addr:NEWLINE if isValidPublicAddress(addr):NEWLINE addr_list.append(addr)NEWLINE else:NEWLINE print(f"{addr} is not a valid address")NEWLINE return FalseNEWLINENEWLINE p_fee = Fixed8.Zero()NEWLINE if priority_fee is not None:NEWLINE p_fee = priority_feeNEWLINE if p_fee is False:NEWLINE logger.debug("invalid fee")NEWLINE return FalseNEWLINENEWLINE tx, fee, results = token.CrowdsaleRegister(wallet, addr_list)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if len(results) > 0 and results[0].GetBigInteger() > 0:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("[%s] Will register addresses for crowdsale: %s " % (token.symbol, register_addr))NEWLINE print("Invocation Fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Registration cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("Could not register address(es)")NEWLINE return FalseNEWLINENEWLINE def command_desc(self):NEWLINE p1 = ParameterDesc('symbol', 'token symbol or script hash')NEWLINE p2 = ParameterDesc('addresses', 'space separated list of NEO addresses')NEWLINE p3 = ParameterDesc('--fee', 'Attach GAS amount to give your transaction priority (> 0.001) e.g. --fee=0.01', optional=True)NEWLINE return CommandDesc('register', 'register for a crowd sale', [p1, p2, p3])NEWLINENEWLINENEWLINEdef _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount):NEWLINE """NEWLINE A helper function to validate common arguments used in NEP-5 functionsNEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid argumentsNEWLINENEWLINE Returns:NEWLINE token (NEP5Token): instanceNEWLINE """NEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE if not isValidPublicAddress(from_addr):NEWLINE raise ValueError("send_from is not a valid address")NEWLINENEWLINE if not isValidPublicAddress(to_addr):NEWLINE raise ValueError("send_to is not a valid address")NEWLINENEWLINE try:NEWLINE # internally this function uses the `Decimal` class which will parse the float amount to its required format.NEWLINE # the name is a bit misleading /shrugNEWLINE amount = amount_from_string(token, amount)NEWLINE except Exception:NEWLINE raise ValueError(f"{amount} is not a valid amount")NEWLINENEWLINE return tokenNEWLINENEWLINENEWLINEdef token_send(wallet, token_str, from_addr, to_addr, amount, fee=Fixed8.Zero(), user_tx_attributes=None):NEWLINE """NEWLINE Send `amount` of tokens from `from_addr` to `to_addr`NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINE fee (Fixed8): (optional) a fee to give the transaction priority (> 0.001) NEWLINE user_tx_attributes (list): a list of ``TransactionAttribute``s.NEWLINENEWLINE Raises:NEWLINE ValueError: for invalid argumentsNEWLINENEWLINE Returns:NEWLINE a Transaction object if successful, False otherwise.NEWLINE """NEWLINE if not user_tx_attributes:NEWLINE user_tx_attributes = []NEWLINENEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE except ValueError:NEWLINE # just making it explicit for the readerNEWLINE raiseNEWLINENEWLINE for attr in user_tx_attributes:NEWLINE if not isinstance(attr, TransactionAttribute):NEWLINE raise ValueError(f"{attr} is not a valid transaction attribute")NEWLINENEWLINE decimal_amount = amount_from_string(token, amount)NEWLINENEWLINE return do_token_transfer(token, wallet, from_addr, to_addr, decimal_amount, fee=fee, tx_attributes=user_tx_attributes)NEWLINENEWLINENEWLINEdef test_token_send_from(wallet, token_str, from_addr, to_addr, amount):NEWLINE """NEWLINE Test sending funds from `addr_from` to `addr_to` without commiting to the network.NEWLINENEWLINE This does a local test to validate all supplied arguments and if the blockchain state allows for the transfer.NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE amount (float): the number of tokens to sendNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid arguments or if allowance is insufficient.NEWLINENEWLINE Returns:NEWLINE tuple:NEWLINE token (NEP5Token): instanceNEWLINE InvocationTransaction: the transaction.NEWLINE int: the transaction fee.NEWLINE list: the neo VM evaluation stack results.NEWLINE """NEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount)NEWLINE allowance = token_get_allowance(wallet, token_str, from_addr, to_addr, verbose=False)NEWLINENEWLINE if allowance < amount:NEWLINE raise ValueError(f"Insufficient allowance: {allowance}")NEWLINE except ValueError:NEWLINE # bad args or allowanceNEWLINE raiseNEWLINENEWLINE tx, fees, results = token.TransferFrom(wallet, from_addr, to_addr, amount)NEWLINE return token, tx, fees, resultsNEWLINENEWLINENEWLINEdef token_get_allowance(wallet, token_str, from_addr, to_addr, verbose=False):NEWLINE """NEWLINE Query the smart contract for the amount from_addr is allowed to send to to_addrNEWLINENEWLINE Requires amount to be `approved`.NEWLINENEWLINE Args:NEWLINE wallet (Wallet): a UserWallet instanceNEWLINE token_str (str): symbol name or script_hashNEWLINE from_addr (str): a wallet addressNEWLINE to_addr (str): a wallet addressNEWLINE verbose (bool): flag indicating whether to print VM resultsNEWLINENEWLINE Raises:NEWLINE ValueError: for invalid arguments or if allowance could not be queriedNEWLINENEWLINE Returns:NEWLINE int: allowanceNEWLINE """NEWLINE try:NEWLINE token = _validate_nep5_args(wallet, token_str, from_addr, to_addr, amount=0)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE tx, fee, results = token.Allowance(wallet, from_addr, to_addr)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE allowance = results[0].GetBigInteger()NEWLINE if verbose:NEWLINE print("%s allowance for %s from %s : %s " % (token.symbol, from_addr, to_addr, allowance))NEWLINENEWLINE return allowanceNEWLINE else:NEWLINE if verbose:NEWLINE print("Could not get allowance for token %s " % token.symbol)NEWLINE raise ValueError(f"Could not get allowance for token {token.symbol}")NEWLINENEWLINENEWLINEdef token_mint(token, wallet, to_addr, asset_attachments=[], fee=Fixed8.Zero(), invoke_attrs=None):NEWLINE if not invoke_attrs:NEWLINE invoke_attrs = []NEWLINENEWLINE p_fee = feeNEWLINENEWLINE tx, fee, results = token.Mint(wallet, to_addr, asset_attachments, invoke_attrs=invoke_attrs)NEWLINENEWLINE if tx is not None and results is not None:NEWLINE if len(results) > 0 and results[0] is not None:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print(f"[{token.symbol}] Will mint tokens to address: {to_addr}")NEWLINE print(f"Invocation Fee: {fee.value / Fixed8.D}")NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Invocation Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Token mint cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeWithTokenVerificationScript(wallet, tx, token, comb_fee, invoke_attrs=invoke_attrs)NEWLINENEWLINE print("Failed to mint tokens")NEWLINE return FalseNEWLINENEWLINENEWLINEdef do_token_transfer(token, wallet, from_address, to_address, amount, fee=Fixed8.Zero(), tx_attributes=None):NEWLINE if not tx_attributes:NEWLINE tx_attributes = []NEWLINENEWLINE p_fee = feeNEWLINENEWLINE # because we cannot differentiate between a normal and multisig from_addr, and because we want to makeNEWLINE # sending NEP5 tokens straight forward even when sending from multisig addresses, we include the script_hashNEWLINE # for verification by default to the transaction attributes. See PR/Issue: https://github.com/CityOfZion/neo-python/pull/491NEWLINE from_script_hash = binascii.unhexlify(bytes(wallet.ToScriptHash(from_address).ToString2(), 'utf-8'))NEWLINE tx_attributes.append(TransactionAttribute(usage=TransactionAttributeUsage.Script, data=from_script_hash))NEWLINENEWLINE tx, fee, results = token.Transfer(wallet, from_address, to_address, amount, tx_attributes=tx_attributes)NEWLINENEWLINE if tx is not None and results is not None and len(results) > 0:NEWLINENEWLINE if results[0].GetBigInteger() == 1:NEWLINE print("\n-----------------------------------------------------------")NEWLINE print("Will transfer %s %s from %s to %s" % (string_from_amount(token, amount), token.symbol, from_address, to_address))NEWLINE print("Transfer fee: %s " % (fee.value / Fixed8.D))NEWLINE print("-------------------------------------------------------------\n")NEWLINE comb_fee = p_fee + feeNEWLINE if comb_fee != fee:NEWLINE print(f"Priority Fee ({p_fee.value / Fixed8.D}) + Transfer Fee ({fee.value / Fixed8.D}) = {comb_fee.value / Fixed8.D}\n")NEWLINE print("Enter your password to send to the network")NEWLINENEWLINE try:NEWLINE passwd = prompt("[Password]> ", is_password=True)NEWLINE except KeyboardInterrupt:NEWLINE print("Transfer cancelled")NEWLINE return FalseNEWLINE if not wallet.ValidatePassword(passwd):NEWLINE print("incorrect password")NEWLINE return FalseNEWLINENEWLINE return InvokeContract(wallet, tx, comb_fee)NEWLINENEWLINE print("could not transfer tokens")NEWLINE return FalseNEWLINENEWLINENEWLINEdef token_history(wallet, token_str):NEWLINE notification_db = NotificationDB.instance()NEWLINENEWLINE try:NEWLINE token = PromptUtils.get_token(wallet, token_str)NEWLINE except ValueError:NEWLINE raiseNEWLINENEWLINE events = notification_db.get_by_contract(token.ScriptHash)NEWLINE return token, eventsNEWLINENEWLINENEWLINEdef amount_from_string(token, amount_str):NEWLINE precision_mult = pow(10, token.decimals)NEWLINE amount = Decimal(amount_str) * precision_multNEWLINENEWLINE return int(amount)NEWLINENEWLINENEWLINEdef string_from_amount(token, amount):NEWLINE precision_mult = pow(10, token.decimals)NEWLINE amount = Decimal(amount) / Decimal(precision_mult)NEWLINE formatter_str = '.%sf' % token.decimalsNEWLINE amount_str = format(amount, formatter_str)NEWLINENEWLINE return amount_strNEWLINE |
#!/usr/bin/env python3NEWLINE"""NEWLINEpixivNEWLINENEWLINEUsage:NEWLINE pixiv.pyNEWLINE pixiv.py <id>...NEWLINE pixiv.py -r [-d | --date=<date>]NEWLINE pixiv.py -uNEWLINENEWLINEArguments:NEWLINE <id> user_idsNEWLINENEWLINEOptions:NEWLINE -r Download by rankingNEWLINE -d <date> --date <date> Target dateNEWLINE -u Update exist folderNEWLINE -h --help Show this screenNEWLINE -v --version Show versionNEWLINENEWLINEExamples:NEWLINE pixiv.py 7210261 1980643NEWLINE pixiv.py -r -d 2016-09-24NEWLINE"""NEWLINEimport datetimeNEWLINEimport mathNEWLINEimport osNEWLINEimport queueNEWLINEimport reNEWLINEimport sysNEWLINEimport threadingNEWLINEimport timeNEWLINEimport tracebackNEWLINENEWLINEimport requestsNEWLINEfrom docopt import docoptNEWLINEfrom tqdm import tqdmNEWLINENEWLINEfrom api import PixivApiNEWLINEfrom i18n import i18n as _NEWLINEfrom model import PixivIllustModelNEWLINENEWLINE_THREADING_NUMBER = 10NEWLINE_finished_download = 0NEWLINE_CREATE_FOLDER_LOCK = threading.Lock()NEWLINE_PROGRESS_LOCK = threading.Lock()NEWLINE_SPEED_LOCK = threading.Lock()NEWLINE_Global_Download = 0NEWLINE_error_count = {}NEWLINE_ILLUST_PER_PAGE = 30NEWLINE_MAX_ERROR_COUNT = 5NEWLINENEWLINENEWLINEdef get_default_save_path():NEWLINE current_path = os.path.dirname(os.path.abspath(sys.argv[0]))NEWLINE filepath = os.path.join(current_path, 'illustrations')NEWLINE if not os.path.exists(filepath):NEWLINE with _CREATE_FOLDER_LOCK:NEWLINE if not os.path.exists(os.path.dirname(filepath)):NEWLINE os.makedirs(os.path.dirname(filepath))NEWLINE os.makedirs(filepath)NEWLINE return filepathNEWLINENEWLINENEWLINEdef get_speed(elapsed):NEWLINE """Get current download speed"""NEWLINE with _SPEED_LOCK:NEWLINE global _Global_DownloadNEWLINE down = _Global_DownloadNEWLINE _Global_Download = 0NEWLINE speed = down / elapsedNEWLINE if speed == 0:NEWLINE return '%8.2f /s' % 0NEWLINE units = [' B', 'KB', 'MB', 'GB', 'TB', 'PB']NEWLINE unit = math.floor(math.log(speed, 1024.0))NEWLINE speed /= math.pow(1024.0, unit)NEWLINE return '%6.2f %s/s' % (speed, units[unit])NEWLINENEWLINENEWLINEdef print_progress(max_size):NEWLINE global _finished_downloadNEWLINE pbar = tqdm(total=max_size)NEWLINENEWLINE last = 0NEWLINE while _finished_download != max_size:NEWLINE pbar.update(_finished_download - last)NEWLINE last = _finished_downloadNEWLINE time.sleep(0.5)NEWLINE pbar.update(_finished_download - last)NEWLINE pbar.close()NEWLINENEWLINENEWLINEdef download_file(url, filepath):NEWLINE headers = {'Referer': 'http://www.pixiv.net/'}NEWLINE r = requests.get(url, headers=headers, stream=True, timeout=PixivApi.timeout)NEWLINE if r.status_code == requests.codes.ok:NEWLINE total_length = r.headers.get('content-length')NEWLINE if total_length:NEWLINE data = []NEWLINE for chunk in r.iter_content(1024 * 16):NEWLINE data.append(chunk)NEWLINE with _SPEED_LOCK:NEWLINE global _Global_DownloadNEWLINE _Global_Download += len(chunk)NEWLINE with open(filepath, 'wb') as f:NEWLINE list(map(f.write, data))NEWLINE else:NEWLINE raise ConnectionError('\r', _('Connection error: %s') % r.status_code)NEWLINENEWLINENEWLINEdef download_threading(download_queue):NEWLINE global _finished_downloadNEWLINE while not download_queue.empty():NEWLINE illustration = download_queue.get()NEWLINE filepath = illustration['path']NEWLINE filename = illustration['file']NEWLINE url = illustration['url']NEWLINE count = _error_count.get(url, 0)NEWLINE if count < _MAX_ERROR_COUNT:NEWLINE if not os.path.exists(filepath):NEWLINE with _CREATE_FOLDER_LOCK:NEWLINE if not os.path.exists(os.path.dirname(filepath)):NEWLINE os.makedirs(os.path.dirname(filepath))NEWLINE try:NEWLINE download_file(url, filepath)NEWLINE with _PROGRESS_LOCK:NEWLINE _finished_download += 1NEWLINE except Exception as e:NEWLINE if count < _MAX_ERROR_COUNT:NEWLINE print(_('%s => %s download error, retry') % (e, filename))NEWLINE download_queue.put(illustration)NEWLINE _error_count[url] = count + 1NEWLINE else:NEWLINE print(url, 'reach max retries, canceled')NEWLINE with _PROGRESS_LOCK:NEWLINE _finished_download += 1NEWLINE download_queue.task_done()NEWLINENEWLINENEWLINEdef start_and_wait_download_threading(download_queue, count):NEWLINE """start download threading and wait till complete"""NEWLINE progress_t = threading.Thread(target=print_progress, args=(count,))NEWLINE progress_t.daemon = TrueNEWLINE progress_t.start()NEWLINE for i in range(_THREADING_NUMBER):NEWLINE download_t = threading.Thread(target=download_threading, args=(download_queue,))NEWLINE download_t.daemon = TrueNEWLINE download_t.start()NEWLINENEWLINE progress_t.join()NEWLINE download_queue.join()NEWLINENEWLINENEWLINEdef get_filepath(url, illustration, save_path='.', add_user_folder=False, add_rank=False):NEWLINE """return (filename,filepath)"""NEWLINENEWLINE if add_user_folder:NEWLINE user_id = illustration.user_idNEWLINE user_name = illustration.user_nameNEWLINE current_path = get_default_save_path()NEWLINE cur_dirs = list(filter(os.path.isdir, [os.path.join(current_path, i) for i in os.listdir(current_path)]))NEWLINE cur_user_ids = [os.path.basename(cur_dir).split()[0] for cur_dir in cur_dirs]NEWLINE if user_id not in cur_user_ids:NEWLINE dir_name = re.sub(r'[<>:"/\\|\?\*]', ' ', user_id + ' ' + user_name)NEWLINE else:NEWLINE dir_name = list(i for i in cur_dirs if os.path.basename(i).split()[0] == user_id)[0]NEWLINE save_path = os.path.join(save_path, dir_name)NEWLINENEWLINE filename = url.split('/')[-1]NEWLINE if add_rank:NEWLINE filename = f'{illustration.rank} - {filename}'NEWLINE filepath = os.path.join(save_path, filename)NEWLINE return filename, filepathNEWLINENEWLINENEWLINEdef check_files(illustrations, save_path='.', add_user_folder=False, add_rank=False):NEWLINE download_queue = queue.Queue()NEWLINE index_list = []NEWLINE count = 0NEWLINE if illustrations:NEWLINE last_i = -1NEWLINE for index, illustration in enumerate(illustrations):NEWLINE if not illustration.image_urls:NEWLINE continueNEWLINE else:NEWLINE for url in illustration.image_urls:NEWLINE filename, filepath = get_filepath(url, illustration, save_path, add_user_folder, add_rank)NEWLINE if os.path.exists(filepath):NEWLINE continueNEWLINE else:NEWLINE if last_i != index:NEWLINE last_i = indexNEWLINE index_list.append(index)NEWLINE download_queue.put({'url': url, 'file': filename, 'path': filepath})NEWLINE count += 1NEWLINE return download_queue, count, index_listNEWLINENEWLINENEWLINEdef count_illustrations(illustrations):NEWLINE return sum(len(i.image_urls) for i in illustrations)NEWLINENEWLINENEWLINEdef is_manga(illustrate):NEWLINE return True if illustrate.is_manga or illustrate.type == 'manga' else FalseNEWLINENEWLINENEWLINEdef download_illustrations(user, data_list, save_path='.', add_user_folder=False, add_rank=False, skip_manga=False):NEWLINE """Download illustratonsNEWLINENEWLINE Args:NEWLINE user: PixivApi()NEWLINE data_list: jsonNEWLINE save_path: str, download path of the illustrationsNEWLINE add_user_folder: bool, whether put the illustration into user folderNEWLINE add_rank: bool, add illustration rank at the beginning of filenameNEWLINE """NEWLINE illustrations = PixivIllustModel.from_data(data_list)NEWLINE if skip_manga:NEWLINE manga_number = sum([is_manga(i) for i in illustrations])NEWLINE if manga_number:NEWLINE print('skip', manga_number, 'manga')NEWLINE illustrations = list(filter(lambda x: not is_manga(x), illustrations))NEWLINE download_queue, count = check_files(illustrations, save_path, add_user_folder, add_rank)[0:2]NEWLINE if count > 0:NEWLINE print(_('Start download, total illustrations '), count)NEWLINE global _finished_download, _Global_DownloadNEWLINE _finished_download = 0NEWLINE _Global_Download = 0NEWLINE start_and_wait_download_threading(download_queue, count)NEWLINE print()NEWLINE else:NEWLINE print(_('There is no new illustration need to download'))NEWLINENEWLINENEWLINEdef download_by_user_id(user, user_ids=None):NEWLINE save_path = get_default_save_path()NEWLINE if not user_ids:NEWLINE user_ids = input(_('Input the artist\'s id:(separate with space)')).strip().split(' ')NEWLINE for user_id in user_ids:NEWLINE print(_('Artists %s') % user_id)NEWLINE data_list = user.get_all_user_illustrations(user_id)NEWLINE download_illustrations(user, data_list, save_path, add_user_folder=True)NEWLINENEWLINENEWLINEdef download_by_ranking(user):NEWLINE today = str(datetime.date.today())NEWLINE save_path = os.path.join(get_default_save_path(), today + ' ranking')NEWLINE data_list = user.get_ranking_illustrations()NEWLINE download_illustrations(user, data_list, save_path, add_rank=True)NEWLINENEWLINENEWLINEdef download_by_history_ranking(user, date=''):NEWLINE if not date:NEWLINE date = input(_('Input the date:(eg:2015-07-10)'))NEWLINE if not (re.search("^\d{4}-\d{2}-\d{2}", date)):NEWLINE print(_('[invalid date format]'))NEWLINE date = str(datetime.date.today() - datetime.timedelta(days=1))NEWLINE save_path = os.path.join(get_default_save_path(), date + ' ranking')NEWLINE data_list = user.get_ranking_illustrations(date=date)NEWLINE download_illustrations(user, data_list, save_path, add_rank=True)NEWLINENEWLINENEWLINEdef artist_folder_scanner(user, user_id_list, save_path, final_list, fast):NEWLINE while not user_id_list.empty():NEWLINE user_info = user_id_list.get()NEWLINE user_id = user_info['id']NEWLINE folder = user_info['folder']NEWLINE try:NEWLINE if fast:NEWLINE data_list = []NEWLINE offset = 0NEWLINE page_result = user.get_all_user_illustrations(user_id, offset, _ILLUST_PER_PAGE)NEWLINE if len(page_result) > 0:NEWLINE data_list.extend(page_result)NEWLINE file_path = os.path.join(save_path, folder, data_list[-1]['image_urls']['large'].split('/')[-1])NEWLINE while not os.path.exists(file_path) and len(page_result) == _ILLUST_PER_PAGE:NEWLINE offset += _ILLUST_PER_PAGENEWLINE page_result = user.get_all_user_illustrations(user_id, offset, _ILLUST_PER_PAGE)NEWLINE data_list.extend(page_result)NEWLINE file_path = os.path.join(save_path, folder, data_list[-1]['image_urls']['large'].split('/')[-1])NEWLINE # prevent rate limitNEWLINE time.sleep(1)NEWLINE else:NEWLINE data_list = user.get_all_user_illustrations(user_id)NEWLINE illustrations = PixivIllustModel.from_data(data_list)NEWLINE count, checked_list = check_files(illustrations, save_path, add_user_folder=True, add_rank=False)[1:3]NEWLINE if len(sys.argv) < 2 or count:NEWLINE try:NEWLINE print(_('Artists %s [%s]') % (folder, count))NEWLINE except UnicodeError:NEWLINE print(_('Artists %s ?? [%s]') % (user_id, count))NEWLINE with _PROGRESS_LOCK:NEWLINE for index in checked_list:NEWLINE final_list.append(data_list[index])NEWLINE except Exception:NEWLINE traceback.print_exc()NEWLINE user_id_list.task_done()NEWLINENEWLINENEWLINEdef update_exist(user, fast=True):NEWLINE current_path = get_default_save_path()NEWLINE final_list = []NEWLINE user_id_list = queue.Queue()NEWLINE for folder in os.listdir(current_path):NEWLINE if os.path.isdir(os.path.join(current_path, folder)):NEWLINE user_id = re.search('^(\d+) ', folder)NEWLINE if user_id:NEWLINE user_id = user_id.group(1)NEWLINE user_id_list.put({'id': user_id, 'folder': folder})NEWLINE for i in range(1):NEWLINE # use one thread to prevent Rate Limit in new App APINEWLINE scan_t = threading.Thread(target=artist_folder_scanner,NEWLINE args=(user, user_id_list, current_path, final_list, fast,))NEWLINE scan_t.daemon = TrueNEWLINE scan_t.start()NEWLINE user_id_list.join()NEWLINE download_illustrations(user, final_list, current_path, add_user_folder=True)NEWLINENEWLINENEWLINEdef remove_repeat(_):NEWLINE """Delete xxxxx.img if xxxxx_p0.img exist"""NEWLINE choice = input(_('Dangerous Action: continue?(y/n)'))NEWLINE if choice == 'y':NEWLINE illust_path = get_default_save_path()NEWLINE for folder in os.listdir(illust_path):NEWLINE if os.path.isdir(os.path.join(illust_path, folder)):NEWLINE if re.search('^(\d+) ', folder):NEWLINE path = os.path.join(illust_path, folder)NEWLINE for file_name in os.listdir(path):NEWLINE illustration_id = re.search('^\d+\.', file_name)NEWLINE if illustration_id:NEWLINE if os.path.isfile(os.path.join(pathNEWLINE , illustration_id.string.replace('.', '_p0.'))):NEWLINE os.remove(os.path.join(path, file_name))NEWLINE print('Delete', os.path.join(path, file_name))NEWLINENEWLINENEWLINEdef main():NEWLINE user = PixivApi()NEWLINE if len(sys.argv) > 1:NEWLINE print(datetime.datetime.now().strftime('%X %x'))NEWLINE ids = arguments['<id>']NEWLINE is_rank = arguments['-r']NEWLINE date = arguments['--date']NEWLINE is_update = arguments['-u']NEWLINE if ids:NEWLINE download_by_user_id(user, ids)NEWLINE elif is_rank:NEWLINE if date:NEWLINE date = date[0]NEWLINE download_by_history_ranking(user, date)NEWLINE else:NEWLINE download_by_ranking(user)NEWLINE elif is_update:NEWLINE update_exist(user)NEWLINE print(datetime.datetime.now().strftime('%X %x'))NEWLINE else:NEWLINE print(_(' Pixiv Downloader 2.4 ').center(77, '#'))NEWLINE options = {NEWLINE '1': download_by_user_id,NEWLINE '2': download_by_ranking,NEWLINE '3': download_by_history_ranking,NEWLINE '4': update_exist,NEWLINE '5': remove_repeatNEWLINE }NEWLINE while True:NEWLINE print(_('Which do you want to:'))NEWLINE for i in sorted(options.keys()):NEWLINE print('\t %s %s' % (i, _(options[i].__name__).replace('_', ' ')))NEWLINE choose = input('\t e %s \n:' % _('exit'))NEWLINE if choose in [str(i) for i in range(1, len(options) + 1)]:NEWLINE print((' ' + _(options[choose].__name__).replace('_', ' ') + ' ').center(60, '#') + '\n')NEWLINE if choose == 4:NEWLINE options[choose](user, False)NEWLINE else:NEWLINE options[choose](user)NEWLINE print('\n' + (' ' + _(options[choose].__name__).replace('_', ' ') + _(' finished ')).center(60,NEWLINE '#') + '\n')NEWLINE elif choose == 'e':NEWLINE breakNEWLINE else:NEWLINE print(_('Wrong input!'))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE arguments = docopt(__doc__, version='pixiv 3')NEWLINE sys.exit(main())NEWLINE |
import argparseNEWLINENEWLINEimport torchNEWLINEfrom torch_geometric.nn import Node2VecNEWLINEfrom torch_geometric.utils import to_undirectedNEWLINENEWLINEfrom ogb.nodeproppred import PygNodePropPredDatasetNEWLINENEWLINENEWLINEdef save_embedding(model):NEWLINE torch.save(model.embedding.weight.data.cpu(), 'embedding.pt')NEWLINENEWLINENEWLINEdef main():NEWLINE parser = argparse.ArgumentParser(description='OGBN-Arxiv (Node2Vec)')NEWLINE parser.add_argument('--device', type=int, default=0)NEWLINE parser.add_argument('--embedding_dim', type=int, default=128)NEWLINE parser.add_argument('--walk_length', type=int, default=80)NEWLINE parser.add_argument('--context_size', type=int, default=20)NEWLINE parser.add_argument('--walks_per_node', type=int, default=10)NEWLINE parser.add_argument('--batch_size', type=int, default=256)NEWLINE parser.add_argument('--lr', type=float, default=0.01)NEWLINE parser.add_argument('--epochs', type=int, default=5)NEWLINE parser.add_argument('--log_steps', type=int, default=1)NEWLINE args = parser.parse_args()NEWLINENEWLINE device = f'cuda:{args.device}' if torch.cuda.is_available() else 'cpu'NEWLINE device = torch.device(device)NEWLINENEWLINE dataset = PygNodePropPredDataset(name='ogbn-arxiv',NEWLINE root='/srv/scratch/ogb/datasets/nodeproppred')NEWLINE data = dataset[0]NEWLINE data.edge_index = to_undirected(data.edge_index, data.num_nodes)NEWLINENEWLINE model = Node2Vec(data.edge_index, args.embedding_dim, args.walk_length,NEWLINE args.context_size, args.walks_per_node,NEWLINE sparse=True).to(device)NEWLINENEWLINE loader = model.loader(batch_size=args.batch_size, shuffle=True,NEWLINE num_workers=4)NEWLINE optimizer = torch.optim.SparseAdam(list(model.parameters()), lr=args.lr)NEWLINENEWLINE model.train()NEWLINE for epoch in range(1, args.epochs + 1):NEWLINE for i, (pos_rw, neg_rw) in enumerate(loader):NEWLINE optimizer.zero_grad()NEWLINE loss = model.loss(pos_rw.to(device), neg_rw.to(device))NEWLINE loss.backward()NEWLINE optimizer.step()NEWLINENEWLINE if (i + 1) % args.log_steps == 0:NEWLINE print(f'Epoch: {epoch:02d}, Step: {i+1:03d}/{len(loader)}, 'NEWLINE f'Loss: {loss:.4f}')NEWLINENEWLINE if (i + 1) % 100 == 0: # Save model every 100 steps.NEWLINE save_embedding(model)NEWLINE save_embedding(model)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE main()NEWLINE |
# coding=utf-8NEWLINE# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""The Large Spanish Corpus is a compilation of Spanish corpora spanning Wikipedia to European parliament notes."""NEWLINENEWLINEfrom __future__ import absolute_import, division, print_functionNEWLINENEWLINEimport osNEWLINENEWLINEimport datasetsNEWLINENEWLINENEWLINE_CITATION = """\NEWLINE@dataset{jose_canete_2019_3247731,NEWLINE author = {José Cañete},NEWLINE title = {Compilation of Large Spanish Unannotated Corpora},NEWLINE month = may,NEWLINE year = 2019,NEWLINE publisher = {Zenodo},NEWLINE doi = {10.5281/zenodo.3247731},NEWLINE url = {https://doi.org/10.5281/zenodo.3247731}NEWLINE}NEWLINE"""NEWLINENEWLINE_DESCRIPTION = """\NEWLINEThe Large Spanish Corpus is a compilation of 15 unlabelled Spanish corpora spanning Wikipedia to European parliament \NEWLINEnotes. Each config contains the data corresponding to a different corpus. For example, "all_wiki" only includes \NEWLINEexamples from Spanish Wikipedia. By default, the config is set to "combined" which loads all the corpora; with this \NEWLINEsetting you can also specify the number of samples to return per corpus by configuring the "split" argument.NEWLINE"""NEWLINENEWLINE_HOMEPAGE = "https://github.com/josecannete/spanish-corpora"NEWLINENEWLINE_LICENSE = "MIT"NEWLINENEWLINE_URL = "https://zenodo.org/record/3247731/files/raw.tar.bz2"NEWLINENEWLINE_CORPORA = [NEWLINE "JRC",NEWLINE "EMEA",NEWLINE "GlobalVoices",NEWLINE "ECB",NEWLINE "DOGC",NEWLINE "all_wikis",NEWLINE "TED",NEWLINE "multiUN",NEWLINE "Europarl",NEWLINE "NewsCommentary11",NEWLINE "UN",NEWLINE "EUBookShop",NEWLINE "ParaCrawl",NEWLINE "OpenSubtitles2018",NEWLINE "DGT",NEWLINE]NEWLINENEWLINE_CORPORA_FILEPATHS = {corpus: os.path.join("spanish-corpora", "raw", f"{corpus}.txt") for corpus in _CORPORA}NEWLINENEWLINE_VERSION = "1.1.0"NEWLINENEWLINE_COMBINED = "combined"NEWLINENEWLINENEWLINEclass LargeSpanishCorpusConfig(datasets.BuilderConfig):NEWLINE def __init__(self, corpora=None, **kwargs):NEWLINE super(LargeSpanishCorpusConfig, self).__init__(version=datasets.Version(_VERSION, ""), **kwargs)NEWLINE self.corpora = corporaNEWLINENEWLINE @propertyNEWLINE def filepaths(self):NEWLINE return [_CORPORA_FILEPATHS[corpus] for corpus in self.corpora]NEWLINENEWLINENEWLINEclass LargeSpanishCorpus(datasets.GeneratorBasedBuilder):NEWLINE """The Large Spanish Corpus."""NEWLINENEWLINE BUILDER_CONFIGS = [NEWLINE LargeSpanishCorpusConfig(name=corpus, corpora=[corpus], description=f"Spanish examples in corpus {corpus}.")NEWLINE for corpus in _CORPORANEWLINE ] + [NEWLINE LargeSpanishCorpusConfig(NEWLINE name=_COMBINED, corpora=_CORPORA, description=f"Complete Spanish dataset with all corpora."NEWLINE )NEWLINE ]NEWLINE BUILDER_CONFIG_CLASS = LargeSpanishCorpusConfigNEWLINE DEFAULT_CONFIG_NAME = _COMBINEDNEWLINENEWLINE def _info(self):NEWLINE return datasets.DatasetInfo(NEWLINE description=_DESCRIPTION,NEWLINE features=datasets.Features(NEWLINE {NEWLINE "text": datasets.Value("string"),NEWLINE }NEWLINE ),NEWLINE supervised_keys=None,NEWLINE homepage=_HOMEPAGE,NEWLINE license=_LICENSE,NEWLINE citation=_CITATION,NEWLINE )NEWLINENEWLINE def _split_generators(self, dl_manager):NEWLINE data_dir = dl_manager.download_and_extract(_URL)NEWLINE return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"data_dir": data_dir})]NEWLINENEWLINE def _generate_examples(self, data_dir):NEWLINE for filepath in self.config.filepaths:NEWLINE filepath = os.path.join(data_dir, filepath)NEWLINE _id = 0NEWLINE with open(filepath, mode="r", encoding="utf-8") as f:NEWLINE for line in f:NEWLINE yield _id, {"text": line.strip()},NEWLINE _id += 1NEWLINE |