id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
251,200 | F5Networks/f5-common-python | f5/bigip/tm/asm/policies/__init__.py | Policy.delete | def delete(self, **kwargs):
"""Custom deletion logic to handle edge cases
This shouldn't be needed, but ASM has a tendency to raise various errors that
are painful to handle from a customer point-of-view
The error itself are described in their exception handler
To address these failure, we try a number of exception handling cases to catch
and reliably deal with the error.
:param kwargs:
:return:
"""
for x in range(0, 30):
try:
return self._delete(**kwargs)
except iControlUnexpectedHTTPError as ex:
if self._check_exception(ex):
continue
else:
raise | python | def delete(self, **kwargs):
for x in range(0, 30):
try:
return self._delete(**kwargs)
except iControlUnexpectedHTTPError as ex:
if self._check_exception(ex):
continue
else:
raise | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"30",
")",
":",
"try",
":",
"return",
"self",
".",
"_delete",
"(",
"*",
"*",
"kwargs",
")",
"except",
"iControlUnexpectedHTTPError",
"as",
"ex",
":",
"if",
"self",
".",
"_check_exception",
"(",
"ex",
")",
":",
"continue",
"else",
":",
"raise"
] | Custom deletion logic to handle edge cases
This shouldn't be needed, but ASM has a tendency to raise various errors that
are painful to handle from a customer point-of-view
The error itself are described in their exception handler
To address these failure, we try a number of exception handling cases to catch
and reliably deal with the error.
:param kwargs:
:return: | [
"Custom",
"deletion",
"logic",
"to",
"handle",
"edge",
"cases"
] | 7e67d5acd757a60e3d5f8c88c534bd72208f5494 | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/asm/policies/__init__.py#L174-L195 |
251,201 | laurencium/Causalinference | causalinference/causal.py | CausalModel.reset | def reset(self):
"""
Reinitializes data to original inputs, and drops any estimated
results.
"""
Y, D, X = self.old_data['Y'], self.old_data['D'], self.old_data['X']
self.raw_data = Data(Y, D, X)
self.summary_stats = Summary(self.raw_data)
self.propensity = None
self.cutoff = None
self.blocks = None
self.strata = None
self.estimates = Estimators() | python | def reset(self):
Y, D, X = self.old_data['Y'], self.old_data['D'], self.old_data['X']
self.raw_data = Data(Y, D, X)
self.summary_stats = Summary(self.raw_data)
self.propensity = None
self.cutoff = None
self.blocks = None
self.strata = None
self.estimates = Estimators() | [
"def",
"reset",
"(",
"self",
")",
":",
"Y",
",",
"D",
",",
"X",
"=",
"self",
".",
"old_data",
"[",
"'Y'",
"]",
",",
"self",
".",
"old_data",
"[",
"'D'",
"]",
",",
"self",
".",
"old_data",
"[",
"'X'",
"]",
"self",
".",
"raw_data",
"=",
"Data",
"(",
"Y",
",",
"D",
",",
"X",
")",
"self",
".",
"summary_stats",
"=",
"Summary",
"(",
"self",
".",
"raw_data",
")",
"self",
".",
"propensity",
"=",
"None",
"self",
".",
"cutoff",
"=",
"None",
"self",
".",
"blocks",
"=",
"None",
"self",
".",
"strata",
"=",
"None",
"self",
".",
"estimates",
"=",
"Estimators",
"(",
")"
] | Reinitializes data to original inputs, and drops any estimated
results. | [
"Reinitializes",
"data",
"to",
"original",
"inputs",
"and",
"drops",
"any",
"estimated",
"results",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L21-L35 |
251,202 | laurencium/Causalinference | causalinference/causal.py | CausalModel.est_propensity | def est_propensity(self, lin='all', qua=None):
"""
Estimates the propensity scores given list of covariates to
include linearly or quadratically.
The propensity score is the conditional probability of
receiving the treatment given the observed covariates.
Estimation is done via a logistic regression.
Parameters
----------
lin: string or list, optional
Column numbers (zero-based) of variables of
the original covariate matrix X to include
linearly. Defaults to the string 'all', which
uses whole covariate matrix.
qua: list, optional
Tuples indicating which columns of the original
covariate matrix to multiply and include. E.g.,
[(1,1), (2,3)] indicates squaring the 2nd column
and including the product of the 3rd and 4th
columns. Default is to not include any
quadratic terms.
"""
lin_terms = parse_lin_terms(self.raw_data['K'], lin)
qua_terms = parse_qua_terms(self.raw_data['K'], qua)
self.propensity = Propensity(self.raw_data, lin_terms, qua_terms)
self.raw_data._dict['pscore'] = self.propensity['fitted']
self._post_pscore_init() | python | def est_propensity(self, lin='all', qua=None):
lin_terms = parse_lin_terms(self.raw_data['K'], lin)
qua_terms = parse_qua_terms(self.raw_data['K'], qua)
self.propensity = Propensity(self.raw_data, lin_terms, qua_terms)
self.raw_data._dict['pscore'] = self.propensity['fitted']
self._post_pscore_init() | [
"def",
"est_propensity",
"(",
"self",
",",
"lin",
"=",
"'all'",
",",
"qua",
"=",
"None",
")",
":",
"lin_terms",
"=",
"parse_lin_terms",
"(",
"self",
".",
"raw_data",
"[",
"'K'",
"]",
",",
"lin",
")",
"qua_terms",
"=",
"parse_qua_terms",
"(",
"self",
".",
"raw_data",
"[",
"'K'",
"]",
",",
"qua",
")",
"self",
".",
"propensity",
"=",
"Propensity",
"(",
"self",
".",
"raw_data",
",",
"lin_terms",
",",
"qua_terms",
")",
"self",
".",
"raw_data",
".",
"_dict",
"[",
"'pscore'",
"]",
"=",
"self",
".",
"propensity",
"[",
"'fitted'",
"]",
"self",
".",
"_post_pscore_init",
"(",
")"
] | Estimates the propensity scores given list of covariates to
include linearly or quadratically.
The propensity score is the conditional probability of
receiving the treatment given the observed covariates.
Estimation is done via a logistic regression.
Parameters
----------
lin: string or list, optional
Column numbers (zero-based) of variables of
the original covariate matrix X to include
linearly. Defaults to the string 'all', which
uses whole covariate matrix.
qua: list, optional
Tuples indicating which columns of the original
covariate matrix to multiply and include. E.g.,
[(1,1), (2,3)] indicates squaring the 2nd column
and including the product of the 3rd and 4th
columns. Default is to not include any
quadratic terms. | [
"Estimates",
"the",
"propensity",
"scores",
"given",
"list",
"of",
"covariates",
"to",
"include",
"linearly",
"or",
"quadratically",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L38-L69 |
251,203 | laurencium/Causalinference | causalinference/causal.py | CausalModel.trim | def trim(self):
"""
Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has been estimated.
"""
if 0 < self.cutoff <= 0.5:
pscore = self.raw_data['pscore']
keep = (pscore >= self.cutoff) & (pscore <= 1-self.cutoff)
Y_trimmed = self.raw_data['Y'][keep]
D_trimmed = self.raw_data['D'][keep]
X_trimmed = self.raw_data['X'][keep]
self.raw_data = Data(Y_trimmed, D_trimmed, X_trimmed)
self.raw_data._dict['pscore'] = pscore[keep]
self.summary_stats = Summary(self.raw_data)
self.strata = None
self.estimates = Estimators()
elif self.cutoff == 0:
pass
else:
raise ValueError('Invalid cutoff.') | python | def trim(self):
if 0 < self.cutoff <= 0.5:
pscore = self.raw_data['pscore']
keep = (pscore >= self.cutoff) & (pscore <= 1-self.cutoff)
Y_trimmed = self.raw_data['Y'][keep]
D_trimmed = self.raw_data['D'][keep]
X_trimmed = self.raw_data['X'][keep]
self.raw_data = Data(Y_trimmed, D_trimmed, X_trimmed)
self.raw_data._dict['pscore'] = pscore[keep]
self.summary_stats = Summary(self.raw_data)
self.strata = None
self.estimates = Estimators()
elif self.cutoff == 0:
pass
else:
raise ValueError('Invalid cutoff.') | [
"def",
"trim",
"(",
"self",
")",
":",
"if",
"0",
"<",
"self",
".",
"cutoff",
"<=",
"0.5",
":",
"pscore",
"=",
"self",
".",
"raw_data",
"[",
"'pscore'",
"]",
"keep",
"=",
"(",
"pscore",
">=",
"self",
".",
"cutoff",
")",
"&",
"(",
"pscore",
"<=",
"1",
"-",
"self",
".",
"cutoff",
")",
"Y_trimmed",
"=",
"self",
".",
"raw_data",
"[",
"'Y'",
"]",
"[",
"keep",
"]",
"D_trimmed",
"=",
"self",
".",
"raw_data",
"[",
"'D'",
"]",
"[",
"keep",
"]",
"X_trimmed",
"=",
"self",
".",
"raw_data",
"[",
"'X'",
"]",
"[",
"keep",
"]",
"self",
".",
"raw_data",
"=",
"Data",
"(",
"Y_trimmed",
",",
"D_trimmed",
",",
"X_trimmed",
")",
"self",
".",
"raw_data",
".",
"_dict",
"[",
"'pscore'",
"]",
"=",
"pscore",
"[",
"keep",
"]",
"self",
".",
"summary_stats",
"=",
"Summary",
"(",
"self",
".",
"raw_data",
")",
"self",
".",
"strata",
"=",
"None",
"self",
".",
"estimates",
"=",
"Estimators",
"(",
")",
"elif",
"self",
".",
"cutoff",
"==",
"0",
":",
"pass",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid cutoff.'",
")"
] | Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has been estimated. | [
"Trims",
"data",
"based",
"on",
"propensity",
"score",
"to",
"create",
"a",
"subsample",
"with",
"better",
"covariate",
"balance",
".",
"The",
"default",
"cutoff",
"value",
"is",
"set",
"to",
"0",
".",
"1",
".",
"To",
"set",
"a",
"custom",
"cutoff",
"value",
"modify",
"the",
"object",
"attribute",
"named",
"cutoff",
"directly",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L118-L145 |
251,204 | laurencium/Causalinference | causalinference/causal.py | CausalModel.stratify | def stratify(self):
"""
Stratifies the sample based on propensity score.
By default the sample is divided into five equal-sized bins.
The number of bins can be set by modifying the object
attribute named blocks. Alternatively, custom-sized bins can
be created by setting blocks equal to a sorted list of numbers
between 0 and 1 indicating the bin boundaries.
This method should only be executed after the propensity score
has been estimated.
"""
Y, D, X = self.raw_data['Y'], self.raw_data['D'], self.raw_data['X']
pscore = self.raw_data['pscore']
if isinstance(self.blocks, int):
blocks = split_equal_bins(pscore, self.blocks)
else:
blocks = self.blocks[:] # make a copy; should be sorted
blocks[0] = 0 # avoids always dropping 1st unit
def subset(p_low, p_high):
return (p_low < pscore) & (pscore <= p_high)
subsets = [subset(*ps) for ps in zip(blocks, blocks[1:])]
strata = [CausalModel(Y[s], D[s], X[s]) for s in subsets]
self.strata = Strata(strata, subsets, pscore) | python | def stratify(self):
Y, D, X = self.raw_data['Y'], self.raw_data['D'], self.raw_data['X']
pscore = self.raw_data['pscore']
if isinstance(self.blocks, int):
blocks = split_equal_bins(pscore, self.blocks)
else:
blocks = self.blocks[:] # make a copy; should be sorted
blocks[0] = 0 # avoids always dropping 1st unit
def subset(p_low, p_high):
return (p_low < pscore) & (pscore <= p_high)
subsets = [subset(*ps) for ps in zip(blocks, blocks[1:])]
strata = [CausalModel(Y[s], D[s], X[s]) for s in subsets]
self.strata = Strata(strata, subsets, pscore) | [
"def",
"stratify",
"(",
"self",
")",
":",
"Y",
",",
"D",
",",
"X",
"=",
"self",
".",
"raw_data",
"[",
"'Y'",
"]",
",",
"self",
".",
"raw_data",
"[",
"'D'",
"]",
",",
"self",
".",
"raw_data",
"[",
"'X'",
"]",
"pscore",
"=",
"self",
".",
"raw_data",
"[",
"'pscore'",
"]",
"if",
"isinstance",
"(",
"self",
".",
"blocks",
",",
"int",
")",
":",
"blocks",
"=",
"split_equal_bins",
"(",
"pscore",
",",
"self",
".",
"blocks",
")",
"else",
":",
"blocks",
"=",
"self",
".",
"blocks",
"[",
":",
"]",
"# make a copy; should be sorted",
"blocks",
"[",
"0",
"]",
"=",
"0",
"# avoids always dropping 1st unit",
"def",
"subset",
"(",
"p_low",
",",
"p_high",
")",
":",
"return",
"(",
"p_low",
"<",
"pscore",
")",
"&",
"(",
"pscore",
"<=",
"p_high",
")",
"subsets",
"=",
"[",
"subset",
"(",
"*",
"ps",
")",
"for",
"ps",
"in",
"zip",
"(",
"blocks",
",",
"blocks",
"[",
"1",
":",
"]",
")",
"]",
"strata",
"=",
"[",
"CausalModel",
"(",
"Y",
"[",
"s",
"]",
",",
"D",
"[",
"s",
"]",
",",
"X",
"[",
"s",
"]",
")",
"for",
"s",
"in",
"subsets",
"]",
"self",
".",
"strata",
"=",
"Strata",
"(",
"strata",
",",
"subsets",
",",
"pscore",
")"
] | Stratifies the sample based on propensity score.
By default the sample is divided into five equal-sized bins.
The number of bins can be set by modifying the object
attribute named blocks. Alternatively, custom-sized bins can
be created by setting blocks equal to a sorted list of numbers
between 0 and 1 indicating the bin boundaries.
This method should only be executed after the propensity score
has been estimated. | [
"Stratifies",
"the",
"sample",
"based",
"on",
"propensity",
"score",
".",
"By",
"default",
"the",
"sample",
"is",
"divided",
"into",
"five",
"equal",
"-",
"sized",
"bins",
".",
"The",
"number",
"of",
"bins",
"can",
"be",
"set",
"by",
"modifying",
"the",
"object",
"attribute",
"named",
"blocks",
".",
"Alternatively",
"custom",
"-",
"sized",
"bins",
"can",
"be",
"created",
"by",
"setting",
"blocks",
"equal",
"to",
"a",
"sorted",
"list",
"of",
"numbers",
"between",
"0",
"and",
"1",
"indicating",
"the",
"bin",
"boundaries",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L171-L199 |
251,205 | laurencium/Causalinference | causalinference/causal.py | CausalModel.est_via_matching | def est_via_matching(self, weights='inv', matches=1, bias_adj=False):
"""
Estimates average treatment effects using nearest-
neighborhood matching.
Matching is done with replacement. Method supports multiple
matching. Correcting bias that arise due to imperfect matches
is also supported. For details on methodology, see [1]_.
Parameters
----------
weights: str or positive definite square matrix
Specifies weighting matrix used in computing
distance measures. Defaults to string 'inv',
which does inverse variance weighting. String
'maha' gives the weighting matrix used in the
Mahalanobis metric.
matches: int
Number of matches to use for each subject.
bias_adj: bool
Specifies whether bias adjustments should be
attempted.
References
----------
.. [1] Imbens, G. & Rubin, D. (2015). Causal Inference in
Statistics, Social, and Biomedical Sciences: An
Introduction.
"""
X, K = self.raw_data['X'], self.raw_data['K']
X_c, X_t = self.raw_data['X_c'], self.raw_data['X_t']
if weights == 'inv':
W = 1/X.var(0)
elif weights == 'maha':
V_c = np.cov(X_c, rowvar=False, ddof=0)
V_t = np.cov(X_t, rowvar=False, ddof=0)
if K == 1:
W = 1/np.array([[(V_c+V_t)/2]]) # matrix form
else:
W = np.linalg.inv((V_c+V_t)/2)
else:
W = weights
self.estimates['matching'] = Matching(self.raw_data, W,
matches, bias_adj) | python | def est_via_matching(self, weights='inv', matches=1, bias_adj=False):
X, K = self.raw_data['X'], self.raw_data['K']
X_c, X_t = self.raw_data['X_c'], self.raw_data['X_t']
if weights == 'inv':
W = 1/X.var(0)
elif weights == 'maha':
V_c = np.cov(X_c, rowvar=False, ddof=0)
V_t = np.cov(X_t, rowvar=False, ddof=0)
if K == 1:
W = 1/np.array([[(V_c+V_t)/2]]) # matrix form
else:
W = np.linalg.inv((V_c+V_t)/2)
else:
W = weights
self.estimates['matching'] = Matching(self.raw_data, W,
matches, bias_adj) | [
"def",
"est_via_matching",
"(",
"self",
",",
"weights",
"=",
"'inv'",
",",
"matches",
"=",
"1",
",",
"bias_adj",
"=",
"False",
")",
":",
"X",
",",
"K",
"=",
"self",
".",
"raw_data",
"[",
"'X'",
"]",
",",
"self",
".",
"raw_data",
"[",
"'K'",
"]",
"X_c",
",",
"X_t",
"=",
"self",
".",
"raw_data",
"[",
"'X_c'",
"]",
",",
"self",
".",
"raw_data",
"[",
"'X_t'",
"]",
"if",
"weights",
"==",
"'inv'",
":",
"W",
"=",
"1",
"/",
"X",
".",
"var",
"(",
"0",
")",
"elif",
"weights",
"==",
"'maha'",
":",
"V_c",
"=",
"np",
".",
"cov",
"(",
"X_c",
",",
"rowvar",
"=",
"False",
",",
"ddof",
"=",
"0",
")",
"V_t",
"=",
"np",
".",
"cov",
"(",
"X_t",
",",
"rowvar",
"=",
"False",
",",
"ddof",
"=",
"0",
")",
"if",
"K",
"==",
"1",
":",
"W",
"=",
"1",
"/",
"np",
".",
"array",
"(",
"[",
"[",
"(",
"V_c",
"+",
"V_t",
")",
"/",
"2",
"]",
"]",
")",
"# matrix form",
"else",
":",
"W",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"(",
"V_c",
"+",
"V_t",
")",
"/",
"2",
")",
"else",
":",
"W",
"=",
"weights",
"self",
".",
"estimates",
"[",
"'matching'",
"]",
"=",
"Matching",
"(",
"self",
".",
"raw_data",
",",
"W",
",",
"matches",
",",
"bias_adj",
")"
] | Estimates average treatment effects using nearest-
neighborhood matching.
Matching is done with replacement. Method supports multiple
matching. Correcting bias that arise due to imperfect matches
is also supported. For details on methodology, see [1]_.
Parameters
----------
weights: str or positive definite square matrix
Specifies weighting matrix used in computing
distance measures. Defaults to string 'inv',
which does inverse variance weighting. String
'maha' gives the weighting matrix used in the
Mahalanobis metric.
matches: int
Number of matches to use for each subject.
bias_adj: bool
Specifies whether bias adjustments should be
attempted.
References
----------
.. [1] Imbens, G. & Rubin, D. (2015). Causal Inference in
Statistics, Social, and Biomedical Sciences: An
Introduction. | [
"Estimates",
"average",
"treatment",
"effects",
"using",
"nearest",
"-",
"neighborhood",
"matching",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/causal.py#L285-L332 |
251,206 | laurencium/Causalinference | causalinference/utils/tools.py | random_data | def random_data(N=5000, K=3, unobservables=False, **kwargs):
"""
Function that generates data according to one of two simple models that
satisfies the unconfoundedness assumption.
The covariates and error terms are generated according to
X ~ N(mu, Sigma), epsilon ~ N(0, Gamma).
The counterfactual outcomes are generated by
Y0 = X*beta + epsilon_0,
Y1 = delta + X*(beta+theta) + epsilon_1.
Selection is done according to the following propensity score function:
P(D=1|X) = Lambda(X*beta).
Here Lambda is the standard logistic CDF.
Parameters
----------
N: int
Number of units to draw. Defaults to 5000.
K: int
Number of covariates. Defaults to 3.
unobservables: bool
Returns potential outcomes and true propensity score
in addition to observed outcome and covariates if True.
Defaults to False.
mu, Sigma, Gamma, beta, delta, theta: NumPy ndarrays, optional
Parameter values appearing in data generating process.
Returns
-------
tuple
A tuple in the form of (Y, D, X) or (Y, D, X, Y0, Y1) of
observed outcomes, treatment indicators, covariate matrix,
and potential outomces.
"""
mu = kwargs.get('mu', np.zeros(K))
beta = kwargs.get('beta', np.ones(K))
theta = kwargs.get('theta', np.ones(K))
delta = kwargs.get('delta', 3)
Sigma = kwargs.get('Sigma', np.identity(K))
Gamma = kwargs.get('Gamma', np.identity(2))
X = np.random.multivariate_normal(mean=mu, cov=Sigma, size=N)
Xbeta = X.dot(beta)
pscore = logistic.cdf(Xbeta)
D = np.array([np.random.binomial(1, p, size=1) for p in pscore]).flatten()
epsilon = np.random.multivariate_normal(mean=np.zeros(2), cov=Gamma, size=N)
Y0 = Xbeta + epsilon[:,0]
Y1 = delta + X.dot(beta+theta) + epsilon[:,1]
Y = (1-D)*Y0 + D*Y1
if unobservables:
return Y, D, X, Y0, Y1, pscore
else:
return Y, D, X | python | def random_data(N=5000, K=3, unobservables=False, **kwargs):
mu = kwargs.get('mu', np.zeros(K))
beta = kwargs.get('beta', np.ones(K))
theta = kwargs.get('theta', np.ones(K))
delta = kwargs.get('delta', 3)
Sigma = kwargs.get('Sigma', np.identity(K))
Gamma = kwargs.get('Gamma', np.identity(2))
X = np.random.multivariate_normal(mean=mu, cov=Sigma, size=N)
Xbeta = X.dot(beta)
pscore = logistic.cdf(Xbeta)
D = np.array([np.random.binomial(1, p, size=1) for p in pscore]).flatten()
epsilon = np.random.multivariate_normal(mean=np.zeros(2), cov=Gamma, size=N)
Y0 = Xbeta + epsilon[:,0]
Y1 = delta + X.dot(beta+theta) + epsilon[:,1]
Y = (1-D)*Y0 + D*Y1
if unobservables:
return Y, D, X, Y0, Y1, pscore
else:
return Y, D, X | [
"def",
"random_data",
"(",
"N",
"=",
"5000",
",",
"K",
"=",
"3",
",",
"unobservables",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"mu",
"=",
"kwargs",
".",
"get",
"(",
"'mu'",
",",
"np",
".",
"zeros",
"(",
"K",
")",
")",
"beta",
"=",
"kwargs",
".",
"get",
"(",
"'beta'",
",",
"np",
".",
"ones",
"(",
"K",
")",
")",
"theta",
"=",
"kwargs",
".",
"get",
"(",
"'theta'",
",",
"np",
".",
"ones",
"(",
"K",
")",
")",
"delta",
"=",
"kwargs",
".",
"get",
"(",
"'delta'",
",",
"3",
")",
"Sigma",
"=",
"kwargs",
".",
"get",
"(",
"'Sigma'",
",",
"np",
".",
"identity",
"(",
"K",
")",
")",
"Gamma",
"=",
"kwargs",
".",
"get",
"(",
"'Gamma'",
",",
"np",
".",
"identity",
"(",
"2",
")",
")",
"X",
"=",
"np",
".",
"random",
".",
"multivariate_normal",
"(",
"mean",
"=",
"mu",
",",
"cov",
"=",
"Sigma",
",",
"size",
"=",
"N",
")",
"Xbeta",
"=",
"X",
".",
"dot",
"(",
"beta",
")",
"pscore",
"=",
"logistic",
".",
"cdf",
"(",
"Xbeta",
")",
"D",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"random",
".",
"binomial",
"(",
"1",
",",
"p",
",",
"size",
"=",
"1",
")",
"for",
"p",
"in",
"pscore",
"]",
")",
".",
"flatten",
"(",
")",
"epsilon",
"=",
"np",
".",
"random",
".",
"multivariate_normal",
"(",
"mean",
"=",
"np",
".",
"zeros",
"(",
"2",
")",
",",
"cov",
"=",
"Gamma",
",",
"size",
"=",
"N",
")",
"Y0",
"=",
"Xbeta",
"+",
"epsilon",
"[",
":",
",",
"0",
"]",
"Y1",
"=",
"delta",
"+",
"X",
".",
"dot",
"(",
"beta",
"+",
"theta",
")",
"+",
"epsilon",
"[",
":",
",",
"1",
"]",
"Y",
"=",
"(",
"1",
"-",
"D",
")",
"*",
"Y0",
"+",
"D",
"*",
"Y1",
"if",
"unobservables",
":",
"return",
"Y",
",",
"D",
",",
"X",
",",
"Y0",
",",
"Y1",
",",
"pscore",
"else",
":",
"return",
"Y",
",",
"D",
",",
"X"
] | Function that generates data according to one of two simple models that
satisfies the unconfoundedness assumption.
The covariates and error terms are generated according to
X ~ N(mu, Sigma), epsilon ~ N(0, Gamma).
The counterfactual outcomes are generated by
Y0 = X*beta + epsilon_0,
Y1 = delta + X*(beta+theta) + epsilon_1.
Selection is done according to the following propensity score function:
P(D=1|X) = Lambda(X*beta).
Here Lambda is the standard logistic CDF.
Parameters
----------
N: int
Number of units to draw. Defaults to 5000.
K: int
Number of covariates. Defaults to 3.
unobservables: bool
Returns potential outcomes and true propensity score
in addition to observed outcome and covariates if True.
Defaults to False.
mu, Sigma, Gamma, beta, delta, theta: NumPy ndarrays, optional
Parameter values appearing in data generating process.
Returns
-------
tuple
A tuple in the form of (Y, D, X) or (Y, D, X, Y0, Y1) of
observed outcomes, treatment indicators, covariate matrix,
and potential outomces. | [
"Function",
"that",
"generates",
"data",
"according",
"to",
"one",
"of",
"two",
"simple",
"models",
"that",
"satisfies",
"the",
"unconfoundedness",
"assumption",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/utils/tools.py#L54-L113 |
251,207 | laurencium/Causalinference | causalinference/core/summary.py | Summary._summarize_pscore | def _summarize_pscore(self, pscore_c, pscore_t):
"""
Called by Strata class during initialization.
"""
self._dict['p_min'] = min(pscore_c.min(), pscore_t.min())
self._dict['p_max'] = max(pscore_c.max(), pscore_t.max())
self._dict['p_c_mean'] = pscore_c.mean()
self._dict['p_t_mean'] = pscore_t.mean() | python | def _summarize_pscore(self, pscore_c, pscore_t):
self._dict['p_min'] = min(pscore_c.min(), pscore_t.min())
self._dict['p_max'] = max(pscore_c.max(), pscore_t.max())
self._dict['p_c_mean'] = pscore_c.mean()
self._dict['p_t_mean'] = pscore_t.mean() | [
"def",
"_summarize_pscore",
"(",
"self",
",",
"pscore_c",
",",
"pscore_t",
")",
":",
"self",
".",
"_dict",
"[",
"'p_min'",
"]",
"=",
"min",
"(",
"pscore_c",
".",
"min",
"(",
")",
",",
"pscore_t",
".",
"min",
"(",
")",
")",
"self",
".",
"_dict",
"[",
"'p_max'",
"]",
"=",
"max",
"(",
"pscore_c",
".",
"max",
"(",
")",
",",
"pscore_t",
".",
"max",
"(",
")",
")",
"self",
".",
"_dict",
"[",
"'p_c_mean'",
"]",
"=",
"pscore_c",
".",
"mean",
"(",
")",
"self",
".",
"_dict",
"[",
"'p_t_mean'",
"]",
"=",
"pscore_t",
".",
"mean",
"(",
")"
] | Called by Strata class during initialization. | [
"Called",
"by",
"Strata",
"class",
"during",
"initialization",
"."
] | 3b20ae0560c711628fba47975180c8484d8aa3e7 | https://github.com/laurencium/Causalinference/blob/3b20ae0560c711628fba47975180c8484d8aa3e7/causalinference/core/summary.py#L40-L49 |
251,208 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonAPI.lookup_bulk | def lookup_bulk(self, ResponseGroup="Large", **kwargs):
"""Lookup Amazon Products in bulk.
Returns all products matching requested ASINs, ignoring invalid
entries.
:return:
A list of :class:`~.AmazonProduct` instances.
"""
response = self.api.ItemLookup(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if not hasattr(root.Items, 'Item'):
return []
return list(
AmazonProduct(
item,
self.aws_associate_tag,
self,
region=self.region) for item in root.Items.Item
) | python | def lookup_bulk(self, ResponseGroup="Large", **kwargs):
response = self.api.ItemLookup(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if not hasattr(root.Items, 'Item'):
return []
return list(
AmazonProduct(
item,
self.aws_associate_tag,
self,
region=self.region) for item in root.Items.Item
) | [
"def",
"lookup_bulk",
"(",
"self",
",",
"ResponseGroup",
"=",
"\"Large\"",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"ItemLookup",
"(",
"ResponseGroup",
"=",
"ResponseGroup",
",",
"*",
"*",
"kwargs",
")",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"response",
")",
"if",
"not",
"hasattr",
"(",
"root",
".",
"Items",
",",
"'Item'",
")",
":",
"return",
"[",
"]",
"return",
"list",
"(",
"AmazonProduct",
"(",
"item",
",",
"self",
".",
"aws_associate_tag",
",",
"self",
",",
"region",
"=",
"self",
".",
"region",
")",
"for",
"item",
"in",
"root",
".",
"Items",
".",
"Item",
")"
] | Lookup Amazon Products in bulk.
Returns all products matching requested ASINs, ignoring invalid
entries.
:return:
A list of :class:`~.AmazonProduct` instances. | [
"Lookup",
"Amazon",
"Products",
"in",
"bulk",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L200-L219 |
251,209 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonAPI.similarity_lookup | def similarity_lookup(self, ResponseGroup="Large", **kwargs):
"""Similarty Lookup.
Returns up to ten products that are similar to all items
specified in the request.
Example:
>>> api.similarity_lookup(ItemId='B002L3XLBO,B000LQTBKI')
"""
response = self.api.SimilarityLookup(
ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.Items.Request.IsValid == 'False':
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
raise SimilartyLookupException(
"Amazon Similarty Lookup Error: '{0}', '{1}'".format(
code, msg))
return [
AmazonProduct(
item,
self.aws_associate_tag,
self.api,
region=self.region
)
for item in getattr(root.Items, 'Item', [])
] | python | def similarity_lookup(self, ResponseGroup="Large", **kwargs):
response = self.api.SimilarityLookup(
ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.Items.Request.IsValid == 'False':
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
raise SimilartyLookupException(
"Amazon Similarty Lookup Error: '{0}', '{1}'".format(
code, msg))
return [
AmazonProduct(
item,
self.aws_associate_tag,
self.api,
region=self.region
)
for item in getattr(root.Items, 'Item', [])
] | [
"def",
"similarity_lookup",
"(",
"self",
",",
"ResponseGroup",
"=",
"\"Large\"",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"SimilarityLookup",
"(",
"ResponseGroup",
"=",
"ResponseGroup",
",",
"*",
"*",
"kwargs",
")",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"response",
")",
"if",
"root",
".",
"Items",
".",
"Request",
".",
"IsValid",
"==",
"'False'",
":",
"code",
"=",
"root",
".",
"Items",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Code",
"msg",
"=",
"root",
".",
"Items",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Message",
"raise",
"SimilartyLookupException",
"(",
"\"Amazon Similarty Lookup Error: '{0}', '{1}'\"",
".",
"format",
"(",
"code",
",",
"msg",
")",
")",
"return",
"[",
"AmazonProduct",
"(",
"item",
",",
"self",
".",
"aws_associate_tag",
",",
"self",
".",
"api",
",",
"region",
"=",
"self",
".",
"region",
")",
"for",
"item",
"in",
"getattr",
"(",
"root",
".",
"Items",
",",
"'Item'",
",",
"[",
"]",
")",
"]"
] | Similarty Lookup.
Returns up to ten products that are similar to all items
specified in the request.
Example:
>>> api.similarity_lookup(ItemId='B002L3XLBO,B000LQTBKI') | [
"Similarty",
"Lookup",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L221-L247 |
251,210 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonAPI.browse_node_lookup | def browse_node_lookup(self, ResponseGroup="BrowseNodeInfo", **kwargs):
"""Browse Node Lookup.
Returns the specified browse node's name, children, and ancestors.
Example:
>>> api.browse_node_lookup(BrowseNodeId='163357')
"""
response = self.api.BrowseNodeLookup(
ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.BrowseNodes.Request.IsValid == 'False':
code = root.BrowseNodes.Request.Errors.Error.Code
msg = root.BrowseNodes.Request.Errors.Error.Message
raise BrowseNodeLookupException(
"Amazon BrowseNode Lookup Error: '{0}', '{1}'".format(
code, msg))
return [AmazonBrowseNode(node.BrowseNode) for node in root.BrowseNodes] | python | def browse_node_lookup(self, ResponseGroup="BrowseNodeInfo", **kwargs):
response = self.api.BrowseNodeLookup(
ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.BrowseNodes.Request.IsValid == 'False':
code = root.BrowseNodes.Request.Errors.Error.Code
msg = root.BrowseNodes.Request.Errors.Error.Message
raise BrowseNodeLookupException(
"Amazon BrowseNode Lookup Error: '{0}', '{1}'".format(
code, msg))
return [AmazonBrowseNode(node.BrowseNode) for node in root.BrowseNodes] | [
"def",
"browse_node_lookup",
"(",
"self",
",",
"ResponseGroup",
"=",
"\"BrowseNodeInfo\"",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"BrowseNodeLookup",
"(",
"ResponseGroup",
"=",
"ResponseGroup",
",",
"*",
"*",
"kwargs",
")",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"response",
")",
"if",
"root",
".",
"BrowseNodes",
".",
"Request",
".",
"IsValid",
"==",
"'False'",
":",
"code",
"=",
"root",
".",
"BrowseNodes",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Code",
"msg",
"=",
"root",
".",
"BrowseNodes",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Message",
"raise",
"BrowseNodeLookupException",
"(",
"\"Amazon BrowseNode Lookup Error: '{0}', '{1}'\"",
".",
"format",
"(",
"code",
",",
"msg",
")",
")",
"return",
"[",
"AmazonBrowseNode",
"(",
"node",
".",
"BrowseNode",
")",
"for",
"node",
"in",
"root",
".",
"BrowseNodes",
"]"
] | Browse Node Lookup.
Returns the specified browse node's name, children, and ancestors.
Example:
>>> api.browse_node_lookup(BrowseNodeId='163357') | [
"Browse",
"Node",
"Lookup",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L249-L265 |
251,211 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonAPI.search_n | def search_n(self, n, **kwargs):
"""Search and return first N results..
:param n:
An integer specifying the number of results to return.
:return:
A list of :class:`~.AmazonProduct`.
"""
region = kwargs.get('region', self.region)
kwargs.update({'region': region})
items = AmazonSearch(self.api, self.aws_associate_tag, **kwargs)
return list(islice(items, n)) | python | def search_n(self, n, **kwargs):
region = kwargs.get('region', self.region)
kwargs.update({'region': region})
items = AmazonSearch(self.api, self.aws_associate_tag, **kwargs)
return list(islice(items, n)) | [
"def",
"search_n",
"(",
"self",
",",
"n",
",",
"*",
"*",
"kwargs",
")",
":",
"region",
"=",
"kwargs",
".",
"get",
"(",
"'region'",
",",
"self",
".",
"region",
")",
"kwargs",
".",
"update",
"(",
"{",
"'region'",
":",
"region",
"}",
")",
"items",
"=",
"AmazonSearch",
"(",
"self",
".",
"api",
",",
"self",
".",
"aws_associate_tag",
",",
"*",
"*",
"kwargs",
")",
"return",
"list",
"(",
"islice",
"(",
"items",
",",
"n",
")",
")"
] | Search and return first N results..
:param n:
An integer specifying the number of results to return.
:return:
A list of :class:`~.AmazonProduct`. | [
"Search",
"and",
"return",
"first",
"N",
"results",
".."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L277-L288 |
251,212 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | LXMLWrapper._safe_get_element_date | def _safe_get_element_date(self, path, root=None):
"""Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None.
"""
value = self._safe_get_element_text(path=path, root=root)
if value is not None:
try:
value = dateutil.parser.parse(value)
if value:
value = value.date()
except ValueError:
value = None
return value | python | def _safe_get_element_date(self, path, root=None):
value = self._safe_get_element_text(path=path, root=root)
if value is not None:
try:
value = dateutil.parser.parse(value)
if value:
value = value.date()
except ValueError:
value = None
return value | [
"def",
"_safe_get_element_date",
"(",
"self",
",",
"path",
",",
"root",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"path",
"=",
"path",
",",
"root",
"=",
"root",
")",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"value",
")",
"if",
"value",
":",
"value",
"=",
"value",
".",
"date",
"(",
")",
"except",
"ValueError",
":",
"value",
"=",
"None",
"return",
"value"
] | Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None. | [
"Safe",
"get",
"elemnent",
"date",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L490-L510 |
251,213 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonSearch.iterate_pages | def iterate_pages(self):
"""Iterate Pages.
A generator which iterates over all pages.
Keep in mind that Amazon limits the number of pages it makes available.
:return:
Yields lxml root elements.
"""
try:
while not self.is_last_page:
self.current_page += 1
yield self._query(ItemPage=self.current_page, **self.kwargs)
except NoMorePages:
pass | python | def iterate_pages(self):
try:
while not self.is_last_page:
self.current_page += 1
yield self._query(ItemPage=self.current_page, **self.kwargs)
except NoMorePages:
pass | [
"def",
"iterate_pages",
"(",
"self",
")",
":",
"try",
":",
"while",
"not",
"self",
".",
"is_last_page",
":",
"self",
".",
"current_page",
"+=",
"1",
"yield",
"self",
".",
"_query",
"(",
"ItemPage",
"=",
"self",
".",
"current_page",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
"except",
"NoMorePages",
":",
"pass"
] | Iterate Pages.
A generator which iterates over all pages.
Keep in mind that Amazon limits the number of pages it makes available.
:return:
Yields lxml root elements. | [
"Iterate",
"Pages",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L549-L563 |
251,214 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonBrowseNode.ancestor | def ancestor(self):
"""This browse node's immediate ancestor in the browse node tree.
:return:
The ancestor as an :class:`~.AmazonBrowseNode`, or None.
"""
ancestors = getattr(self.parsed_response, 'Ancestors', None)
if hasattr(ancestors, 'BrowseNode'):
return AmazonBrowseNode(ancestors['BrowseNode'])
return None | python | def ancestor(self):
ancestors = getattr(self.parsed_response, 'Ancestors', None)
if hasattr(ancestors, 'BrowseNode'):
return AmazonBrowseNode(ancestors['BrowseNode'])
return None | [
"def",
"ancestor",
"(",
"self",
")",
":",
"ancestors",
"=",
"getattr",
"(",
"self",
".",
"parsed_response",
",",
"'Ancestors'",
",",
"None",
")",
"if",
"hasattr",
"(",
"ancestors",
",",
"'BrowseNode'",
")",
":",
"return",
"AmazonBrowseNode",
"(",
"ancestors",
"[",
"'BrowseNode'",
"]",
")",
"return",
"None"
] | This browse node's immediate ancestor in the browse node tree.
:return:
The ancestor as an :class:`~.AmazonBrowseNode`, or None. | [
"This",
"browse",
"node",
"s",
"immediate",
"ancestor",
"in",
"the",
"browse",
"node",
"tree",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L624-L633 |
251,215 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonBrowseNode.ancestors | def ancestors(self):
"""A list of this browse node's ancestors in the browse node tree.
:return:
List of :class:`~.AmazonBrowseNode` objects.
"""
ancestors = []
node = self.ancestor
while node is not None:
ancestors.append(node)
node = node.ancestor
return ancestors | python | def ancestors(self):
ancestors = []
node = self.ancestor
while node is not None:
ancestors.append(node)
node = node.ancestor
return ancestors | [
"def",
"ancestors",
"(",
"self",
")",
":",
"ancestors",
"=",
"[",
"]",
"node",
"=",
"self",
".",
"ancestor",
"while",
"node",
"is",
"not",
"None",
":",
"ancestors",
".",
"append",
"(",
"node",
")",
"node",
"=",
"node",
".",
"ancestor",
"return",
"ancestors"
] | A list of this browse node's ancestors in the browse node tree.
:return:
List of :class:`~.AmazonBrowseNode` objects. | [
"A",
"list",
"of",
"this",
"browse",
"node",
"s",
"ancestors",
"in",
"the",
"browse",
"node",
"tree",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L636-L647 |
251,216 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonBrowseNode.children | def children(self):
"""This browse node's children in the browse node tree.
:return:
A list of this browse node's children in the browse node tree.
"""
children = []
child_nodes = getattr(self.parsed_response, 'Children')
for child in getattr(child_nodes, 'BrowseNode', []):
children.append(AmazonBrowseNode(child))
return children | python | def children(self):
children = []
child_nodes = getattr(self.parsed_response, 'Children')
for child in getattr(child_nodes, 'BrowseNode', []):
children.append(AmazonBrowseNode(child))
return children | [
"def",
"children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"child_nodes",
"=",
"getattr",
"(",
"self",
".",
"parsed_response",
",",
"'Children'",
")",
"for",
"child",
"in",
"getattr",
"(",
"child_nodes",
",",
"'BrowseNode'",
",",
"[",
"]",
")",
":",
"children",
".",
"append",
"(",
"AmazonBrowseNode",
"(",
"child",
")",
")",
"return",
"children"
] | This browse node's children in the browse node tree.
:return:
A list of this browse node's children in the browse node tree. | [
"This",
"browse",
"node",
"s",
"children",
"in",
"the",
"browse",
"node",
"tree",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L650-L660 |
251,217 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.price_and_currency | def price_and_currency(self):
"""Get Offer Price and Currency.
Return price according to the following process:
* If product has a sale return Sales Price, otherwise,
* Return Price, otherwise,
* Return lowest offer price, otherwise,
* Return None.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.CurrencyCode')
else:
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.CurrencyCode')
else:
price = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.Amount')
currency = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.CurrencyCode')
if price:
dprice = Decimal(
price) / 100 if 'JP' not in self.region else Decimal(price)
return dprice, currency
else:
return None, None | python | def price_and_currency(self):
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.CurrencyCode')
else:
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.CurrencyCode')
else:
price = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.Amount')
currency = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.CurrencyCode')
if price:
dprice = Decimal(
price) / 100 if 'JP' not in self.region else Decimal(price)
return dprice, currency
else:
return None, None | [
"def",
"price_and_currency",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.Amount'",
")",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.CurrencyCode'",
")",
"if",
"price",
":",
"dprice",
"=",
"Decimal",
"(",
"price",
")",
"/",
"100",
"if",
"'JP'",
"not",
"in",
"self",
".",
"region",
"else",
"Decimal",
"(",
"price",
")",
"return",
"dprice",
",",
"currency",
"else",
":",
"return",
"None",
",",
"None"
] | Get Offer Price and Currency.
Return price according to the following process:
* If product has a sale return Sales Price, otherwise,
* Return Price, otherwise,
* Return lowest offer price, otherwise,
* Return None.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string). | [
"Get",
"Offer",
"Price",
"and",
"Currency",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L687-L724 |
251,218 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.reviews | def reviews(self):
"""Customer Reviews.
Get a iframe URL for customer reviews.
:return:
A tuple of: has_reviews (bool), reviews url (string)
"""
iframe = self._safe_get_element_text('CustomerReviews.IFrameURL')
has_reviews = self._safe_get_element_text('CustomerReviews.HasReviews')
if has_reviews is not None and has_reviews == 'true':
has_reviews = True
else:
has_reviews = False
return has_reviews, iframe | python | def reviews(self):
iframe = self._safe_get_element_text('CustomerReviews.IFrameURL')
has_reviews = self._safe_get_element_text('CustomerReviews.HasReviews')
if has_reviews is not None and has_reviews == 'true':
has_reviews = True
else:
has_reviews = False
return has_reviews, iframe | [
"def",
"reviews",
"(",
"self",
")",
":",
"iframe",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'CustomerReviews.IFrameURL'",
")",
"has_reviews",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'CustomerReviews.HasReviews'",
")",
"if",
"has_reviews",
"is",
"not",
"None",
"and",
"has_reviews",
"==",
"'true'",
":",
"has_reviews",
"=",
"True",
"else",
":",
"has_reviews",
"=",
"False",
"return",
"has_reviews",
",",
"iframe"
] | Customer Reviews.
Get a iframe URL for customer reviews.
:return:
A tuple of: has_reviews (bool), reviews url (string) | [
"Customer",
"Reviews",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L954-L968 |
251,219 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.editorial_reviews | def editorial_reviews(self):
"""Editorial Review.
Returns a list of all editorial reviews.
:return:
A list containing:
Editorial Review (string)
"""
result = []
reviews_node = self._safe_get_element('EditorialReviews')
if reviews_node is not None:
for review_node in reviews_node.iterchildren():
content_node = getattr(review_node, 'Content')
if content_node is not None:
result.append(content_node.text)
return result | python | def editorial_reviews(self):
result = []
reviews_node = self._safe_get_element('EditorialReviews')
if reviews_node is not None:
for review_node in reviews_node.iterchildren():
content_node = getattr(review_node, 'Content')
if content_node is not None:
result.append(content_node.text)
return result | [
"def",
"editorial_reviews",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"reviews_node",
"=",
"self",
".",
"_safe_get_element",
"(",
"'EditorialReviews'",
")",
"if",
"reviews_node",
"is",
"not",
"None",
":",
"for",
"review_node",
"in",
"reviews_node",
".",
"iterchildren",
"(",
")",
":",
"content_node",
"=",
"getattr",
"(",
"review_node",
",",
"'Content'",
")",
"if",
"content_node",
"is",
"not",
"None",
":",
"result",
".",
"append",
"(",
"content_node",
".",
"text",
")",
"return",
"result"
] | Editorial Review.
Returns a list of all editorial reviews.
:return:
A list containing:
Editorial Review (string) | [
"Editorial",
"Review",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1069-L1087 |
251,220 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.list_price | def list_price(self):
"""List Price.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount')
currency = self._safe_get_element_text(
'ItemAttributes.ListPrice.CurrencyCode')
if price:
dprice = Decimal(
price) / 100 if 'JP' not in self.region else Decimal(price)
return dprice, currency
else:
return None, None | python | def list_price(self):
price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount')
currency = self._safe_get_element_text(
'ItemAttributes.ListPrice.CurrencyCode')
if price:
dprice = Decimal(
price) / 100 if 'JP' not in self.region else Decimal(price)
return dprice, currency
else:
return None, None | [
"def",
"list_price",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'ItemAttributes.ListPrice.Amount'",
")",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'ItemAttributes.ListPrice.CurrencyCode'",
")",
"if",
"price",
":",
"dprice",
"=",
"Decimal",
"(",
"price",
")",
"/",
"100",
"if",
"'JP'",
"not",
"in",
"self",
".",
"region",
"else",
"Decimal",
"(",
"price",
")",
"return",
"dprice",
",",
"currency",
"else",
":",
"return",
"None",
",",
"None"
] | List Price.
:return:
A tuple containing:
1. Decimal representation of price.
2. ISO Currency code (string). | [
"List",
"Price",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1124-L1141 |
251,221 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.get_parent | def get_parent(self):
"""Get Parent.
Fetch parent product if it exists.
Use `parent_asin` to check if a parent exist before fetching.
:return:
An instance of :class:`~.AmazonProduct` representing the
parent product.
"""
if not self.parent:
parent = self._safe_get_element('ParentASIN')
if parent:
self.parent = self.api.lookup(ItemId=parent)
return self.parent | python | def get_parent(self):
if not self.parent:
parent = self._safe_get_element('ParentASIN')
if parent:
self.parent = self.api.lookup(ItemId=parent)
return self.parent | [
"def",
"get_parent",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"parent",
"=",
"self",
".",
"_safe_get_element",
"(",
"'ParentASIN'",
")",
"if",
"parent",
":",
"self",
".",
"parent",
"=",
"self",
".",
"api",
".",
"lookup",
"(",
"ItemId",
"=",
"parent",
")",
"return",
"self",
".",
"parent"
] | Get Parent.
Fetch parent product if it exists.
Use `parent_asin` to check if a parent exist before fetching.
:return:
An instance of :class:`~.AmazonProduct` representing the
parent product. | [
"Get",
"Parent",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1196-L1210 |
251,222 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.browse_nodes | def browse_nodes(self):
"""Browse Nodes.
:return:
A list of :class:`~.AmazonBrowseNode` objects.
"""
root = self._safe_get_element('BrowseNodes')
if root is None:
return []
return [AmazonBrowseNode(child) for child in root.iterchildren()] | python | def browse_nodes(self):
root = self._safe_get_element('BrowseNodes')
if root is None:
return []
return [AmazonBrowseNode(child) for child in root.iterchildren()] | [
"def",
"browse_nodes",
"(",
"self",
")",
":",
"root",
"=",
"self",
".",
"_safe_get_element",
"(",
"'BrowseNodes'",
")",
"if",
"root",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"[",
"AmazonBrowseNode",
"(",
"child",
")",
"for",
"child",
"in",
"root",
".",
"iterchildren",
"(",
")",
"]"
] | Browse Nodes.
:return:
A list of :class:`~.AmazonBrowseNode` objects. | [
"Browse",
"Nodes",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1213-L1223 |
251,223 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.images | def images(self):
"""List of images for a response.
When using lookup with RespnoseGroup 'Images', you'll get a
list of images. Parse them so they are returned in an easily
used list format.
:return:
A list of `ObjectifiedElement` images
"""
try:
images = [image for image in self._safe_get_element(
'ImageSets.ImageSet')]
except TypeError: # No images in this ResponseGroup
images = []
return images | python | def images(self):
try:
images = [image for image in self._safe_get_element(
'ImageSets.ImageSet')]
except TypeError: # No images in this ResponseGroup
images = []
return images | [
"def",
"images",
"(",
"self",
")",
":",
"try",
":",
"images",
"=",
"[",
"image",
"for",
"image",
"in",
"self",
".",
"_safe_get_element",
"(",
"'ImageSets.ImageSet'",
")",
"]",
"except",
"TypeError",
":",
"# No images in this ResponseGroup",
"images",
"=",
"[",
"]",
"return",
"images"
] | List of images for a response.
When using lookup with RespnoseGroup 'Images', you'll get a
list of images. Parse them so they are returned in an easily
used list format.
:return:
A list of `ObjectifiedElement` images | [
"List",
"of",
"images",
"for",
"a",
"response",
".",
"When",
"using",
"lookup",
"with",
"RespnoseGroup",
"Images",
"you",
"ll",
"get",
"a",
"list",
"of",
"images",
".",
"Parse",
"them",
"so",
"they",
"are",
"returned",
"in",
"an",
"easily",
"used",
"list",
"format",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1226-L1240 |
251,224 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.actors | def actors(self):
"""Movie Actors.
:return:
A list of actors names.
"""
result = []
actors = self._safe_get_element('ItemAttributes.Actor') or []
for actor in actors:
result.append(actor.text)
return result | python | def actors(self):
result = []
actors = self._safe_get_element('ItemAttributes.Actor') or []
for actor in actors:
result.append(actor.text)
return result | [
"def",
"actors",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"actors",
"=",
"self",
".",
"_safe_get_element",
"(",
"'ItemAttributes.Actor'",
")",
"or",
"[",
"]",
"for",
"actor",
"in",
"actors",
":",
"result",
".",
"append",
"(",
"actor",
".",
"text",
")",
"return",
"result"
] | Movie Actors.
:return:
A list of actors names. | [
"Movie",
"Actors",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1252-L1262 |
251,225 | yoavaviram/python-amazon-simple-product-api | amazon/api.py | AmazonProduct.directors | def directors(self):
"""Movie Directors.
:return:
A list of directors for a movie.
"""
result = []
directors = self._safe_get_element('ItemAttributes.Director') or []
for director in directors:
result.append(director.text)
return result | python | def directors(self):
result = []
directors = self._safe_get_element('ItemAttributes.Director') or []
for director in directors:
result.append(director.text)
return result | [
"def",
"directors",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"directors",
"=",
"self",
".",
"_safe_get_element",
"(",
"'ItemAttributes.Director'",
")",
"or",
"[",
"]",
"for",
"director",
"in",
"directors",
":",
"result",
".",
"append",
"(",
"director",
".",
"text",
")",
"return",
"result"
] | Movie Directors.
:return:
A list of directors for a movie. | [
"Movie",
"Directors",
"."
] | f1cb0e209145fcfac9444e4c733dd19deb59d31a | https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L1265-L1275 |
251,226 | etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.getMibSymbol | def getMibSymbol(self):
"""Returns MIB variable symbolic identification.
Returns
-------
str
MIB module name
str
MIB variable symbolic name
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
class instance representing MIB variable instance index.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('1.3.6.1.2.1.1.1.0')
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))
>>>
"""
if self._state & self.ST_CLEAN:
return self._modName, self._symName, self._indices
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | python | def getMibSymbol(self):
if self._state & self.ST_CLEAN:
return self._modName, self._symName, self._indices
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | [
"def",
"getMibSymbol",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
".",
"_modName",
",",
"self",
".",
"_symName",
",",
"self",
".",
"_indices",
"else",
":",
"raise",
"SmiError",
"(",
"'%s object not fully initialized'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | Returns MIB variable symbolic identification.
Returns
-------
str
MIB module name
str
MIB variable symbolic name
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
class instance representing MIB variable instance index.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('1.3.6.1.2.1.1.1.0')
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))
>>> | [
"Returns",
"MIB",
"variable",
"symbolic",
"identification",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L98-L128 |
251,227 | etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.getOid | def getOid(self):
"""Returns OID identifying MIB variable.
Returns
-------
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
full OID identifying MIB variable including possible index part.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
ObjectName('1.3.6.1.2.1.1.1.0')
>>>
"""
if self._state & self.ST_CLEAN:
return self._oid
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | python | def getOid(self):
if self._state & self.ST_CLEAN:
return self._oid
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | [
"def",
"getOid",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
".",
"_oid",
"else",
":",
"raise",
"SmiError",
"(",
"'%s object not fully initialized'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | Returns OID identifying MIB variable.
Returns
-------
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
full OID identifying MIB variable including possible index part.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
ObjectName('1.3.6.1.2.1.1.1.0')
>>> | [
"Returns",
"OID",
"identifying",
"MIB",
"variable",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L130-L156 |
251,228 | etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.getLabel | def getLabel(self):
"""Returns symbolic path to this MIB variable.
Meaning a sequence of symbolic identifications for each of parent
MIB objects in MIB tree.
Returns
-------
tuple
sequence of names of nodes in a MIB tree from the top of the tree
towards this MIB variable.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Notes
-----
Returned sequence may not contain full path to this MIB variable
if some symbols are now known at the moment of MIB look up.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
>>>
"""
if self._state & self.ST_CLEAN:
return self._label
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | python | def getLabel(self):
if self._state & self.ST_CLEAN:
return self._label
else:
raise SmiError(
'%s object not fully initialized' % self.__class__.__name__) | [
"def",
"getLabel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
".",
"_label",
"else",
":",
"raise",
"SmiError",
"(",
"'%s object not fully initialized'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | Returns symbolic path to this MIB variable.
Meaning a sequence of symbolic identifications for each of parent
MIB objects in MIB tree.
Returns
-------
tuple
sequence of names of nodes in a MIB tree from the top of the tree
towards this MIB variable.
Raises
------
SmiError
If MIB variable conversion has not been performed.
Notes
-----
Returned sequence may not contain full path to this MIB variable
if some symbols are now known at the moment of MIB look up.
Examples
--------
>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
>>> | [
"Returns",
"symbolic",
"path",
"to",
"this",
"MIB",
"variable",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L158-L193 |
251,229 | etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.addMibSource | def addMibSource(self, *mibSources):
"""Adds path to repository to search PySNMP MIB files.
Parameters
----------
*mibSources :
one or more paths to search or Python package names to import
and search for PySNMP MIB modules.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Notes
-----
Normally, ASN.1-to-Python MIB modules conversion is performed
automatically through PySNMP/PySMI interaction. ASN1 MIB modules
could also be manually compiled into Python via the
`mibdump.py <http://snmplabs.com/pysmi/mibdump.html>`_
tool.
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
"""
if self._mibSourcesToAdd is None:
self._mibSourcesToAdd = mibSources
else:
self._mibSourcesToAdd += mibSources
return self | python | def addMibSource(self, *mibSources):
if self._mibSourcesToAdd is None:
self._mibSourcesToAdd = mibSources
else:
self._mibSourcesToAdd += mibSources
return self | [
"def",
"addMibSource",
"(",
"self",
",",
"*",
"mibSources",
")",
":",
"if",
"self",
".",
"_mibSourcesToAdd",
"is",
"None",
":",
"self",
".",
"_mibSourcesToAdd",
"=",
"mibSources",
"else",
":",
"self",
".",
"_mibSourcesToAdd",
"+=",
"mibSources",
"return",
"self"
] | Adds path to repository to search PySNMP MIB files.
Parameters
----------
*mibSources :
one or more paths to search or Python package names to import
and search for PySNMP MIB modules.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Notes
-----
Normally, ASN.1-to-Python MIB modules conversion is performed
automatically through PySNMP/PySMI interaction. ASN1 MIB modules
could also be manually compiled into Python via the
`mibdump.py <http://snmplabs.com/pysmi/mibdump.html>`_
tool.
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>> | [
"Adds",
"path",
"to",
"repository",
"to",
"search",
"PySNMP",
"MIB",
"files",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L253-L287 |
251,230 | etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectIdentity.loadMibs | def loadMibs(self, *modNames):
"""Schedules search and load of given MIB modules.
Parameters
----------
*modNames:
one or more MIB module names to load up and use for MIB
variables resolution purposes.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').loadMibs('IF-MIB', 'TCP-MIB')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
"""
if self._modNamesToLoad is None:
self._modNamesToLoad = modNames
else:
self._modNamesToLoad += modNames
return self | python | def loadMibs(self, *modNames):
if self._modNamesToLoad is None:
self._modNamesToLoad = modNames
else:
self._modNamesToLoad += modNames
return self | [
"def",
"loadMibs",
"(",
"self",
",",
"*",
"modNames",
")",
":",
"if",
"self",
".",
"_modNamesToLoad",
"is",
"None",
":",
"self",
".",
"_modNamesToLoad",
"=",
"modNames",
"else",
":",
"self",
".",
"_modNamesToLoad",
"+=",
"modNames",
"return",
"self"
] | Schedules search and load of given MIB modules.
Parameters
----------
*modNames:
one or more MIB module names to load up and use for MIB
variables resolution purposes.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
reference to itself
Examples
--------
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').loadMibs('IF-MIB', 'TCP-MIB')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>> | [
"Schedules",
"search",
"and",
"load",
"of",
"given",
"MIB",
"modules",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L290-L316 |
251,231 | etingof/pysnmp | pysnmp/smi/rfc1902.py | ObjectType.resolveWithMib | def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID and associated value conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method involves
:py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib`
method invocation.
Examples
--------
>>> from pysmi.hlapi import varbinds
>>> mibViewController = varbinds.AbstractVarBinds.getMibViewController( engine )
>>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386')
>>> objectType.resolveWithMib(mibViewController)
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386'))
>>> str(objectType)
'SNMPv2-MIB::sysDescr."0" = Linux i386'
>>>
"""
if self._state & self.ST_CLEAM:
return self
self._args[0].resolveWithMib(mibViewController)
MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols(
'SNMPv2-SMI', 'MibScalar', 'MibTableColumn')
if not isinstance(self._args[0].getMibNode(),
(MibScalar, MibTableColumn)):
if not isinstance(self._args[1], AbstractSimpleAsn1Item):
raise SmiError('MIB object %r is not OBJECT-TYPE '
'(MIB not loaded?)' % (self._args[0],))
self._state |= self.ST_CLEAM
return self
if isinstance(self._args[1], (rfc1905.UnSpecified,
rfc1905.NoSuchObject,
rfc1905.NoSuchInstance,
rfc1905.EndOfMibView)):
self._state |= self.ST_CLEAM
return self
syntax = self._args[0].getMibNode().getSyntax()
try:
self._args[1] = syntax.clone(self._args[1])
except PyAsn1Error as exc:
raise SmiError(
'MIB object %r having type %r failed to cast value '
'%r: %s' % (self._args[0].prettyPrint(),
syntax.__class__.__name__, self._args[1], exc))
if rfc1902.ObjectIdentifier().isSuperTypeOf(
self._args[1], matchConstraints=False):
self._args[1] = ObjectIdentity(
self._args[1]).resolveWithMib(mibViewController)
self._state |= self.ST_CLEAM
debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r syntax is %r' % (self._args[0], self._args[1]))
return self | python | def resolveWithMib(self, mibViewController):
if self._state & self.ST_CLEAM:
return self
self._args[0].resolveWithMib(mibViewController)
MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols(
'SNMPv2-SMI', 'MibScalar', 'MibTableColumn')
if not isinstance(self._args[0].getMibNode(),
(MibScalar, MibTableColumn)):
if not isinstance(self._args[1], AbstractSimpleAsn1Item):
raise SmiError('MIB object %r is not OBJECT-TYPE '
'(MIB not loaded?)' % (self._args[0],))
self._state |= self.ST_CLEAM
return self
if isinstance(self._args[1], (rfc1905.UnSpecified,
rfc1905.NoSuchObject,
rfc1905.NoSuchInstance,
rfc1905.EndOfMibView)):
self._state |= self.ST_CLEAM
return self
syntax = self._args[0].getMibNode().getSyntax()
try:
self._args[1] = syntax.clone(self._args[1])
except PyAsn1Error as exc:
raise SmiError(
'MIB object %r having type %r failed to cast value '
'%r: %s' % (self._args[0].prettyPrint(),
syntax.__class__.__name__, self._args[1], exc))
if rfc1902.ObjectIdentifier().isSuperTypeOf(
self._args[1], matchConstraints=False):
self._args[1] = ObjectIdentity(
self._args[1]).resolveWithMib(mibViewController)
self._state |= self.ST_CLEAM
debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r syntax is %r' % (self._args[0], self._args[1]))
return self | [
"def",
"resolveWithMib",
"(",
"self",
",",
"mibViewController",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAM",
":",
"return",
"self",
"self",
".",
"_args",
"[",
"0",
"]",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"MibScalar",
",",
"MibTableColumn",
"=",
"mibViewController",
".",
"mibBuilder",
".",
"importSymbols",
"(",
"'SNMPv2-SMI'",
",",
"'MibScalar'",
",",
"'MibTableColumn'",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_args",
"[",
"0",
"]",
".",
"getMibNode",
"(",
")",
",",
"(",
"MibScalar",
",",
"MibTableColumn",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
",",
"AbstractSimpleAsn1Item",
")",
":",
"raise",
"SmiError",
"(",
"'MIB object %r is not OBJECT-TYPE '",
"'(MIB not loaded?)'",
"%",
"(",
"self",
".",
"_args",
"[",
"0",
"]",
",",
")",
")",
"self",
".",
"_state",
"|=",
"self",
".",
"ST_CLEAM",
"return",
"self",
"if",
"isinstance",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
",",
"(",
"rfc1905",
".",
"UnSpecified",
",",
"rfc1905",
".",
"NoSuchObject",
",",
"rfc1905",
".",
"NoSuchInstance",
",",
"rfc1905",
".",
"EndOfMibView",
")",
")",
":",
"self",
".",
"_state",
"|=",
"self",
".",
"ST_CLEAM",
"return",
"self",
"syntax",
"=",
"self",
".",
"_args",
"[",
"0",
"]",
".",
"getMibNode",
"(",
")",
".",
"getSyntax",
"(",
")",
"try",
":",
"self",
".",
"_args",
"[",
"1",
"]",
"=",
"syntax",
".",
"clone",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
")",
"except",
"PyAsn1Error",
"as",
"exc",
":",
"raise",
"SmiError",
"(",
"'MIB object %r having type %r failed to cast value '",
"'%r: %s'",
"%",
"(",
"self",
".",
"_args",
"[",
"0",
"]",
".",
"prettyPrint",
"(",
")",
",",
"syntax",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"_args",
"[",
"1",
"]",
",",
"exc",
")",
")",
"if",
"rfc1902",
".",
"ObjectIdentifier",
"(",
")",
".",
"isSuperTypeOf",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
",",
"matchConstraints",
"=",
"False",
")",
":",
"self",
".",
"_args",
"[",
"1",
"]",
"=",
"ObjectIdentity",
"(",
"self",
".",
"_args",
"[",
"1",
"]",
")",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"self",
".",
"_state",
"|=",
"self",
".",
"ST_CLEAM",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_MIB",
"and",
"debug",
".",
"logger",
"(",
"'resolved %r syntax is %r'",
"%",
"(",
"self",
".",
"_args",
"[",
"0",
"]",
",",
"self",
".",
"_args",
"[",
"1",
"]",
")",
")",
"return",
"self"
] | Perform MIB variable ID and associated value conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method involves
:py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib`
method invocation.
Examples
--------
>>> from pysmi.hlapi import varbinds
>>> mibViewController = varbinds.AbstractVarBinds.getMibViewController( engine )
>>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386')
>>> objectType.resolveWithMib(mibViewController)
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386'))
>>> str(objectType)
'SNMPv2-MIB::sysDescr."0" = Linux i386'
>>> | [
"Perform",
"MIB",
"variable",
"ID",
"and",
"associated",
"value",
"conversion",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L911-L993 |
251,232 | etingof/pysnmp | pysnmp/smi/rfc1902.py | NotificationType.addVarBinds | def addVarBinds(self, *varBinds):
"""Appends variable-binding to notification.
Parameters
----------
*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Notes
-----
This method can be used to add custom variable-bindings to
notification message in addition to MIB variables specified
in NOTIFICATION-TYPE->OBJECTS clause.
Examples
--------
>>> nt = NotificationType(ObjectIdentity('IP-MIB', 'linkDown'))
>>> nt.addVarBinds(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), (), {})
>>>
"""
debug.logger & debug.FLAG_MIB and debug.logger(
'additional var-binds: %r' % (varBinds,))
if self._state & self.ST_CLEAN:
raise SmiError(
'%s object is already sealed' % self.__class__.__name__)
else:
self._additionalVarBinds.extend(varBinds)
return self | python | def addVarBinds(self, *varBinds):
debug.logger & debug.FLAG_MIB and debug.logger(
'additional var-binds: %r' % (varBinds,))
if self._state & self.ST_CLEAN:
raise SmiError(
'%s object is already sealed' % self.__class__.__name__)
else:
self._additionalVarBinds.extend(varBinds)
return self | [
"def",
"addVarBinds",
"(",
"self",
",",
"*",
"varBinds",
")",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_MIB",
"and",
"debug",
".",
"logger",
"(",
"'additional var-binds: %r'",
"%",
"(",
"varBinds",
",",
")",
")",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"raise",
"SmiError",
"(",
"'%s object is already sealed'",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"self",
".",
"_additionalVarBinds",
".",
"extend",
"(",
"varBinds",
")",
"return",
"self"
] | Appends variable-binding to notification.
Parameters
----------
*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Notes
-----
This method can be used to add custom variable-bindings to
notification message in addition to MIB variables specified
in NOTIFICATION-TYPE->OBJECTS clause.
Examples
--------
>>> nt = NotificationType(ObjectIdentity('IP-MIB', 'linkDown'))
>>> nt.addVarBinds(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), (), {})
>>> | [
"Appends",
"variable",
"-",
"binding",
"to",
"notification",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L1096-L1133 |
251,233 | etingof/pysnmp | pysnmp/smi/rfc1902.py | NotificationType.resolveWithMib | def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID conversion and notification objects expansion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method might cause the following sequence of
events (exact details depends on many factors):
* :py:meth:`pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib` is called
* MIB variables names are read from NOTIFICATION-TYPE->OBJECTS clause,
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instances are created
from MIB variable OID and `indexInstance` suffix.
* `objects` dictionary is queried for each MIB variable OID,
acquired values are added to corresponding MIB variable
Examples
--------
>>> notificationType = NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))
>>> notificationType.resolveWithMib(mibViewController)
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>>
"""
if self._state & self.ST_CLEAN:
return self
self._objectIdentity.resolveWithMib(mibViewController)
self._varBinds.append(
ObjectType(ObjectIdentity(v2c.apiTrapPDU.snmpTrapOID),
self._objectIdentity).resolveWithMib(mibViewController))
SmiNotificationType, = mibViewController.mibBuilder.importSymbols(
'SNMPv2-SMI', 'NotificationType')
mibNode = self._objectIdentity.getMibNode()
varBindsLocation = {}
if isinstance(mibNode, SmiNotificationType):
for notificationObject in mibNode.getObjects():
objectIdentity = ObjectIdentity(
*notificationObject + self._instanceIndex)
objectIdentity.resolveWithMib(mibViewController)
objectType = ObjectType(
objectIdentity, self._objects.get(
notificationObject, rfc1905.unSpecified))
objectType.resolveWithMib(mibViewController)
self._varBinds.append(objectType)
varBindsLocation[objectIdentity] = len(self._varBinds) - 1
else:
debug.logger & debug.FLAG_MIB and debug.logger(
'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not '
'loaded?)' % (self._objectIdentity,))
for varBinds in self._additionalVarBinds:
if not isinstance(varBinds, ObjectType):
varBinds = ObjectType(ObjectIdentity(varBinds[0]), varBinds[1])
varBinds.resolveWithMib(mibViewController)
if varBinds[0] in varBindsLocation:
self._varBinds[varBindsLocation[varBinds[0]]] = varBinds
else:
self._varBinds.append(varBinds)
self._additionalVarBinds = []
self._state |= self.ST_CLEAN
debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r into %r' % (self._objectIdentity, self._varBinds))
return self | python | def resolveWithMib(self, mibViewController):
if self._state & self.ST_CLEAN:
return self
self._objectIdentity.resolveWithMib(mibViewController)
self._varBinds.append(
ObjectType(ObjectIdentity(v2c.apiTrapPDU.snmpTrapOID),
self._objectIdentity).resolveWithMib(mibViewController))
SmiNotificationType, = mibViewController.mibBuilder.importSymbols(
'SNMPv2-SMI', 'NotificationType')
mibNode = self._objectIdentity.getMibNode()
varBindsLocation = {}
if isinstance(mibNode, SmiNotificationType):
for notificationObject in mibNode.getObjects():
objectIdentity = ObjectIdentity(
*notificationObject + self._instanceIndex)
objectIdentity.resolveWithMib(mibViewController)
objectType = ObjectType(
objectIdentity, self._objects.get(
notificationObject, rfc1905.unSpecified))
objectType.resolveWithMib(mibViewController)
self._varBinds.append(objectType)
varBindsLocation[objectIdentity] = len(self._varBinds) - 1
else:
debug.logger & debug.FLAG_MIB and debug.logger(
'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not '
'loaded?)' % (self._objectIdentity,))
for varBinds in self._additionalVarBinds:
if not isinstance(varBinds, ObjectType):
varBinds = ObjectType(ObjectIdentity(varBinds[0]), varBinds[1])
varBinds.resolveWithMib(mibViewController)
if varBinds[0] in varBindsLocation:
self._varBinds[varBindsLocation[varBinds[0]]] = varBinds
else:
self._varBinds.append(varBinds)
self._additionalVarBinds = []
self._state |= self.ST_CLEAN
debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r into %r' % (self._objectIdentity, self._varBinds))
return self | [
"def",
"resolveWithMib",
"(",
"self",
",",
"mibViewController",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
"self",
".",
"_objectIdentity",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"self",
".",
"_varBinds",
".",
"append",
"(",
"ObjectType",
"(",
"ObjectIdentity",
"(",
"v2c",
".",
"apiTrapPDU",
".",
"snmpTrapOID",
")",
",",
"self",
".",
"_objectIdentity",
")",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
")",
"SmiNotificationType",
",",
"=",
"mibViewController",
".",
"mibBuilder",
".",
"importSymbols",
"(",
"'SNMPv2-SMI'",
",",
"'NotificationType'",
")",
"mibNode",
"=",
"self",
".",
"_objectIdentity",
".",
"getMibNode",
"(",
")",
"varBindsLocation",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"mibNode",
",",
"SmiNotificationType",
")",
":",
"for",
"notificationObject",
"in",
"mibNode",
".",
"getObjects",
"(",
")",
":",
"objectIdentity",
"=",
"ObjectIdentity",
"(",
"*",
"notificationObject",
"+",
"self",
".",
"_instanceIndex",
")",
"objectIdentity",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"objectType",
"=",
"ObjectType",
"(",
"objectIdentity",
",",
"self",
".",
"_objects",
".",
"get",
"(",
"notificationObject",
",",
"rfc1905",
".",
"unSpecified",
")",
")",
"objectType",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"self",
".",
"_varBinds",
".",
"append",
"(",
"objectType",
")",
"varBindsLocation",
"[",
"objectIdentity",
"]",
"=",
"len",
"(",
"self",
".",
"_varBinds",
")",
"-",
"1",
"else",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_MIB",
"and",
"debug",
".",
"logger",
"(",
"'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not '",
"'loaded?)'",
"%",
"(",
"self",
".",
"_objectIdentity",
",",
")",
")",
"for",
"varBinds",
"in",
"self",
".",
"_additionalVarBinds",
":",
"if",
"not",
"isinstance",
"(",
"varBinds",
",",
"ObjectType",
")",
":",
"varBinds",
"=",
"ObjectType",
"(",
"ObjectIdentity",
"(",
"varBinds",
"[",
"0",
"]",
")",
",",
"varBinds",
"[",
"1",
"]",
")",
"varBinds",
".",
"resolveWithMib",
"(",
"mibViewController",
")",
"if",
"varBinds",
"[",
"0",
"]",
"in",
"varBindsLocation",
":",
"self",
".",
"_varBinds",
"[",
"varBindsLocation",
"[",
"varBinds",
"[",
"0",
"]",
"]",
"]",
"=",
"varBinds",
"else",
":",
"self",
".",
"_varBinds",
".",
"append",
"(",
"varBinds",
")",
"self",
".",
"_additionalVarBinds",
"=",
"[",
"]",
"self",
".",
"_state",
"|=",
"self",
".",
"ST_CLEAN",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_MIB",
"and",
"debug",
".",
"logger",
"(",
"'resolved %r into %r'",
"%",
"(",
"self",
".",
"_objectIdentity",
",",
"self",
".",
"_varBinds",
")",
")",
"return",
"self"
] | Perform MIB variable ID conversion and notification objects expansion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py:class:`~pysnmp.smi.rfc1902.NotificationType`
reference to itself
Raises
------
SmiError
In case of fatal MIB hanling errora
Notes
-----
Calling this method might cause the following sequence of
events (exact details depends on many factors):
* :py:meth:`pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib` is called
* MIB variables names are read from NOTIFICATION-TYPE->OBJECTS clause,
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instances are created
from MIB variable OID and `indexInstance` suffix.
* `objects` dictionary is queried for each MIB variable OID,
acquired values are added to corresponding MIB variable
Examples
--------
>>> notificationType = NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))
>>> notificationType.resolveWithMib(mibViewController)
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>> | [
"Perform",
"MIB",
"variable",
"ID",
"conversion",
"and",
"notification",
"objects",
"expansion",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/rfc1902.py#L1224-L1319 |
251,234 | etingof/pysnmp | pysnmp/proto/rfc1902.py | Integer32.withValues | def withValues(cls, *values):
"""Creates a subclass with discreet values constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values)
X.__name__ = cls.__name__
return X | python | def withValues(cls, *values):
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values)
X.__name__ = cls.__name__
return X | [
"def",
"withValues",
"(",
"cls",
",",
"*",
"values",
")",
":",
"class",
"X",
"(",
"cls",
")",
":",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"SingleValueConstraint",
"(",
"*",
"values",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Creates a subclass with discreet values constraint. | [
"Creates",
"a",
"subclass",
"with",
"discreet",
"values",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L93-L102 |
251,235 | etingof/pysnmp | pysnmp/proto/rfc1902.py | Integer32.withRange | def withRange(cls, minimum, maximum):
"""Creates a subclass with value range constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueRangeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | python | def withRange(cls, minimum, maximum):
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueRangeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | [
"def",
"withRange",
"(",
"cls",
",",
"minimum",
",",
"maximum",
")",
":",
"class",
"X",
"(",
"cls",
")",
":",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"ValueRangeConstraint",
"(",
"minimum",
",",
"maximum",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Creates a subclass with value range constraint. | [
"Creates",
"a",
"subclass",
"with",
"value",
"range",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L105-L114 |
251,236 | etingof/pysnmp | pysnmp/proto/rfc1902.py | Integer.withNamedValues | def withNamedValues(cls, **values):
"""Create a subclass with discreet named values constraint.
Reduce fully duplicate enumerations along the way.
"""
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.NamedValues(*enums)
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values.values())
X.__name__ = cls.__name__
return X | python | def withNamedValues(cls, **values):
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.NamedValues(*enums)
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values.values())
X.__name__ = cls.__name__
return X | [
"def",
"withNamedValues",
"(",
"cls",
",",
"*",
"*",
"values",
")",
":",
"enums",
"=",
"set",
"(",
"cls",
".",
"namedValues",
".",
"items",
"(",
")",
")",
"enums",
".",
"update",
"(",
"values",
".",
"items",
"(",
")",
")",
"class",
"X",
"(",
"cls",
")",
":",
"namedValues",
"=",
"namedval",
".",
"NamedValues",
"(",
"*",
"enums",
")",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"SingleValueConstraint",
"(",
"*",
"values",
".",
"values",
"(",
")",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Create a subclass with discreet named values constraint.
Reduce fully duplicate enumerations along the way. | [
"Create",
"a",
"subclass",
"with",
"discreet",
"named",
"values",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L162-L177 |
251,237 | etingof/pysnmp | pysnmp/proto/rfc1902.py | OctetString.withSize | def withSize(cls, minimum, maximum):
"""Creates a subclass with value size constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueSizeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | python | def withSize(cls, minimum, maximum):
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.ValueSizeConstraint(
minimum, maximum)
X.__name__ = cls.__name__
return X | [
"def",
"withSize",
"(",
"cls",
",",
"minimum",
",",
"maximum",
")",
":",
"class",
"X",
"(",
"cls",
")",
":",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"ValueSizeConstraint",
"(",
"minimum",
",",
"maximum",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Creates a subclass with value size constraint. | [
"Creates",
"a",
"subclass",
"with",
"value",
"size",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L248-L257 |
251,238 | etingof/pysnmp | pysnmp/proto/rfc1902.py | Bits.withNamedBits | def withNamedBits(cls, **values):
"""Creates a subclass with discreet named bits constraint.
Reduce fully duplicate enumerations along the way.
"""
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.NamedValues(*enums)
X.__name__ = cls.__name__
return X | python | def withNamedBits(cls, **values):
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.NamedValues(*enums)
X.__name__ = cls.__name__
return X | [
"def",
"withNamedBits",
"(",
"cls",
",",
"*",
"*",
"values",
")",
":",
"enums",
"=",
"set",
"(",
"cls",
".",
"namedValues",
".",
"items",
"(",
")",
")",
"enums",
".",
"update",
"(",
"values",
".",
"items",
"(",
")",
")",
"class",
"X",
"(",
"cls",
")",
":",
"namedValues",
"=",
"namedval",
".",
"NamedValues",
"(",
"*",
"enums",
")",
"X",
".",
"__name__",
"=",
"cls",
".",
"__name__",
"return",
"X"
] | Creates a subclass with discreet named bits constraint.
Reduce fully duplicate enumerations along the way. | [
"Creates",
"a",
"subclass",
"with",
"discreet",
"named",
"bits",
"constraint",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L698-L710 |
251,239 | etingof/pysnmp | pysnmp/smi/builder.py | MibBuilder.loadModule | def loadModule(self, modName, **userCtx):
"""Load and execute MIB modules as Python code"""
for mibSource in self._mibSources:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: trying %s at %s' % (modName, mibSource))
try:
codeObj, sfx = mibSource.read(modName)
except IOError as exc:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: read %s from %s failed: '
'%s' % (modName, mibSource, exc))
continue
modPath = mibSource.fullPath(modName, sfx)
if modPath in self._modPathsSeen:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: seen %s' % modPath)
break
else:
self._modPathsSeen.add(modPath)
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: evaluating %s' % modPath)
g = {'mibBuilder': self,
'userCtx': userCtx}
try:
exec(codeObj, g)
except Exception:
self._modPathsSeen.remove(modPath)
raise error.MibLoadError(
'MIB module "%s" load error: '
'%s' % (modPath, traceback.format_exception(*sys.exc_info())))
self._modSeen[modName] = modPath
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: loaded %s' % modPath)
break
if modName not in self._modSeen:
raise error.MibNotFoundError(
'MIB file "%s" not found in search path '
'(%s)' % (modName and modName + ".py[co]", ', '.join(
[str(x) for x in self._mibSources])))
return self | python | def loadModule(self, modName, **userCtx):
for mibSource in self._mibSources:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: trying %s at %s' % (modName, mibSource))
try:
codeObj, sfx = mibSource.read(modName)
except IOError as exc:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: read %s from %s failed: '
'%s' % (modName, mibSource, exc))
continue
modPath = mibSource.fullPath(modName, sfx)
if modPath in self._modPathsSeen:
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: seen %s' % modPath)
break
else:
self._modPathsSeen.add(modPath)
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: evaluating %s' % modPath)
g = {'mibBuilder': self,
'userCtx': userCtx}
try:
exec(codeObj, g)
except Exception:
self._modPathsSeen.remove(modPath)
raise error.MibLoadError(
'MIB module "%s" load error: '
'%s' % (modPath, traceback.format_exception(*sys.exc_info())))
self._modSeen[modName] = modPath
debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: loaded %s' % modPath)
break
if modName not in self._modSeen:
raise error.MibNotFoundError(
'MIB file "%s" not found in search path '
'(%s)' % (modName and modName + ".py[co]", ', '.join(
[str(x) for x in self._mibSources])))
return self | [
"def",
"loadModule",
"(",
"self",
",",
"modName",
",",
"*",
"*",
"userCtx",
")",
":",
"for",
"mibSource",
"in",
"self",
".",
"_mibSources",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: trying %s at %s'",
"%",
"(",
"modName",
",",
"mibSource",
")",
")",
"try",
":",
"codeObj",
",",
"sfx",
"=",
"mibSource",
".",
"read",
"(",
"modName",
")",
"except",
"IOError",
"as",
"exc",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: read %s from %s failed: '",
"'%s'",
"%",
"(",
"modName",
",",
"mibSource",
",",
"exc",
")",
")",
"continue",
"modPath",
"=",
"mibSource",
".",
"fullPath",
"(",
"modName",
",",
"sfx",
")",
"if",
"modPath",
"in",
"self",
".",
"_modPathsSeen",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: seen %s'",
"%",
"modPath",
")",
"break",
"else",
":",
"self",
".",
"_modPathsSeen",
".",
"add",
"(",
"modPath",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: evaluating %s'",
"%",
"modPath",
")",
"g",
"=",
"{",
"'mibBuilder'",
":",
"self",
",",
"'userCtx'",
":",
"userCtx",
"}",
"try",
":",
"exec",
"(",
"codeObj",
",",
"g",
")",
"except",
"Exception",
":",
"self",
".",
"_modPathsSeen",
".",
"remove",
"(",
"modPath",
")",
"raise",
"error",
".",
"MibLoadError",
"(",
"'MIB module \"%s\" load error: '",
"'%s'",
"%",
"(",
"modPath",
",",
"traceback",
".",
"format_exception",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
")",
")",
"self",
".",
"_modSeen",
"[",
"modName",
"]",
"=",
"modPath",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_BLD",
"and",
"debug",
".",
"logger",
"(",
"'loadModule: loaded %s'",
"%",
"modPath",
")",
"break",
"if",
"modName",
"not",
"in",
"self",
".",
"_modSeen",
":",
"raise",
"error",
".",
"MibNotFoundError",
"(",
"'MIB file \"%s\" not found in search path '",
"'(%s)'",
"%",
"(",
"modName",
"and",
"modName",
"+",
"\".py[co]\"",
",",
"', '",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"_mibSources",
"]",
")",
")",
")",
"return",
"self"
] | Load and execute MIB modules as Python code | [
"Load",
"and",
"execute",
"MIB",
"modules",
"as",
"Python",
"code"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/builder.py#L354-L407 |
251,240 | etingof/pysnmp | pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py | nextCmd | def nextCmd(snmpDispatcher, authData, transportTarget,
*varBinds, **options):
"""Create a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpDispatcher : :py:class:`~pysnmp.hlapi.snmpDispatcher`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication: str
True value indicates SNMP engine error.
errorStatus: str
True value indicates SNMP PDU error.
errorIndex: int
Non-zero value refers to `varBinds[errorIndex-1]`
varBindTable: tuple
A 2-dimensional array of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing a table of MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi.v1arch import *
>>>
>>> g = nextCmd(snmpDispatcher(),
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
>>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))])
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))])
"""
def cbFun(*args, **kwargs):
response[:] = args + (kwargs.get('nextVarBinds', ()),)
options['cbFun'] = cbFun
lexicographicMode = options.pop('lexicographicMode', True)
maxRows = options.pop('maxRows', 0)
maxCalls = options.pop('maxCalls', 0)
initialVarBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
totalRows = totalCalls = 0
errorIndication, errorStatus, errorIndex, varBindTable = None, 0, 0, ()
response = []
while True:
if not varBinds:
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
cmdgen.nextCmd(snmpDispatcher, authData, transportTarget,
*[(x[0], Null('')) for x in varBinds], **options)
snmpDispatcher.transportDispatcher.runDispatcher()
errorIndication, errorStatus, errorIndex, varBindTable, varBinds = response
if errorIndication:
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
else:
varBindRow = varBindTable and varBindTable[-1]
if not lexicographicMode:
for idx, varBind in enumerate(varBindRow):
name, val = varBind
if not isinstance(val, Null):
if initialVarBinds[idx][0].isPrefixOf(name):
break
else:
return
for varBindRow in varBindTable:
nextVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow)
if nextVarBinds:
initialVarBinds = varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
totalRows += 1
totalCalls += 1
if maxRows and totalRows >= maxRows:
return
if maxCalls and totalCalls >= maxCalls:
return | python | def nextCmd(snmpDispatcher, authData, transportTarget,
*varBinds, **options):
def cbFun(*args, **kwargs):
response[:] = args + (kwargs.get('nextVarBinds', ()),)
options['cbFun'] = cbFun
lexicographicMode = options.pop('lexicographicMode', True)
maxRows = options.pop('maxRows', 0)
maxCalls = options.pop('maxCalls', 0)
initialVarBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
totalRows = totalCalls = 0
errorIndication, errorStatus, errorIndex, varBindTable = None, 0, 0, ()
response = []
while True:
if not varBinds:
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
cmdgen.nextCmd(snmpDispatcher, authData, transportTarget,
*[(x[0], Null('')) for x in varBinds], **options)
snmpDispatcher.transportDispatcher.runDispatcher()
errorIndication, errorStatus, errorIndex, varBindTable, varBinds = response
if errorIndication:
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex,
varBindTable and varBindTable[0] or [])
return
else:
varBindRow = varBindTable and varBindTable[-1]
if not lexicographicMode:
for idx, varBind in enumerate(varBindRow):
name, val = varBind
if not isinstance(val, Null):
if initialVarBinds[idx][0].isPrefixOf(name):
break
else:
return
for varBindRow in varBindTable:
nextVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow)
if nextVarBinds:
initialVarBinds = varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
totalRows += 1
totalCalls += 1
if maxRows and totalRows >= maxRows:
return
if maxCalls and totalCalls >= maxCalls:
return | [
"def",
"nextCmd",
"(",
"snmpDispatcher",
",",
"authData",
",",
"transportTarget",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"cbFun",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"[",
":",
"]",
"=",
"args",
"+",
"(",
"kwargs",
".",
"get",
"(",
"'nextVarBinds'",
",",
"(",
")",
")",
",",
")",
"options",
"[",
"'cbFun'",
"]",
"=",
"cbFun",
"lexicographicMode",
"=",
"options",
".",
"pop",
"(",
"'lexicographicMode'",
",",
"True",
")",
"maxRows",
"=",
"options",
".",
"pop",
"(",
"'maxRows'",
",",
"0",
")",
"maxCalls",
"=",
"options",
".",
"pop",
"(",
"'maxCalls'",
",",
"0",
")",
"initialVarBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpDispatcher",
".",
"cache",
",",
"varBinds",
")",
"totalRows",
"=",
"totalCalls",
"=",
"0",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
"=",
"None",
",",
"0",
",",
"0",
",",
"(",
")",
"response",
"=",
"[",
"]",
"while",
"True",
":",
"if",
"not",
"varBinds",
":",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
"and",
"varBindTable",
"[",
"0",
"]",
"or",
"[",
"]",
")",
"return",
"cmdgen",
".",
"nextCmd",
"(",
"snmpDispatcher",
",",
"authData",
",",
"transportTarget",
",",
"*",
"[",
"(",
"x",
"[",
"0",
"]",
",",
"Null",
"(",
"''",
")",
")",
"for",
"x",
"in",
"varBinds",
"]",
",",
"*",
"*",
"options",
")",
"snmpDispatcher",
".",
"transportDispatcher",
".",
"runDispatcher",
"(",
")",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
",",
"varBinds",
"=",
"response",
"if",
"errorIndication",
":",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
"and",
"varBindTable",
"[",
"0",
"]",
"or",
"[",
"]",
")",
"return",
"elif",
"errorStatus",
":",
"if",
"errorStatus",
"==",
"2",
":",
"# Hide SNMPv1 noSuchName error which leaks in here",
"# from SNMPv1 Agent through internal pysnmp proxy.",
"errorStatus",
"=",
"errorStatus",
".",
"clone",
"(",
"0",
")",
"errorIndex",
"=",
"errorIndex",
".",
"clone",
"(",
"0",
")",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
"and",
"varBindTable",
"[",
"0",
"]",
"or",
"[",
"]",
")",
"return",
"else",
":",
"varBindRow",
"=",
"varBindTable",
"and",
"varBindTable",
"[",
"-",
"1",
"]",
"if",
"not",
"lexicographicMode",
":",
"for",
"idx",
",",
"varBind",
"in",
"enumerate",
"(",
"varBindRow",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"if",
"not",
"isinstance",
"(",
"val",
",",
"Null",
")",
":",
"if",
"initialVarBinds",
"[",
"idx",
"]",
"[",
"0",
"]",
".",
"isPrefixOf",
"(",
"name",
")",
":",
"break",
"else",
":",
"return",
"for",
"varBindRow",
"in",
"varBindTable",
":",
"nextVarBinds",
"=",
"(",
"yield",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindRow",
")",
"if",
"nextVarBinds",
":",
"initialVarBinds",
"=",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpDispatcher",
".",
"cache",
",",
"nextVarBinds",
")",
"totalRows",
"+=",
"1",
"totalCalls",
"+=",
"1",
"if",
"maxRows",
"and",
"totalRows",
">=",
"maxRows",
":",
"return",
"if",
"maxCalls",
"and",
"totalCalls",
">=",
"maxCalls",
":",
"return"
] | Create a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpDispatcher : :py:class:`~pysnmp.hlapi.snmpDispatcher`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication: str
True value indicates SNMP engine error.
errorStatus: str
True value indicates SNMP PDU error.
errorIndex: int
Non-zero value refers to `varBinds[errorIndex-1]`
varBindTable: tuple
A 2-dimensional array of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing a table of MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi.v1arch import *
>>>
>>> g = nextCmd(snmpDispatcher(),
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
>>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))])
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) | [
"Create",
"a",
"generator",
"to",
"perform",
"one",
"or",
"more",
"SNMP",
"GETNEXT",
"queries",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py#L201-L363 |
251,241 | etingof/pysnmp | pysnmp/proto/rfc3412.py | MsgAndPduDispatcher.registerContextEngineId | def registerContextEngineId(self, contextEngineId, pduTypes, processPdu):
"""Register application with dispatcher"""
# 4.3.2 -> no-op
# 4.3.3
for pduType in pduTypes:
k = contextEngineId, pduType
if k in self._appsRegistration:
raise error.ProtocolError(
'Duplicate registration %r/%s' % (contextEngineId, pduType))
# 4.3.4
self._appsRegistration[k] = processPdu
debug.logger & debug.FLAG_DSP and debug.logger(
'registerContextEngineId: contextEngineId %r pduTypes '
'%s' % (contextEngineId, pduTypes)) | python | def registerContextEngineId(self, contextEngineId, pduTypes, processPdu):
# 4.3.2 -> no-op
# 4.3.3
for pduType in pduTypes:
k = contextEngineId, pduType
if k in self._appsRegistration:
raise error.ProtocolError(
'Duplicate registration %r/%s' % (contextEngineId, pduType))
# 4.3.4
self._appsRegistration[k] = processPdu
debug.logger & debug.FLAG_DSP and debug.logger(
'registerContextEngineId: contextEngineId %r pduTypes '
'%s' % (contextEngineId, pduTypes)) | [
"def",
"registerContextEngineId",
"(",
"self",
",",
"contextEngineId",
",",
"pduTypes",
",",
"processPdu",
")",
":",
"# 4.3.2 -> no-op",
"# 4.3.3",
"for",
"pduType",
"in",
"pduTypes",
":",
"k",
"=",
"contextEngineId",
",",
"pduType",
"if",
"k",
"in",
"self",
".",
"_appsRegistration",
":",
"raise",
"error",
".",
"ProtocolError",
"(",
"'Duplicate registration %r/%s'",
"%",
"(",
"contextEngineId",
",",
"pduType",
")",
")",
"# 4.3.4",
"self",
".",
"_appsRegistration",
"[",
"k",
"]",
"=",
"processPdu",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_DSP",
"and",
"debug",
".",
"logger",
"(",
"'registerContextEngineId: contextEngineId %r pduTypes '",
"'%s'",
"%",
"(",
"contextEngineId",
",",
"pduTypes",
")",
")"
] | Register application with dispatcher | [
"Register",
"application",
"with",
"dispatcher"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc3412.py#L64-L80 |
251,242 | etingof/pysnmp | pysnmp/proto/rfc3412.py | MsgAndPduDispatcher.unregisterContextEngineId | def unregisterContextEngineId(self, contextEngineId, pduTypes):
"""Unregister application with dispatcher"""
# 4.3.4
if contextEngineId is None:
# Default to local snmpEngineId
contextEngineId, = self.mibInstrumController.mibBuilder.importSymbols(
'__SNMP-FRAMEWORK-MIB', 'snmpEngineID')
for pduType in pduTypes:
k = contextEngineId, pduType
if k in self._appsRegistration:
del self._appsRegistration[k]
debug.logger & debug.FLAG_DSP and debug.logger(
'unregisterContextEngineId: contextEngineId %r pduTypes '
'%s' % (contextEngineId, pduTypes)) | python | def unregisterContextEngineId(self, contextEngineId, pduTypes):
# 4.3.4
if contextEngineId is None:
# Default to local snmpEngineId
contextEngineId, = self.mibInstrumController.mibBuilder.importSymbols(
'__SNMP-FRAMEWORK-MIB', 'snmpEngineID')
for pduType in pduTypes:
k = contextEngineId, pduType
if k in self._appsRegistration:
del self._appsRegistration[k]
debug.logger & debug.FLAG_DSP and debug.logger(
'unregisterContextEngineId: contextEngineId %r pduTypes '
'%s' % (contextEngineId, pduTypes)) | [
"def",
"unregisterContextEngineId",
"(",
"self",
",",
"contextEngineId",
",",
"pduTypes",
")",
":",
"# 4.3.4",
"if",
"contextEngineId",
"is",
"None",
":",
"# Default to local snmpEngineId",
"contextEngineId",
",",
"=",
"self",
".",
"mibInstrumController",
".",
"mibBuilder",
".",
"importSymbols",
"(",
"'__SNMP-FRAMEWORK-MIB'",
",",
"'snmpEngineID'",
")",
"for",
"pduType",
"in",
"pduTypes",
":",
"k",
"=",
"contextEngineId",
",",
"pduType",
"if",
"k",
"in",
"self",
".",
"_appsRegistration",
":",
"del",
"self",
".",
"_appsRegistration",
"[",
"k",
"]",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_DSP",
"and",
"debug",
".",
"logger",
"(",
"'unregisterContextEngineId: contextEngineId %r pduTypes '",
"'%s'",
"%",
"(",
"contextEngineId",
",",
"pduTypes",
")",
")"
] | Unregister application with dispatcher | [
"Unregister",
"application",
"with",
"dispatcher"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc3412.py#L83-L99 |
251,243 | etingof/pysnmp | pysnmp/hlapi/v3arch/twisted/ntforg.py | sendNotification | def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyType, *varBinds, **options):
"""Sends SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM message
(:RFC:`1905#section-4.2.6`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine: :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData: :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData: :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
notifyType: str
Indicates type of notification to be sent. Recognized literal
values are *trap* or *inform*.
\*varBinds: :class:`tuple` of OID-value pairs or :py:class:`~pysnmp.smi.rfc1902.ObjectType` or :py:class:`~pysnmp.smi.rfc1902.NotificationType`
One or more objects representing MIB variables to place
into SNMP notification. It could be tuples of OID-values
or :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
of :py:class:`~pysnmp.smi.rfc1902.NotificationType` objects.
SNMP Notification PDU includes some housekeeping items that
are required for SNMP to function.
Agent information:
* SNMPv2-MIB::sysUpTime.0 = <agent uptime>
* SNMPv2-SMI::snmpTrapOID.0 = {SNMPv2-MIB::coldStart, ...}
Applicable to SNMP v1 TRAP:
* SNMP-COMMUNITY-MIB::snmpTrapAddress.0 = <agent-IP>
* SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = <snmp-community-name>
* SNMP-COMMUNITY-MIB::snmpTrapEnterprise.0 = <enterprise-OID>
.. note::
Unless user passes some of these variable-bindings, `.sendNotification()`
call will fill in the missing items.
User variable-bindings:
* SNMPv2-SMI::NOTIFICATION-TYPE
* SNMPv2-SMI::OBJECT-TYPE
.. note::
The :py:class:`~pysnmp.smi.rfc1902.NotificationType` object ensures
properly formed SNMP notification (to comply MIB definition). If you
build notification PDU out of :py:class:`~pysnmp.smi.rfc1902.ObjectType`
objects or simple tuples of OID-value objects, it is your responsibility
to provide well-formed notification payload.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) : A sequence of
:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing
MIB variables returned in SNMP response.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBinds) = args
... print(errorStatus, errorIndex, varBind)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = sendNotification(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 162)),
... ContextData(),
... 'trap',
... NotificationType(ObjectIdentity('IF-MIB', 'linkDown')))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, [])
"""
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBinds, cbCtx):
lookupMib, deferred = cbCtx
if errorIndication:
deferred.errback(Failure(errorIndication))
else:
try:
varBinds = VB_PROCESSOR.unmakeVarBinds(
snmpEngine.cache, varBinds, lookupMib)
except Exception as e:
deferred.errback(Failure(e))
else:
deferred.callback((errorStatus, errorIndex, varBinds))
notifyName = LCD.configure(snmpEngine, authData, transportTarget,
notifyType, contextData.contextName)
def __trapFun(deferred):
deferred.callback((0, 0, []))
varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds)
deferred = Deferred()
ntforg.NotificationOriginator().sendVarBinds(
snmpEngine, notifyName, contextData.contextEngineId,
contextData.contextName, varBinds, __cbFun,
(options.get('lookupMib', True), deferred)
)
if notifyType == 'trap':
reactor.callLater(0, __trapFun, deferred)
return deferred | python | def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyType, *varBinds, **options):
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBinds, cbCtx):
lookupMib, deferred = cbCtx
if errorIndication:
deferred.errback(Failure(errorIndication))
else:
try:
varBinds = VB_PROCESSOR.unmakeVarBinds(
snmpEngine.cache, varBinds, lookupMib)
except Exception as e:
deferred.errback(Failure(e))
else:
deferred.callback((errorStatus, errorIndex, varBinds))
notifyName = LCD.configure(snmpEngine, authData, transportTarget,
notifyType, contextData.contextName)
def __trapFun(deferred):
deferred.callback((0, 0, []))
varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds)
deferred = Deferred()
ntforg.NotificationOriginator().sendVarBinds(
snmpEngine, notifyName, contextData.contextEngineId,
contextData.contextName, varBinds, __cbFun,
(options.get('lookupMib', True), deferred)
)
if notifyType == 'trap':
reactor.callLater(0, __trapFun, deferred)
return deferred | [
"def",
"sendNotification",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"notifyType",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"__cbFun",
"(",
"snmpEngine",
",",
"sendRequestHandle",
",",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
",",
"cbCtx",
")",
":",
"lookupMib",
",",
"deferred",
"=",
"cbCtx",
"if",
"errorIndication",
":",
"deferred",
".",
"errback",
"(",
"Failure",
"(",
"errorIndication",
")",
")",
"else",
":",
"try",
":",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"unmakeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
",",
"lookupMib",
")",
"except",
"Exception",
"as",
"e",
":",
"deferred",
".",
"errback",
"(",
"Failure",
"(",
"e",
")",
")",
"else",
":",
"deferred",
".",
"callback",
"(",
"(",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
")",
")",
"notifyName",
"=",
"LCD",
".",
"configure",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"notifyType",
",",
"contextData",
".",
"contextName",
")",
"def",
"__trapFun",
"(",
"deferred",
")",
":",
"deferred",
".",
"callback",
"(",
"(",
"0",
",",
"0",
",",
"[",
"]",
")",
")",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
")",
"deferred",
"=",
"Deferred",
"(",
")",
"ntforg",
".",
"NotificationOriginator",
"(",
")",
".",
"sendVarBinds",
"(",
"snmpEngine",
",",
"notifyName",
",",
"contextData",
".",
"contextEngineId",
",",
"contextData",
".",
"contextName",
",",
"varBinds",
",",
"__cbFun",
",",
"(",
"options",
".",
"get",
"(",
"'lookupMib'",
",",
"True",
")",
",",
"deferred",
")",
")",
"if",
"notifyType",
"==",
"'trap'",
":",
"reactor",
".",
"callLater",
"(",
"0",
",",
"__trapFun",
",",
"deferred",
")",
"return",
"deferred"
] | Sends SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM message
(:RFC:`1905#section-4.2.6`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine: :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData: :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData: :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
notifyType: str
Indicates type of notification to be sent. Recognized literal
values are *trap* or *inform*.
\*varBinds: :class:`tuple` of OID-value pairs or :py:class:`~pysnmp.smi.rfc1902.ObjectType` or :py:class:`~pysnmp.smi.rfc1902.NotificationType`
One or more objects representing MIB variables to place
into SNMP notification. It could be tuples of OID-values
or :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
of :py:class:`~pysnmp.smi.rfc1902.NotificationType` objects.
SNMP Notification PDU includes some housekeeping items that
are required for SNMP to function.
Agent information:
* SNMPv2-MIB::sysUpTime.0 = <agent uptime>
* SNMPv2-SMI::snmpTrapOID.0 = {SNMPv2-MIB::coldStart, ...}
Applicable to SNMP v1 TRAP:
* SNMP-COMMUNITY-MIB::snmpTrapAddress.0 = <agent-IP>
* SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = <snmp-community-name>
* SNMP-COMMUNITY-MIB::snmpTrapEnterprise.0 = <enterprise-OID>
.. note::
Unless user passes some of these variable-bindings, `.sendNotification()`
call will fill in the missing items.
User variable-bindings:
* SNMPv2-SMI::NOTIFICATION-TYPE
* SNMPv2-SMI::OBJECT-TYPE
.. note::
The :py:class:`~pysnmp.smi.rfc1902.NotificationType` object ensures
properly formed SNMP notification (to comply MIB definition). If you
build notification PDU out of :py:class:`~pysnmp.smi.rfc1902.ObjectType`
objects or simple tuples of OID-value objects, it is your responsibility
to provide well-formed notification payload.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) : A sequence of
:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing
MIB variables returned in SNMP response.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBinds) = args
... print(errorStatus, errorIndex, varBind)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = sendNotification(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 162)),
... ContextData(),
... 'trap',
... NotificationType(ObjectIdentity('IF-MIB', 'linkDown')))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, []) | [
"Sends",
"SNMP",
"notification",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/twisted/ntforg.py#L25-L189 |
251,244 | etingof/pysnmp | pysnmp/hlapi/v3arch/twisted/cmdgen.py | nextCmd | def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Performs SNMP GETNEXT query.
Based on passed parameters, prepares SNMP GETNEXT packet
(:RFC:`1905#section-4.2.2`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) :
A sequence of sequences (e.g. 2-D array) of
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response.
Inner sequences represent table rows and ordered exactly the same
as `varBinds` in request. Response to GETNEXT always contain
a single row.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBindTable) = args
... print(errorStatus, errorIndex, varBindTable)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
"""
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
lookupMib, deferred = cbCtx
if (options.get('ignoreNonIncreasingOid', False) and errorIndication
and isinstance(errorIndication, errind.OidNotIncreasing)):
errorIndication = None
if errorIndication:
deferred.errback(Failure(errorIndication))
else:
try:
varBindTable = [
VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache,
varBindTableRow, lookupMib)
for varBindTableRow in varBindTable
]
except Exception as e:
deferred.errback(Failure(e))
else:
deferred.callback((errorStatus, errorIndex, varBindTable))
addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds)
deferred = Deferred()
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName, varBinds, __cbFun,
(options.get('lookupMib', True), deferred))
return deferred | python | def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
def __cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
lookupMib, deferred = cbCtx
if (options.get('ignoreNonIncreasingOid', False) and errorIndication
and isinstance(errorIndication, errind.OidNotIncreasing)):
errorIndication = None
if errorIndication:
deferred.errback(Failure(errorIndication))
else:
try:
varBindTable = [
VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache,
varBindTableRow, lookupMib)
for varBindTableRow in varBindTable
]
except Exception as e:
deferred.errback(Failure(e))
else:
deferred.callback((errorStatus, errorIndex, varBindTable))
addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds)
deferred = Deferred()
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName, varBinds, __cbFun,
(options.get('lookupMib', True), deferred))
return deferred | [
"def",
"nextCmd",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"__cbFun",
"(",
"snmpEngine",
",",
"sendRequestHandle",
",",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
",",
"cbCtx",
")",
":",
"lookupMib",
",",
"deferred",
"=",
"cbCtx",
"if",
"(",
"options",
".",
"get",
"(",
"'ignoreNonIncreasingOid'",
",",
"False",
")",
"and",
"errorIndication",
"and",
"isinstance",
"(",
"errorIndication",
",",
"errind",
".",
"OidNotIncreasing",
")",
")",
":",
"errorIndication",
"=",
"None",
"if",
"errorIndication",
":",
"deferred",
".",
"errback",
"(",
"Failure",
"(",
"errorIndication",
")",
")",
"else",
":",
"try",
":",
"varBindTable",
"=",
"[",
"VB_PROCESSOR",
".",
"unmakeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBindTableRow",
",",
"lookupMib",
")",
"for",
"varBindTableRow",
"in",
"varBindTable",
"]",
"except",
"Exception",
"as",
"e",
":",
"deferred",
".",
"errback",
"(",
"Failure",
"(",
"e",
")",
")",
"else",
":",
"deferred",
".",
"callback",
"(",
"(",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
")",
")",
"addrName",
",",
"paramsName",
"=",
"LCD",
".",
"configure",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
".",
"contextName",
")",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
")",
"deferred",
"=",
"Deferred",
"(",
")",
"cmdgen",
".",
"NextCommandGenerator",
"(",
")",
".",
"sendVarBinds",
"(",
"snmpEngine",
",",
"addrName",
",",
"contextData",
".",
"contextEngineId",
",",
"contextData",
".",
"contextName",
",",
"varBinds",
",",
"__cbFun",
",",
"(",
"options",
".",
"get",
"(",
"'lookupMib'",
",",
"True",
")",
",",
"deferred",
")",
")",
"return",
"deferred"
] | Performs SNMP GETNEXT query.
Based on passed parameters, prepares SNMP GETNEXT packet
(:RFC:`1905#section-4.2.2`) and schedules its transmission by
:mod:`twisted` I/O framework at a later point of time.
Parameters
----------
snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
Returns
-------
deferred : :class:`~twisted.internet.defer.Deferred`
Twisted Deferred object representing work-in-progress. User
is expected to attach his own `success` and `error` callback
functions to the Deferred object though
:meth:`~twisted.internet.defer.Deferred.addCallbacks` method.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
User `success` callback is called with the following tuple as
its first argument:
* errorStatus (str) : True value indicates SNMP PDU error.
* errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
* varBinds (tuple) :
A sequence of sequences (e.g. 2-D array) of
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response.
Inner sequences represent table rows and ordered exactly the same
as `varBinds` in request. Response to GETNEXT always contain
a single row.
User `error` callback is called with `errorIndication` object wrapped
in :class:`~twisted.python.failure.Failure` object.
Examples
--------
>>> from twisted.internet.task import react
>>> from pysnmp.hlapi.twisted import *
>>>
>>> def success(args):
... (errorStatus, errorIndex, varBindTable) = args
... print(errorStatus, errorIndex, varBindTable)
...
>>> def failure(errorIndication):
... print(errorIndication)
...
>>> def run(reactor):
... d = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))
... d.addCallback(success).addErrback(failure)
... return d
...
>>> react(run)
(0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]]) | [
"Performs",
"SNMP",
"GETNEXT",
"query",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/twisted/cmdgen.py#L268-L401 |
251,245 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | ManagedMibObject.getBranch | def getBranch(self, name, **context):
"""Return a branch of this tree where the 'name' OID may reside"""
for keyLen in self._vars.getKeysLens():
subName = name[:keyLen]
if subName in self._vars:
return self._vars[subName]
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | python | def getBranch(self, name, **context):
for keyLen in self._vars.getKeysLens():
subName = name[:keyLen]
if subName in self._vars:
return self._vars[subName]
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | [
"def",
"getBranch",
"(",
"self",
",",
"name",
",",
"*",
"*",
"context",
")",
":",
"for",
"keyLen",
"in",
"self",
".",
"_vars",
".",
"getKeysLens",
"(",
")",
":",
"subName",
"=",
"name",
"[",
":",
"keyLen",
"]",
"if",
"subName",
"in",
"self",
".",
"_vars",
":",
"return",
"self",
".",
"_vars",
"[",
"subName",
"]",
"raise",
"error",
".",
"NoSuchObjectError",
"(",
"name",
"=",
"name",
",",
"idx",
"=",
"context",
".",
"get",
"(",
"'idx'",
")",
")"
] | Return a branch of this tree where the 'name' OID may reside | [
"Return",
"a",
"branch",
"of",
"this",
"tree",
"where",
"the",
"name",
"OID",
"may",
"reside"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L455-L462 |
251,246 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | ManagedMibObject.getNode | def getNode(self, name, **context):
"""Return tree node found by name"""
if name == self.name:
return self
else:
return self.getBranch(name, **context).getNode(name, **context) | python | def getNode(self, name, **context):
if name == self.name:
return self
else:
return self.getBranch(name, **context).getNode(name, **context) | [
"def",
"getNode",
"(",
"self",
",",
"name",
",",
"*",
"*",
"context",
")",
":",
"if",
"name",
"==",
"self",
".",
"name",
":",
"return",
"self",
"else",
":",
"return",
"self",
".",
"getBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
".",
"getNode",
"(",
"name",
",",
"*",
"*",
"context",
")"
] | Return tree node found by name | [
"Return",
"tree",
"node",
"found",
"by",
"name"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L478-L483 |
251,247 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | ManagedMibObject.getNextNode | def getNextNode(self, name, **context):
"""Return tree node next to name"""
try:
nextNode = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
return self.getNextBranch(name, **context)
else:
try:
return nextNode.getNextNode(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
try:
return self._vars[self._vars.nextKey(nextNode.name)]
except KeyError:
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | python | def getNextNode(self, name, **context):
try:
nextNode = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
return self.getNextBranch(name, **context)
else:
try:
return nextNode.getNextNode(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
try:
return self._vars[self._vars.nextKey(nextNode.name)]
except KeyError:
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | [
"def",
"getNextNode",
"(",
"self",
",",
"name",
",",
"*",
"*",
"context",
")",
":",
"try",
":",
"nextNode",
"=",
"self",
".",
"getBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
"except",
"(",
"error",
".",
"NoSuchInstanceError",
",",
"error",
".",
"NoSuchObjectError",
")",
":",
"return",
"self",
".",
"getNextBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
"else",
":",
"try",
":",
"return",
"nextNode",
".",
"getNextNode",
"(",
"name",
",",
"*",
"*",
"context",
")",
"except",
"(",
"error",
".",
"NoSuchInstanceError",
",",
"error",
".",
"NoSuchObjectError",
")",
":",
"try",
":",
"return",
"self",
".",
"_vars",
"[",
"self",
".",
"_vars",
".",
"nextKey",
"(",
"nextNode",
".",
"name",
")",
"]",
"except",
"KeyError",
":",
"raise",
"error",
".",
"NoSuchObjectError",
"(",
"name",
"=",
"name",
",",
"idx",
"=",
"context",
".",
"get",
"(",
"'idx'",
")",
")"
] | Return tree node next to name | [
"Return",
"tree",
"node",
"next",
"to",
"name"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L485-L498 |
251,248 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | ManagedMibObject.writeCommit | def writeCommit(self, varBind, **context):
"""Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
Object Instance. When multiple Managed Objects Instances are modified at
once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to set
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
if idx in instances[self.ST_CREATE]:
self.createCommit(varBind, **context)
return
if idx in instances[self.ST_DESTROY]:
self.destroyCommit(varBind, **context)
return
try:
node = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError) as exc:
cbFun(varBind, **dict(context, error=exc))
else:
node.writeCommit(varBind, **context) | python | def writeCommit(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
if idx in instances[self.ST_CREATE]:
self.createCommit(varBind, **context)
return
if idx in instances[self.ST_DESTROY]:
self.destroyCommit(varBind, **context)
return
try:
node = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError) as exc:
cbFun(varBind, **dict(context, error=exc))
else:
node.writeCommit(varBind, **context) | [
"def",
"writeCommit",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: writeCommit(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"instances",
"=",
"context",
"[",
"'instances'",
"]",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"{",
"self",
".",
"ST_CREATE",
":",
"{",
"}",
",",
"self",
".",
"ST_DESTROY",
":",
"{",
"}",
"}",
")",
"idx",
"=",
"context",
"[",
"'idx'",
"]",
"if",
"idx",
"in",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
":",
"self",
".",
"createCommit",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"if",
"idx",
"in",
"instances",
"[",
"self",
".",
"ST_DESTROY",
"]",
":",
"self",
".",
"destroyCommit",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"try",
":",
"node",
"=",
"self",
".",
"getBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
"except",
"(",
"error",
".",
"NoSuchInstanceError",
",",
"error",
".",
"NoSuchObjectError",
")",
"as",
"exc",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"error",
"=",
"exc",
")",
")",
"else",
":",
"node",
".",
"writeCommit",
"(",
"varBind",
",",
"*",
"*",
"context",
")"
] | Commit new value of the Managed Object Instance.
Implements the second of the multi-step workflow of the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually modify the requested Managed
Object Instance. When multiple Managed Objects Instances are modified at
once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to set
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Commit",
"new",
"value",
"of",
"the",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L860-L925 |
251,249 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibScalar.readGet | def readGet(self, varBind, **context):
"""Read Managed Object Instance.
Implements the second of the two phases of the SNMP GET command
processing (:RFC:`1905#section-4.2.1`).
The goal of the second phase is to actually read the requested Managed
Object Instance. When multiple Managed Objects Instances are read at
once (likely coming all in one SNMP PDU), each of them has to run through
the first (*test*) and second (*read) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) has the same signature as
this method where `varBind` contains read Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: readGet(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
if name == self.name:
cbFun((name, exval.noSuchInstance), **context)
return
acFun = context.get('acFun')
if acFun:
if (self.maxAccess not in ('readonly', 'readwrite', 'readcreate') or
acFun('read', (name, self.syntax), **context)):
cbFun((name, exval.noSuchInstance), **context)
return
ManagedMibObject.readGet(self, varBind, **context) | python | def readGet(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: readGet(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
if name == self.name:
cbFun((name, exval.noSuchInstance), **context)
return
acFun = context.get('acFun')
if acFun:
if (self.maxAccess not in ('readonly', 'readwrite', 'readcreate') or
acFun('read', (name, self.syntax), **context)):
cbFun((name, exval.noSuchInstance), **context)
return
ManagedMibObject.readGet(self, varBind, **context) | [
"def",
"readGet",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: readGet(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"if",
"name",
"==",
"self",
".",
"name",
":",
"cbFun",
"(",
"(",
"name",
",",
"exval",
".",
"noSuchInstance",
")",
",",
"*",
"*",
"context",
")",
"return",
"acFun",
"=",
"context",
".",
"get",
"(",
"'acFun'",
")",
"if",
"acFun",
":",
"if",
"(",
"self",
".",
"maxAccess",
"not",
"in",
"(",
"'readonly'",
",",
"'readwrite'",
",",
"'readcreate'",
")",
"or",
"acFun",
"(",
"'read'",
",",
"(",
"name",
",",
"self",
".",
"syntax",
")",
",",
"*",
"*",
"context",
")",
")",
":",
"cbFun",
"(",
"(",
"name",
",",
"exval",
".",
"noSuchInstance",
")",
",",
"*",
"*",
"context",
")",
"return",
"ManagedMibObject",
".",
"readGet",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")"
] | Read Managed Object Instance.
Implements the second of the two phases of the SNMP GET command
processing (:RFC:`1905#section-4.2.1`).
The goal of the second phase is to actually read the requested Managed
Object Instance. When multiple Managed Objects Instances are read at
once (likely coming all in one SNMP PDU), each of them has to run through
the first (*test*) and second (*read) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) has the same signature as
this method where `varBind` contains read Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Read",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L1139-L1203 |
251,250 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibScalar.readGetNext | def readGetNext(self, varBind, **context):
"""Read the next Managed Object Instance.
Implements the second of the two phases of the SNMP GETNEXT command
processing (:RFC:`1905#section-4.2.2`).
The goal of the second phase is to actually read the Managed Object
Instance which is next in the MIB tree to the one being requested.
When multiple Managed Objects Instances are read at once (likely coming
all in one SNMP PDU), each of them has to run through the first
(*testnext*) and second (*getnext*) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance (the *next* one in the MIB tree
relative to the one being requested) or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the Managed Object Instance which is *next*
to the one being requested. If not supplied, no access control
will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) have the same signature
as this method where `varBind` contains read Managed Object Instance
value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: readGetNext(%s, %r)' % (self, name, val)))
acFun = context.get('acFun')
if acFun:
if (self.maxAccess not in ('readonly', 'readwrite', 'readcreate') or
acFun('read', (name, self.syntax), **context)):
nextName = context.get('nextName')
if nextName:
varBind = nextName, exval.noSuchInstance
else:
varBind = name, exval.endOfMibView
cbFun = context['cbFun']
cbFun(varBind, **context)
return
ManagedMibObject.readGetNext(self, varBind, **context) | python | def readGetNext(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: readGetNext(%s, %r)' % (self, name, val)))
acFun = context.get('acFun')
if acFun:
if (self.maxAccess not in ('readonly', 'readwrite', 'readcreate') or
acFun('read', (name, self.syntax), **context)):
nextName = context.get('nextName')
if nextName:
varBind = nextName, exval.noSuchInstance
else:
varBind = name, exval.endOfMibView
cbFun = context['cbFun']
cbFun(varBind, **context)
return
ManagedMibObject.readGetNext(self, varBind, **context) | [
"def",
"readGetNext",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: readGetNext(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"acFun",
"=",
"context",
".",
"get",
"(",
"'acFun'",
")",
"if",
"acFun",
":",
"if",
"(",
"self",
".",
"maxAccess",
"not",
"in",
"(",
"'readonly'",
",",
"'readwrite'",
",",
"'readcreate'",
")",
"or",
"acFun",
"(",
"'read'",
",",
"(",
"name",
",",
"self",
".",
"syntax",
")",
",",
"*",
"*",
"context",
")",
")",
":",
"nextName",
"=",
"context",
".",
"get",
"(",
"'nextName'",
")",
"if",
"nextName",
":",
"varBind",
"=",
"nextName",
",",
"exval",
".",
"noSuchInstance",
"else",
":",
"varBind",
"=",
"name",
",",
"exval",
".",
"endOfMibView",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"ManagedMibObject",
".",
"readGetNext",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")"
] | Read the next Managed Object Instance.
Implements the second of the two phases of the SNMP GETNEXT command
processing (:RFC:`1905#section-4.2.2`).
The goal of the second phase is to actually read the Managed Object
Instance which is next in the MIB tree to the one being requested.
When multiple Managed Objects Instances are read at once (likely coming
all in one SNMP PDU), each of them has to run through the first
(*testnext*) and second (*getnext*) phases successfully for the whole
read operation to succeed.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Beyond that, this object imposes access control logic towards the
underlying :class:`MibScalarInstance` objects by invoking the `acFun`
callable.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
Managed Object Instance to read
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass read Managed Object Instance (the *next* one in the MIB tree
relative to the one being requested) or an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the Managed Object Instance which is *next*
to the one being requested. If not supplied, no access control
will be performed.
Notes
-----
The callback functions (e.g. `cbFun`, `acFun`) have the same signature
as this method where `varBind` contains read Managed Object Instance
value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Read",
"the",
"next",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L1205-L1274 |
251,251 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibScalar.createCommit | def createCommit(self, varBind, **context):
"""Create Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually create requested Managed
Object Instance. When multiple Managed Objects Instances are created/modified
at once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
if name in self._vars:
cbFun(varBind, **context)
return
# NOTE: multiple names are possible in a single PDU, that could collide
# Therefore let's keep old object indexed by (negative) var-bind index
self._vars[name], instances[self.ST_CREATE][-idx - 1] = instances[self.ST_CREATE][idx], self._vars.get(name)
instances[self.ST_CREATE][idx].writeCommit(varBind, **context) | python | def createCommit(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
if name in self._vars:
cbFun(varBind, **context)
return
# NOTE: multiple names are possible in a single PDU, that could collide
# Therefore let's keep old object indexed by (negative) var-bind index
self._vars[name], instances[self.ST_CREATE][-idx - 1] = instances[self.ST_CREATE][idx], self._vars.get(name)
instances[self.ST_CREATE][idx].writeCommit(varBind, **context) | [
"def",
"createCommit",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: writeCommit(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"instances",
"=",
"context",
"[",
"'instances'",
"]",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"{",
"self",
".",
"ST_CREATE",
":",
"{",
"}",
",",
"self",
".",
"ST_DESTROY",
":",
"{",
"}",
"}",
")",
"idx",
"=",
"context",
"[",
"'idx'",
"]",
"if",
"name",
"in",
"self",
".",
"_vars",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"# NOTE: multiple names are possible in a single PDU, that could collide",
"# Therefore let's keep old object indexed by (negative) var-bind index",
"self",
".",
"_vars",
"[",
"name",
"]",
",",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
"[",
"-",
"idx",
"-",
"1",
"]",
"=",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
"[",
"idx",
"]",
",",
"self",
".",
"_vars",
".",
"get",
"(",
"name",
")",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
"[",
"idx",
"]",
".",
"writeCommit",
"(",
"varBind",
",",
"*",
"*",
"context",
")"
] | Create Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually create requested Managed
Object Instance. When multiple Managed Objects Instances are created/modified
at once (likely coming all in one SNMP PDU), each of them has to run through
the second (*commit*) phase successfully for the system to transition to
the third (*cleanup*) phase. If any single *commit* step fails, the system
transitions into the *undo* state for each of Managed Objects Instances
being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Create",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L1420-L1481 |
251,252 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibScalar.createCleanup | def createCleanup(self, varBind, **context):
"""Finalize Managed Object Instance creation.
Implements the successful third step of the multi-step workflow similar to
the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third (successful) phase is to seal the new Managed Object
Instance. Once the system transitions into the *cleanup* state, no roll back
to the previous Managed Object Instance state is possible.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: createCleanup(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
self.branchVersionId += 1
instances[self.ST_CREATE].pop(-idx - 1, None)
self._vars[name].writeCleanup(varBind, **context) | python | def createCleanup(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: createCleanup(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
self.branchVersionId += 1
instances[self.ST_CREATE].pop(-idx - 1, None)
self._vars[name].writeCleanup(varBind, **context) | [
"def",
"createCleanup",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: createCleanup(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"instances",
"=",
"context",
"[",
"'instances'",
"]",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"{",
"self",
".",
"ST_CREATE",
":",
"{",
"}",
",",
"self",
".",
"ST_DESTROY",
":",
"{",
"}",
"}",
")",
"idx",
"=",
"context",
"[",
"'idx'",
"]",
"self",
".",
"branchVersionId",
"+=",
"1",
"instances",
"[",
"self",
".",
"ST_CREATE",
"]",
".",
"pop",
"(",
"-",
"idx",
"-",
"1",
",",
"None",
")",
"self",
".",
"_vars",
"[",
"name",
"]",
".",
"writeCleanup",
"(",
"varBind",
",",
"*",
"*",
"context",
")"
] | Finalize Managed Object Instance creation.
Implements the successful third step of the multi-step workflow similar to
the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third (successful) phase is to seal the new Managed Object
Instance. Once the system transitions into the *cleanup* state, no roll back
to the previous Managed Object Instance state is possible.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to create
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being created.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Finalize",
"Managed",
"Object",
"Instance",
"creation",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L1483-L1534 |
251,253 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableColumn.destroyCommit | def destroyCommit(self, varBind, **context):
"""Destroy Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually remove requested Managed
Object Instance from the MIB tree. When multiple Managed Objects Instances
are destroyed/modified at once (likely coming all in one SNMP PDU), each
of them has to run through the second (*commit*) phase successfully for
the system to transition to the third (*cleanup*) phase. If any single
*commit* step fails, the system transitions into the *undo* state for
each of Managed Objects Instances being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to destroy
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being destroyed.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: destroyCommit(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
# NOTE: multiple names are possible in a single PDU, that could collide
# Therefore let's keep old object indexed by (negative) var-bind index
try:
instances[self.ST_DESTROY][-idx - 1] = self._vars.pop(name)
except KeyError:
pass
cbFun = context['cbFun']
cbFun(varBind, **context) | python | def destroyCommit(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: destroyCommit(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
idx = context['idx']
# NOTE: multiple names are possible in a single PDU, that could collide
# Therefore let's keep old object indexed by (negative) var-bind index
try:
instances[self.ST_DESTROY][-idx - 1] = self._vars.pop(name)
except KeyError:
pass
cbFun = context['cbFun']
cbFun(varBind, **context) | [
"def",
"destroyCommit",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: destroyCommit(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"instances",
"=",
"context",
"[",
"'instances'",
"]",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"{",
"self",
".",
"ST_CREATE",
":",
"{",
"}",
",",
"self",
".",
"ST_DESTROY",
":",
"{",
"}",
"}",
")",
"idx",
"=",
"context",
"[",
"'idx'",
"]",
"# NOTE: multiple names are possible in a single PDU, that could collide",
"# Therefore let's keep old object indexed by (negative) var-bind index",
"try",
":",
"instances",
"[",
"self",
".",
"ST_DESTROY",
"]",
"[",
"-",
"idx",
"-",
"1",
"]",
"=",
"self",
".",
"_vars",
".",
"pop",
"(",
"name",
")",
"except",
"KeyError",
":",
"pass",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")"
] | Destroy Managed Object Instance.
Implements the second of the multi-step workflow similar to the SNMP SET
command processing (:RFC:`1905#section-4.2.5`).
The goal of the second phase is to actually remove requested Managed
Object Instance from the MIB tree. When multiple Managed Objects Instances
are destroyed/modified at once (likely coming all in one SNMP PDU), each
of them has to run through the second (*commit*) phase successfully for
the system to transition to the third (*cleanup*) phase. If any single
*commit* step fails, the system transitions into the *undo* state for
each of Managed Objects Instances being processed at once.
The role of this object in the MIB tree is non-terminal. It does not
access the actual Managed Object Instance, but just traverses one level
down the MIB tree and hands off the query to the underlying objects.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new Managed Object Instance value to destroy
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
* `instances` (dict): user-supplied dict for temporarily holding
Managed Objects Instances being destroyed.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Destroy",
"Managed",
"Object",
"Instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2267-L2327 |
251,254 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.oidToValue | def oidToValue(self, syntax, identifier, impliedFlag=False, parentIndices=None):
"""Turn SMI table instance identifier into a value object.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes sequence of integers, representing the tail piece
of a tabular object identifier, and turns it into a value object.
Parameters
----------
syntax: :py:class:`Integer`, :py:class:`OctetString`, :py:class:`ObjectIdentifier`, :py:class:`IpAddress` or :py:class:`Bits` -
one of the SNMP data types that can be used in SMI table indices.
identifier: :py:class:`tuple` - tuple of integers representing the tail
piece of an OBJECT IDENTIFIER (i.e. tabular object instance ID)
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is expected to be present as the first integer of
the sequence. Otherwise the length is not included (which is
frequently the case for the last index in the series or a
fixed-length value).
Returns
-------
:py:class:`object` - Initialized instance of `syntax`
"""
if not identifier:
raise error.SmiError('Short OID for index %r' % (syntax,))
if hasattr(syntax, 'cloneFromName'):
return syntax.cloneFromName(
identifier, impliedFlag, parentRow=self, parentIndices=parentIndices)
baseTag = syntax.getTagSet().getBaseTag()
if baseTag == Integer.tagSet.getBaseTag():
return syntax.clone(identifier[0]), identifier[1:]
elif IpAddress.tagSet.isSuperTagSetOf(syntax.getTagSet()):
return syntax.clone(
'.'.join([str(x) for x in identifier[:4]])), identifier[4:]
elif baseTag == OctetString.tagSet.getBaseTag():
# rfc1902, 7.7
if impliedFlag:
return syntax.clone(tuple(identifier)), ()
elif syntax.isFixedLength():
l = syntax.getFixedLength()
return syntax.clone(tuple(identifier[:l])), identifier[l:]
else:
return syntax.clone(
tuple(identifier[1:identifier[0] + 1])), identifier[identifier[0] + 1:]
elif baseTag == ObjectIdentifier.tagSet.getBaseTag():
if impliedFlag:
return syntax.clone(identifier), ()
else:
return syntax.clone(
identifier[1:identifier[0] + 1]), identifier[identifier[0] + 1:]
# rfc2578, 7.1
elif baseTag == Bits.tagSet.getBaseTag():
return syntax.clone(
tuple(identifier[1:identifier[0] + 1])), identifier[identifier[0] + 1:]
else:
raise error.SmiError('Unknown value type for index %r' % (syntax,)) | python | def oidToValue(self, syntax, identifier, impliedFlag=False, parentIndices=None):
if not identifier:
raise error.SmiError('Short OID for index %r' % (syntax,))
if hasattr(syntax, 'cloneFromName'):
return syntax.cloneFromName(
identifier, impliedFlag, parentRow=self, parentIndices=parentIndices)
baseTag = syntax.getTagSet().getBaseTag()
if baseTag == Integer.tagSet.getBaseTag():
return syntax.clone(identifier[0]), identifier[1:]
elif IpAddress.tagSet.isSuperTagSetOf(syntax.getTagSet()):
return syntax.clone(
'.'.join([str(x) for x in identifier[:4]])), identifier[4:]
elif baseTag == OctetString.tagSet.getBaseTag():
# rfc1902, 7.7
if impliedFlag:
return syntax.clone(tuple(identifier)), ()
elif syntax.isFixedLength():
l = syntax.getFixedLength()
return syntax.clone(tuple(identifier[:l])), identifier[l:]
else:
return syntax.clone(
tuple(identifier[1:identifier[0] + 1])), identifier[identifier[0] + 1:]
elif baseTag == ObjectIdentifier.tagSet.getBaseTag():
if impliedFlag:
return syntax.clone(identifier), ()
else:
return syntax.clone(
identifier[1:identifier[0] + 1]), identifier[identifier[0] + 1:]
# rfc2578, 7.1
elif baseTag == Bits.tagSet.getBaseTag():
return syntax.clone(
tuple(identifier[1:identifier[0] + 1])), identifier[identifier[0] + 1:]
else:
raise error.SmiError('Unknown value type for index %r' % (syntax,)) | [
"def",
"oidToValue",
"(",
"self",
",",
"syntax",
",",
"identifier",
",",
"impliedFlag",
"=",
"False",
",",
"parentIndices",
"=",
"None",
")",
":",
"if",
"not",
"identifier",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Short OID for index %r'",
"%",
"(",
"syntax",
",",
")",
")",
"if",
"hasattr",
"(",
"syntax",
",",
"'cloneFromName'",
")",
":",
"return",
"syntax",
".",
"cloneFromName",
"(",
"identifier",
",",
"impliedFlag",
",",
"parentRow",
"=",
"self",
",",
"parentIndices",
"=",
"parentIndices",
")",
"baseTag",
"=",
"syntax",
".",
"getTagSet",
"(",
")",
".",
"getBaseTag",
"(",
")",
"if",
"baseTag",
"==",
"Integer",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"return",
"syntax",
".",
"clone",
"(",
"identifier",
"[",
"0",
"]",
")",
",",
"identifier",
"[",
"1",
":",
"]",
"elif",
"IpAddress",
".",
"tagSet",
".",
"isSuperTagSetOf",
"(",
"syntax",
".",
"getTagSet",
"(",
")",
")",
":",
"return",
"syntax",
".",
"clone",
"(",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"identifier",
"[",
":",
"4",
"]",
"]",
")",
")",
",",
"identifier",
"[",
"4",
":",
"]",
"elif",
"baseTag",
"==",
"OctetString",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"# rfc1902, 7.7",
"if",
"impliedFlag",
":",
"return",
"syntax",
".",
"clone",
"(",
"tuple",
"(",
"identifier",
")",
")",
",",
"(",
")",
"elif",
"syntax",
".",
"isFixedLength",
"(",
")",
":",
"l",
"=",
"syntax",
".",
"getFixedLength",
"(",
")",
"return",
"syntax",
".",
"clone",
"(",
"tuple",
"(",
"identifier",
"[",
":",
"l",
"]",
")",
")",
",",
"identifier",
"[",
"l",
":",
"]",
"else",
":",
"return",
"syntax",
".",
"clone",
"(",
"tuple",
"(",
"identifier",
"[",
"1",
":",
"identifier",
"[",
"0",
"]",
"+",
"1",
"]",
")",
")",
",",
"identifier",
"[",
"identifier",
"[",
"0",
"]",
"+",
"1",
":",
"]",
"elif",
"baseTag",
"==",
"ObjectIdentifier",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"if",
"impliedFlag",
":",
"return",
"syntax",
".",
"clone",
"(",
"identifier",
")",
",",
"(",
")",
"else",
":",
"return",
"syntax",
".",
"clone",
"(",
"identifier",
"[",
"1",
":",
"identifier",
"[",
"0",
"]",
"+",
"1",
"]",
")",
",",
"identifier",
"[",
"identifier",
"[",
"0",
"]",
"+",
"1",
":",
"]",
"# rfc2578, 7.1",
"elif",
"baseTag",
"==",
"Bits",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"return",
"syntax",
".",
"clone",
"(",
"tuple",
"(",
"identifier",
"[",
"1",
":",
"identifier",
"[",
"0",
"]",
"+",
"1",
"]",
")",
")",
",",
"identifier",
"[",
"identifier",
"[",
"0",
"]",
"+",
"1",
":",
"]",
"else",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Unknown value type for index %r'",
"%",
"(",
"syntax",
",",
")",
")"
] | Turn SMI table instance identifier into a value object.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes sequence of integers, representing the tail piece
of a tabular object identifier, and turns it into a value object.
Parameters
----------
syntax: :py:class:`Integer`, :py:class:`OctetString`, :py:class:`ObjectIdentifier`, :py:class:`IpAddress` or :py:class:`Bits` -
one of the SNMP data types that can be used in SMI table indices.
identifier: :py:class:`tuple` - tuple of integers representing the tail
piece of an OBJECT IDENTIFIER (i.e. tabular object instance ID)
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is expected to be present as the first integer of
the sequence. Otherwise the length is not included (which is
frequently the case for the last index in the series or a
fixed-length value).
Returns
-------
:py:class:`object` - Initialized instance of `syntax` | [
"Turn",
"SMI",
"table",
"instance",
"identifier",
"into",
"a",
"value",
"object",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2478-L2548 |
251,255 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.valueToOid | def valueToOid(self, value, impliedFlag=False, parentIndices=None):
"""Turn value object into SMI table instance identifier.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes an arbitrary value object and turns it into a
sequence of integers representing the tail piece of a tabular
object identifier.
Parameters
----------
value: one of the SNMP data types that can be used in SMI table
indices. Allowed types are: :py:class:`Integer`,
:py:class:`OctetString`, :py:class:`ObjectIdentifier`,
:py:class:`IpAddress` and :py:class:`Bits`.
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is included as the first integer of the sequence.
Otherwise the length is not included (which is frequently the
case for the last index in the series or a fixed-length value).
Returns
-------
:py:class:`tuple` - tuple of integers representing the tail piece
of an OBJECT IDENTIFIER (i.e. tabular object instance ID)
"""
if hasattr(value, 'cloneAsName'):
return value.cloneAsName(impliedFlag, parentRow=self, parentIndices=parentIndices)
baseTag = value.getTagSet().getBaseTag()
if baseTag == Integer.tagSet.getBaseTag():
return int(value),
elif IpAddress.tagSet.isSuperTagSetOf(value.getTagSet()):
return value.asNumbers()
elif baseTag == OctetString.tagSet.getBaseTag():
if impliedFlag or value.isFixedLength():
initial = ()
else:
initial = (len(value),)
return initial + value.asNumbers()
elif baseTag == ObjectIdentifier.tagSet.getBaseTag():
if impliedFlag:
return tuple(value)
else:
return (len(value),) + tuple(value)
# rfc2578, 7.1
elif baseTag == Bits.tagSet.getBaseTag():
return (len(value),) + value.asNumbers()
else:
raise error.SmiError('Unknown value type for index %r' % (value,)) | python | def valueToOid(self, value, impliedFlag=False, parentIndices=None):
if hasattr(value, 'cloneAsName'):
return value.cloneAsName(impliedFlag, parentRow=self, parentIndices=parentIndices)
baseTag = value.getTagSet().getBaseTag()
if baseTag == Integer.tagSet.getBaseTag():
return int(value),
elif IpAddress.tagSet.isSuperTagSetOf(value.getTagSet()):
return value.asNumbers()
elif baseTag == OctetString.tagSet.getBaseTag():
if impliedFlag or value.isFixedLength():
initial = ()
else:
initial = (len(value),)
return initial + value.asNumbers()
elif baseTag == ObjectIdentifier.tagSet.getBaseTag():
if impliedFlag:
return tuple(value)
else:
return (len(value),) + tuple(value)
# rfc2578, 7.1
elif baseTag == Bits.tagSet.getBaseTag():
return (len(value),) + value.asNumbers()
else:
raise error.SmiError('Unknown value type for index %r' % (value,)) | [
"def",
"valueToOid",
"(",
"self",
",",
"value",
",",
"impliedFlag",
"=",
"False",
",",
"parentIndices",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'cloneAsName'",
")",
":",
"return",
"value",
".",
"cloneAsName",
"(",
"impliedFlag",
",",
"parentRow",
"=",
"self",
",",
"parentIndices",
"=",
"parentIndices",
")",
"baseTag",
"=",
"value",
".",
"getTagSet",
"(",
")",
".",
"getBaseTag",
"(",
")",
"if",
"baseTag",
"==",
"Integer",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"return",
"int",
"(",
"value",
")",
",",
"elif",
"IpAddress",
".",
"tagSet",
".",
"isSuperTagSetOf",
"(",
"value",
".",
"getTagSet",
"(",
")",
")",
":",
"return",
"value",
".",
"asNumbers",
"(",
")",
"elif",
"baseTag",
"==",
"OctetString",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"if",
"impliedFlag",
"or",
"value",
".",
"isFixedLength",
"(",
")",
":",
"initial",
"=",
"(",
")",
"else",
":",
"initial",
"=",
"(",
"len",
"(",
"value",
")",
",",
")",
"return",
"initial",
"+",
"value",
".",
"asNumbers",
"(",
")",
"elif",
"baseTag",
"==",
"ObjectIdentifier",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"if",
"impliedFlag",
":",
"return",
"tuple",
"(",
"value",
")",
"else",
":",
"return",
"(",
"len",
"(",
"value",
")",
",",
")",
"+",
"tuple",
"(",
"value",
")",
"# rfc2578, 7.1",
"elif",
"baseTag",
"==",
"Bits",
".",
"tagSet",
".",
"getBaseTag",
"(",
")",
":",
"return",
"(",
"len",
"(",
"value",
")",
",",
")",
"+",
"value",
".",
"asNumbers",
"(",
")",
"else",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Unknown value type for index %r'",
"%",
"(",
"value",
",",
")",
")"
] | Turn value object into SMI table instance identifier.
SNMP SMI table objects are identified by OIDs composed of columnar
object ID and instance index. The index part can be composed
from the values of one or more tabular objects.
This method takes an arbitrary value object and turns it into a
sequence of integers representing the tail piece of a tabular
object identifier.
Parameters
----------
value: one of the SNMP data types that can be used in SMI table
indices. Allowed types are: :py:class:`Integer`,
:py:class:`OctetString`, :py:class:`ObjectIdentifier`,
:py:class:`IpAddress` and :py:class:`Bits`.
impliedFlag: :py:class:`bool` - if `False`, the length of the
serialized value is included as the first integer of the sequence.
Otherwise the length is not included (which is frequently the
case for the last index in the series or a fixed-length value).
Returns
-------
:py:class:`tuple` - tuple of integers representing the tail piece
of an OBJECT IDENTIFIER (i.e. tabular object instance ID) | [
"Turn",
"value",
"object",
"into",
"SMI",
"table",
"instance",
"identifier",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2552-L2608 |
251,256 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.announceManagementEvent | def announceManagementEvent(self, action, varBind, **context):
"""Announce mass operation on parent table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on parent :py:class:`MibTableRow` whenever
row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
being applied on the parent table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all the consumers of this notifications finished with their stuff
or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
name, val = varBind
cbFun = context['cbFun']
if not self._augmentingRows:
cbFun(varBind, **context)
return
# Convert OID suffix into index values
instId = name[len(self.name) + 1:]
baseIndices = []
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax, instId = self.oidToValue(mibObj.syntax, instId,
impliedFlag, indices)
if self.name == mibObj.name[:-1]:
baseIndices.append((mibObj.name, syntax))
indices.append(syntax)
if instId:
exc = error.SmiError('Excessive instance identifier sub-OIDs left at %s: %s' % (self, instId))
cbFun(varBind, **dict(context, error=exc))
return
if not baseIndices:
cbFun(varBind, **context)
return
count = [len(self._augmentingRows)]
def _cbFun(varBind, **context):
count[0] -= 1
if not count[0]:
cbFun(varBind, **context)
for modName, mibSym in self._augmentingRows:
mibObj, = mibBuilder.importSymbols(modName, mibSym)
mibObj.receiveManagementEvent(action, (baseIndices, val), **dict(context, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger('announceManagementEvent %s to %s' % (action, mibObj)) | python | def announceManagementEvent(self, action, varBind, **context):
name, val = varBind
cbFun = context['cbFun']
if not self._augmentingRows:
cbFun(varBind, **context)
return
# Convert OID suffix into index values
instId = name[len(self.name) + 1:]
baseIndices = []
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax, instId = self.oidToValue(mibObj.syntax, instId,
impliedFlag, indices)
if self.name == mibObj.name[:-1]:
baseIndices.append((mibObj.name, syntax))
indices.append(syntax)
if instId:
exc = error.SmiError('Excessive instance identifier sub-OIDs left at %s: %s' % (self, instId))
cbFun(varBind, **dict(context, error=exc))
return
if not baseIndices:
cbFun(varBind, **context)
return
count = [len(self._augmentingRows)]
def _cbFun(varBind, **context):
count[0] -= 1
if not count[0]:
cbFun(varBind, **context)
for modName, mibSym in self._augmentingRows:
mibObj, = mibBuilder.importSymbols(modName, mibSym)
mibObj.receiveManagementEvent(action, (baseIndices, val), **dict(context, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger('announceManagementEvent %s to %s' % (action, mibObj)) | [
"def",
"announceManagementEvent",
"(",
"self",
",",
"action",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"if",
"not",
"self",
".",
"_augmentingRows",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"# Convert OID suffix into index values",
"instId",
"=",
"name",
"[",
"len",
"(",
"self",
".",
"name",
")",
"+",
"1",
":",
"]",
"baseIndices",
"=",
"[",
"]",
"indices",
"=",
"[",
"]",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"syntax",
",",
"instId",
"=",
"self",
".",
"oidToValue",
"(",
"mibObj",
".",
"syntax",
",",
"instId",
",",
"impliedFlag",
",",
"indices",
")",
"if",
"self",
".",
"name",
"==",
"mibObj",
".",
"name",
"[",
":",
"-",
"1",
"]",
":",
"baseIndices",
".",
"append",
"(",
"(",
"mibObj",
".",
"name",
",",
"syntax",
")",
")",
"indices",
".",
"append",
"(",
"syntax",
")",
"if",
"instId",
":",
"exc",
"=",
"error",
".",
"SmiError",
"(",
"'Excessive instance identifier sub-OIDs left at %s: %s'",
"%",
"(",
"self",
",",
"instId",
")",
")",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"error",
"=",
"exc",
")",
")",
"return",
"if",
"not",
"baseIndices",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"count",
"=",
"[",
"len",
"(",
"self",
".",
"_augmentingRows",
")",
"]",
"def",
"_cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"count",
"[",
"0",
"]",
"-=",
"1",
"if",
"not",
"count",
"[",
"0",
"]",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"for",
"modName",
",",
"mibSym",
"in",
"self",
".",
"_augmentingRows",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"mibSym",
")",
"mibObj",
".",
"receiveManagementEvent",
"(",
"action",
",",
"(",
"baseIndices",
",",
"val",
")",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"cbFun",
"=",
"_cbFun",
")",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'announceManagementEvent %s to %s'",
"%",
"(",
"action",
",",
"mibObj",
")",
")"
] | Announce mass operation on parent table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on parent :py:class:`MibTableRow` whenever
row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
being applied on the parent table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all the consumers of this notifications finished with their stuff
or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Announce",
"mass",
"operation",
"on",
"parent",
"table",
"s",
"row",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2612-L2693 |
251,257 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.receiveManagementEvent | def receiveManagementEvent(self, action, varBind, **context):
"""Apply mass operation on extending table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on the extending :py:class:`MibTableRow`
object whenever row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on extending table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
the requested operation has been applied on all columns of the
extending table or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
baseIndices, val = varBind
# The default implementation supports one-to-one rows dependency
instId = ()
# Resolve indices intersection
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
parentIndices = []
for name, syntax in baseIndices:
if name == mibObj.name:
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
if instId:
debug.logger & debug.FLAG_INS and debug.logger(
'receiveManagementEvent %s for suffix %s' % (action, instId))
self._manageColumns(action, (self.name + (0,) + instId, val), **context) | python | def receiveManagementEvent(self, action, varBind, **context):
baseIndices, val = varBind
# The default implementation supports one-to-one rows dependency
instId = ()
# Resolve indices intersection
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
parentIndices = []
for name, syntax in baseIndices:
if name == mibObj.name:
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
if instId:
debug.logger & debug.FLAG_INS and debug.logger(
'receiveManagementEvent %s for suffix %s' % (action, instId))
self._manageColumns(action, (self.name + (0,) + instId, val), **context) | [
"def",
"receiveManagementEvent",
"(",
"self",
",",
"action",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"baseIndices",
",",
"val",
"=",
"varBind",
"# The default implementation supports one-to-one rows dependency",
"instId",
"=",
"(",
")",
"# Resolve indices intersection",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"parentIndices",
"=",
"[",
"]",
"for",
"name",
",",
"syntax",
"in",
"baseIndices",
":",
"if",
"name",
"==",
"mibObj",
".",
"name",
":",
"instId",
"+=",
"self",
".",
"valueToOid",
"(",
"syntax",
",",
"impliedFlag",
",",
"parentIndices",
")",
"parentIndices",
".",
"append",
"(",
"syntax",
")",
"if",
"instId",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'receiveManagementEvent %s for suffix %s'",
"%",
"(",
"action",
",",
"instId",
")",
")",
"self",
".",
"_manageColumns",
"(",
"action",
",",
"(",
"self",
".",
"name",
"+",
"(",
"0",
",",
")",
"+",
"instId",
",",
"val",
")",
",",
"*",
"*",
"context",
")"
] | Apply mass operation on extending table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on the extending :py:class:`MibTableRow`
object whenever row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on extending table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
the requested operation has been applied on all columns of the
extending table or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object. | [
"Apply",
"mass",
"operation",
"on",
"extending",
"table",
"s",
"row",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2695-L2751 |
251,258 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.registerAugmentation | def registerAugmentation(self, *names):
"""Register table extension.
SNMP SMI provides a way to extend already existing SMI table with
another table. This method registers dependent (extending) table
(or type :py:class:`MibTableRow`) to already existing table.
Whenever a row of the parent table is created or destroyed, the
same mass columnar operation is applied on the extending table
row.
Parameters
----------
names: :py:class:`tuple`
One or more `tuple`'s of `str` referring to the extending table by
MIB module name (first `str`) and `:py:class:`MibTableRow` object
name (second `str`).
"""
for name in names:
if name in self._augmentingRows:
raise error.SmiError(
'Row %s already augmented by %s::%s' % (self.name, name[0], name[1])
)
self._augmentingRows.add(name)
return self | python | def registerAugmentation(self, *names):
for name in names:
if name in self._augmentingRows:
raise error.SmiError(
'Row %s already augmented by %s::%s' % (self.name, name[0], name[1])
)
self._augmentingRows.add(name)
return self | [
"def",
"registerAugmentation",
"(",
"self",
",",
"*",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"in",
"self",
".",
"_augmentingRows",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Row %s already augmented by %s::%s'",
"%",
"(",
"self",
".",
"name",
",",
"name",
"[",
"0",
"]",
",",
"name",
"[",
"1",
"]",
")",
")",
"self",
".",
"_augmentingRows",
".",
"add",
"(",
"name",
")",
"return",
"self"
] | Register table extension.
SNMP SMI provides a way to extend already existing SMI table with
another table. This method registers dependent (extending) table
(or type :py:class:`MibTableRow`) to already existing table.
Whenever a row of the parent table is created or destroyed, the
same mass columnar operation is applied on the extending table
row.
Parameters
----------
names: :py:class:`tuple`
One or more `tuple`'s of `str` referring to the extending table by
MIB module name (first `str`) and `:py:class:`MibTableRow` object
name (second `str`). | [
"Register",
"table",
"extension",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2753-L2779 |
251,259 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow._manageColumns | def _manageColumns(self, action, varBind, **context):
"""Apply a management action on all columns
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on all columns but the one passed in `varBind`
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all columns have been processed or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assumes that row consistency check has been triggered by RowStatus
columnar object transition into `active` state.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: _manageColumns(%s, %s, %r)' % (self, action, name, val)))
cbFun = context['cbFun']
colLen = len(self.name) + 1
# Build a map of index names and values for automatic initialization
indexVals = {}
instId = name[colLen:]
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
indexVals[mibObj.name] = syntax
indices.append(syntax)
count = [len(self._vars)]
if name[:colLen] in self._vars:
count[0] -= 1
def _cbFun(varBind, **context):
count[0] -= 1
if not count[0]:
cbFun(varBind, **context)
for colName, colObj in self._vars.items():
acFun = context.get('acFun')
if colName in indexVals:
colInstanceValue = indexVals[colName]
# Index column is usually read-only
acFun = None
elif name[:colLen] == colName:
# status column is following `write` path
continue
else:
colInstanceValue = None
actionFun = getattr(colObj, action)
colInstanceName = colName + name[colLen:]
actionFun((colInstanceName, colInstanceValue),
**dict(context, acFun=acFun, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger(
'_manageColumns: action %s name %s instance %s %svalue %r' % (
action, name, instId, name in indexVals and "index " or "", indexVals.get(name, val))) | python | def _manageColumns(self, action, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: _manageColumns(%s, %s, %r)' % (self, action, name, val)))
cbFun = context['cbFun']
colLen = len(self.name) + 1
# Build a map of index names and values for automatic initialization
indexVals = {}
instId = name[colLen:]
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
indexVals[mibObj.name] = syntax
indices.append(syntax)
count = [len(self._vars)]
if name[:colLen] in self._vars:
count[0] -= 1
def _cbFun(varBind, **context):
count[0] -= 1
if not count[0]:
cbFun(varBind, **context)
for colName, colObj in self._vars.items():
acFun = context.get('acFun')
if colName in indexVals:
colInstanceValue = indexVals[colName]
# Index column is usually read-only
acFun = None
elif name[:colLen] == colName:
# status column is following `write` path
continue
else:
colInstanceValue = None
actionFun = getattr(colObj, action)
colInstanceName = colName + name[colLen:]
actionFun((colInstanceName, colInstanceValue),
**dict(context, acFun=acFun, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger(
'_manageColumns: action %s name %s instance %s %svalue %r' % (
action, name, instId, name in indexVals and "index " or "", indexVals.get(name, val))) | [
"def",
"_manageColumns",
"(",
"self",
",",
"action",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: _manageColumns(%s, %s, %r)'",
"%",
"(",
"self",
",",
"action",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"colLen",
"=",
"len",
"(",
"self",
".",
"name",
")",
"+",
"1",
"# Build a map of index names and values for automatic initialization",
"indexVals",
"=",
"{",
"}",
"instId",
"=",
"name",
"[",
"colLen",
":",
"]",
"indices",
"=",
"[",
"]",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"syntax",
",",
"instId",
"=",
"self",
".",
"oidToValue",
"(",
"mibObj",
".",
"syntax",
",",
"instId",
",",
"impliedFlag",
",",
"indices",
")",
"indexVals",
"[",
"mibObj",
".",
"name",
"]",
"=",
"syntax",
"indices",
".",
"append",
"(",
"syntax",
")",
"count",
"=",
"[",
"len",
"(",
"self",
".",
"_vars",
")",
"]",
"if",
"name",
"[",
":",
"colLen",
"]",
"in",
"self",
".",
"_vars",
":",
"count",
"[",
"0",
"]",
"-=",
"1",
"def",
"_cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"count",
"[",
"0",
"]",
"-=",
"1",
"if",
"not",
"count",
"[",
"0",
"]",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"for",
"colName",
",",
"colObj",
"in",
"self",
".",
"_vars",
".",
"items",
"(",
")",
":",
"acFun",
"=",
"context",
".",
"get",
"(",
"'acFun'",
")",
"if",
"colName",
"in",
"indexVals",
":",
"colInstanceValue",
"=",
"indexVals",
"[",
"colName",
"]",
"# Index column is usually read-only",
"acFun",
"=",
"None",
"elif",
"name",
"[",
":",
"colLen",
"]",
"==",
"colName",
":",
"# status column is following `write` path",
"continue",
"else",
":",
"colInstanceValue",
"=",
"None",
"actionFun",
"=",
"getattr",
"(",
"colObj",
",",
"action",
")",
"colInstanceName",
"=",
"colName",
"+",
"name",
"[",
"colLen",
":",
"]",
"actionFun",
"(",
"(",
"colInstanceName",
",",
"colInstanceValue",
")",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"acFun",
"=",
"acFun",
",",
"cbFun",
"=",
"_cbFun",
")",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'_manageColumns: action %s name %s instance %s %svalue %r'",
"%",
"(",
"action",
",",
"name",
",",
"instId",
",",
"name",
"in",
"indexVals",
"and",
"\"index \"",
"or",
"\"\"",
",",
"indexVals",
".",
"get",
"(",
"name",
",",
"val",
")",
")",
")"
] | Apply a management action on all columns
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on all columns but the one passed in `varBind`
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
all columns have been processed or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assumes that row consistency check has been triggered by RowStatus
columnar object transition into `active` state. | [
"Apply",
"a",
"management",
"action",
"on",
"all",
"columns"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2791-L2879 |
251,260 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow._checkColumns | def _checkColumns(self, varBind, **context):
"""Check the consistency of all columns.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assume that row consistency check has been triggered by RowStatus
columnar object transition into `active` state.
"""
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: _checkColumns(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
# RowStatus != active
if val != 1:
cbFun(varBind, **context)
return
count = [len(self._vars)]
def _cbFun(varBind, **context):
count[0] -= 1
name, val = varBind
if count[0] >= 0:
exc = context.get('error')
if exc or not val.hasValue():
count[0] = -1 # ignore the rest of callbacks
exc = error.InconsistentValueError(msg='Inconsistent column %s: %s' % (name, exc))
cbFun(varBind, **dict(context, error=exc))
return
if not count[0]:
cbFun(varBind, **context)
return
colLen = len(self.name) + 1
for colName, colObj in self._vars.items():
instName = colName + name[colLen:]
colObj.readGet((instName, None), **dict(context, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger(
'%s: _checkColumns: checking instance %s' % (self, instName)) | python | def _checkColumns(self, varBind, **context):
name, val = varBind
(debug.logger & debug.FLAG_INS and
debug.logger('%s: _checkColumns(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
# RowStatus != active
if val != 1:
cbFun(varBind, **context)
return
count = [len(self._vars)]
def _cbFun(varBind, **context):
count[0] -= 1
name, val = varBind
if count[0] >= 0:
exc = context.get('error')
if exc or not val.hasValue():
count[0] = -1 # ignore the rest of callbacks
exc = error.InconsistentValueError(msg='Inconsistent column %s: %s' % (name, exc))
cbFun(varBind, **dict(context, error=exc))
return
if not count[0]:
cbFun(varBind, **context)
return
colLen = len(self.name) + 1
for colName, colObj in self._vars.items():
instName = colName + name[colLen:]
colObj.readGet((instName, None), **dict(context, cbFun=_cbFun))
debug.logger & debug.FLAG_INS and debug.logger(
'%s: _checkColumns: checking instance %s' % (self, instName)) | [
"def",
"_checkColumns",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: _checkColumns(%s, %r)'",
"%",
"(",
"self",
",",
"name",
",",
"val",
")",
")",
")",
"cbFun",
"=",
"context",
"[",
"'cbFun'",
"]",
"# RowStatus != active",
"if",
"val",
"!=",
"1",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"count",
"=",
"[",
"len",
"(",
"self",
".",
"_vars",
")",
"]",
"def",
"_cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"count",
"[",
"0",
"]",
"-=",
"1",
"name",
",",
"val",
"=",
"varBind",
"if",
"count",
"[",
"0",
"]",
">=",
"0",
":",
"exc",
"=",
"context",
".",
"get",
"(",
"'error'",
")",
"if",
"exc",
"or",
"not",
"val",
".",
"hasValue",
"(",
")",
":",
"count",
"[",
"0",
"]",
"=",
"-",
"1",
"# ignore the rest of callbacks",
"exc",
"=",
"error",
".",
"InconsistentValueError",
"(",
"msg",
"=",
"'Inconsistent column %s: %s'",
"%",
"(",
"name",
",",
"exc",
")",
")",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"error",
"=",
"exc",
")",
")",
"return",
"if",
"not",
"count",
"[",
"0",
"]",
":",
"cbFun",
"(",
"varBind",
",",
"*",
"*",
"context",
")",
"return",
"colLen",
"=",
"len",
"(",
"self",
".",
"name",
")",
"+",
"1",
"for",
"colName",
",",
"colObj",
"in",
"self",
".",
"_vars",
".",
"items",
"(",
")",
":",
"instName",
"=",
"colName",
"+",
"name",
"[",
"colLen",
":",
"]",
"colObj",
".",
"readGet",
"(",
"(",
"instName",
",",
"None",
")",
",",
"*",
"*",
"dict",
"(",
"context",
",",
"cbFun",
"=",
"_cbFun",
")",
")",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: _checkColumns: checking instance %s'",
"%",
"(",
"self",
",",
"instName",
")",
")"
] | Check the consistency of all columns.
Parameters
----------
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
Notes
-----
The callback functions (e.g. `cbFun`) have the same signature as this
method where `varBind` contains the new Managed Object Instance value.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
Assume that row consistency check has been triggered by RowStatus
columnar object transition into `active` state. | [
"Check",
"the",
"consistency",
"of",
"all",
"columns",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2881-L2949 |
251,261 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.getIndicesFromInstId | def getIndicesFromInstId(self, instId):
"""Return index values for instance identification"""
if instId in self._idToIdxCache:
return self._idToIdxCache[instId]
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
try:
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
except PyAsn1Error as exc:
debug.logger & debug.FLAG_INS and debug.logger(
'error resolving table indices at %s, %s: %s' % (self.__class__.__name__, instId, exc))
indices = [instId]
instId = ()
break
indices.append(syntax) # to avoid cyclic refs
if instId:
raise error.SmiError(
'Excessive instance identifier sub-OIDs left at %s: %s' %
(self, instId)
)
indices = tuple(indices)
self._idToIdxCache[instId] = indices
return indices | python | def getIndicesFromInstId(self, instId):
if instId in self._idToIdxCache:
return self._idToIdxCache[instId]
indices = []
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
try:
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
except PyAsn1Error as exc:
debug.logger & debug.FLAG_INS and debug.logger(
'error resolving table indices at %s, %s: %s' % (self.__class__.__name__, instId, exc))
indices = [instId]
instId = ()
break
indices.append(syntax) # to avoid cyclic refs
if instId:
raise error.SmiError(
'Excessive instance identifier sub-OIDs left at %s: %s' %
(self, instId)
)
indices = tuple(indices)
self._idToIdxCache[instId] = indices
return indices | [
"def",
"getIndicesFromInstId",
"(",
"self",
",",
"instId",
")",
":",
"if",
"instId",
"in",
"self",
".",
"_idToIdxCache",
":",
"return",
"self",
".",
"_idToIdxCache",
"[",
"instId",
"]",
"indices",
"=",
"[",
"]",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"try",
":",
"syntax",
",",
"instId",
"=",
"self",
".",
"oidToValue",
"(",
"mibObj",
".",
"syntax",
",",
"instId",
",",
"impliedFlag",
",",
"indices",
")",
"except",
"PyAsn1Error",
"as",
"exc",
":",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'error resolving table indices at %s, %s: %s'",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"instId",
",",
"exc",
")",
")",
"indices",
"=",
"[",
"instId",
"]",
"instId",
"=",
"(",
")",
"break",
"indices",
".",
"append",
"(",
"syntax",
")",
"# to avoid cyclic refs",
"if",
"instId",
":",
"raise",
"error",
".",
"SmiError",
"(",
"'Excessive instance identifier sub-OIDs left at %s: %s'",
"%",
"(",
"self",
",",
"instId",
")",
")",
"indices",
"=",
"tuple",
"(",
"indices",
")",
"self",
".",
"_idToIdxCache",
"[",
"instId",
"]",
"=",
"indices",
"return",
"indices"
] | Return index values for instance identification | [
"Return",
"index",
"values",
"for",
"instance",
"identification"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3278-L3306 |
251,262 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.getInstIdFromIndices | def getInstIdFromIndices(self, *indices):
"""Return column instance identification from indices"""
try:
return self._idxToIdCache[indices]
except TypeError:
cacheable = False
except KeyError:
cacheable = True
idx = 0
instId = ()
parentIndices = []
for impliedFlag, modName, symName in self._indexNames:
if idx >= len(indices):
break
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax = mibObj.syntax.clone(indices[idx])
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
idx += 1
if cacheable:
self._idxToIdCache[indices] = instId
return instId | python | def getInstIdFromIndices(self, *indices):
try:
return self._idxToIdCache[indices]
except TypeError:
cacheable = False
except KeyError:
cacheable = True
idx = 0
instId = ()
parentIndices = []
for impliedFlag, modName, symName in self._indexNames:
if idx >= len(indices):
break
mibObj, = mibBuilder.importSymbols(modName, symName)
syntax = mibObj.syntax.clone(indices[idx])
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
idx += 1
if cacheable:
self._idxToIdCache[indices] = instId
return instId | [
"def",
"getInstIdFromIndices",
"(",
"self",
",",
"*",
"indices",
")",
":",
"try",
":",
"return",
"self",
".",
"_idxToIdCache",
"[",
"indices",
"]",
"except",
"TypeError",
":",
"cacheable",
"=",
"False",
"except",
"KeyError",
":",
"cacheable",
"=",
"True",
"idx",
"=",
"0",
"instId",
"=",
"(",
")",
"parentIndices",
"=",
"[",
"]",
"for",
"impliedFlag",
",",
"modName",
",",
"symName",
"in",
"self",
".",
"_indexNames",
":",
"if",
"idx",
">=",
"len",
"(",
"indices",
")",
":",
"break",
"mibObj",
",",
"=",
"mibBuilder",
".",
"importSymbols",
"(",
"modName",
",",
"symName",
")",
"syntax",
"=",
"mibObj",
".",
"syntax",
".",
"clone",
"(",
"indices",
"[",
"idx",
"]",
")",
"instId",
"+=",
"self",
".",
"valueToOid",
"(",
"syntax",
",",
"impliedFlag",
",",
"parentIndices",
")",
"parentIndices",
".",
"append",
"(",
"syntax",
")",
"idx",
"+=",
"1",
"if",
"cacheable",
":",
"self",
".",
"_idxToIdCache",
"[",
"indices",
"]",
"=",
"instId",
"return",
"instId"
] | Return column instance identification from indices | [
"Return",
"column",
"instance",
"identification",
"from",
"indices"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3308-L3329 |
251,263 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.getInstNameByIndex | def getInstNameByIndex(self, colId, *indices):
"""Build column instance name from components"""
return self.name + (colId,) + self.getInstIdFromIndices(*indices) | python | def getInstNameByIndex(self, colId, *indices):
return self.name + (colId,) + self.getInstIdFromIndices(*indices) | [
"def",
"getInstNameByIndex",
"(",
"self",
",",
"colId",
",",
"*",
"indices",
")",
":",
"return",
"self",
".",
"name",
"+",
"(",
"colId",
",",
")",
"+",
"self",
".",
"getInstIdFromIndices",
"(",
"*",
"indices",
")"
] | Build column instance name from components | [
"Build",
"column",
"instance",
"name",
"from",
"components"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3333-L3335 |
251,264 | etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | MibTableRow.getInstNamesByIndex | def getInstNamesByIndex(self, *indices):
"""Build column instance names from indices"""
instNames = []
for columnName in self._vars.keys():
instNames.append(
self.getInstNameByIndex(*(columnName[-1],) + indices)
)
return tuple(instNames) | python | def getInstNamesByIndex(self, *indices):
instNames = []
for columnName in self._vars.keys():
instNames.append(
self.getInstNameByIndex(*(columnName[-1],) + indices)
)
return tuple(instNames) | [
"def",
"getInstNamesByIndex",
"(",
"self",
",",
"*",
"indices",
")",
":",
"instNames",
"=",
"[",
"]",
"for",
"columnName",
"in",
"self",
".",
"_vars",
".",
"keys",
"(",
")",
":",
"instNames",
".",
"append",
"(",
"self",
".",
"getInstNameByIndex",
"(",
"*",
"(",
"columnName",
"[",
"-",
"1",
"]",
",",
")",
"+",
"indices",
")",
")",
"return",
"tuple",
"(",
"instNames",
")"
] | Build column instance names from indices | [
"Build",
"column",
"instance",
"names",
"from",
"indices"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L3337-L3345 |
251,265 | etingof/pysnmp | pysnmp/hlapi/v3arch/asyncore/sync/cmdgen.py | nextCmd | def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Creates a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication : str
True value indicates SNMP engine error.
errorStatus : str
True value indicates SNMP PDU error.
errorIndex : int
Non-zero value refers to `varBinds[errorIndex-1]`
varBinds : tuple
A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi import *
>>> g = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))])
>>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] )
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))])
"""
# noinspection PyShadowingNames
def cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
cbCtx['errorIndication'] = errorIndication
cbCtx['errorStatus'] = errorStatus
cbCtx['errorIndex'] = errorIndex
cbCtx['varBindTable'] = varBindTable
lexicographicMode = options.get('lexicographicMode', True)
ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False)
maxRows = options.get('maxRows', 0)
maxCalls = options.get('maxCalls', 0)
cbCtx = {}
vbProcessor = CommandGeneratorVarBinds()
initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine.cache, varBinds)]
totalRows = totalCalls = 0
while True:
previousVarBinds = varBinds
if varBinds:
cmdgen.nextCmd(snmpEngine, authData, transportTarget, contextData,
*[(x[0], Null('')) for x in varBinds],
cbFun=cbFun, cbCtx=cbCtx,
lookupMib=options.get('lookupMib', True))
snmpEngine.transportDispatcher.runDispatcher()
errorIndication = cbCtx['errorIndication']
errorStatus = cbCtx['errorStatus']
errorIndex = cbCtx['errorIndex']
if ignoreNonIncreasingOid and errorIndication and isinstance(errorIndication, errind.OidNotIncreasing):
errorIndication = None
if errorIndication:
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
else:
stopFlag = True
varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0]
for col, varBind in enumerate(varBinds):
name, val = varBind
if isinstance(val, Null):
varBinds[col] = previousVarBinds[col][0], endOfMibView
if not lexicographicMode and not initialVars[col].isPrefixOf(name):
varBinds[col] = previousVarBinds[col][0], endOfMibView
if stopFlag and varBinds[col][1] is not endOfMibView:
stopFlag = False
if stopFlag:
return
totalRows += 1
totalCalls += 1
else:
errorIndication = errorStatus = errorIndex = None
varBinds = []
initialVarBinds = (yield errorIndication, errorStatus, errorIndex, varBinds)
if initialVarBinds:
varBinds = initialVarBinds
initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine.cache, varBinds)]
if maxRows and totalRows >= maxRows:
return
if maxCalls and totalCalls >= maxCalls:
return | python | def nextCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
# noinspection PyShadowingNames
def cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
cbCtx['errorIndication'] = errorIndication
cbCtx['errorStatus'] = errorStatus
cbCtx['errorIndex'] = errorIndex
cbCtx['varBindTable'] = varBindTable
lexicographicMode = options.get('lexicographicMode', True)
ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False)
maxRows = options.get('maxRows', 0)
maxCalls = options.get('maxCalls', 0)
cbCtx = {}
vbProcessor = CommandGeneratorVarBinds()
initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine.cache, varBinds)]
totalRows = totalCalls = 0
while True:
previousVarBinds = varBinds
if varBinds:
cmdgen.nextCmd(snmpEngine, authData, transportTarget, contextData,
*[(x[0], Null('')) for x in varBinds],
cbFun=cbFun, cbCtx=cbCtx,
lookupMib=options.get('lookupMib', True))
snmpEngine.transportDispatcher.runDispatcher()
errorIndication = cbCtx['errorIndication']
errorStatus = cbCtx['errorStatus']
errorIndex = cbCtx['errorIndex']
if ignoreNonIncreasingOid and errorIndication and isinstance(errorIndication, errind.OidNotIncreasing):
errorIndication = None
if errorIndication:
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
else:
stopFlag = True
varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0]
for col, varBind in enumerate(varBinds):
name, val = varBind
if isinstance(val, Null):
varBinds[col] = previousVarBinds[col][0], endOfMibView
if not lexicographicMode and not initialVars[col].isPrefixOf(name):
varBinds[col] = previousVarBinds[col][0], endOfMibView
if stopFlag and varBinds[col][1] is not endOfMibView:
stopFlag = False
if stopFlag:
return
totalRows += 1
totalCalls += 1
else:
errorIndication = errorStatus = errorIndex = None
varBinds = []
initialVarBinds = (yield errorIndication, errorStatus, errorIndex, varBinds)
if initialVarBinds:
varBinds = initialVarBinds
initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine.cache, varBinds)]
if maxRows and totalRows >= maxRows:
return
if maxCalls and totalCalls >= maxCalls:
return | [
"def",
"nextCmd",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"# noinspection PyShadowingNames",
"def",
"cbFun",
"(",
"snmpEngine",
",",
"sendRequestHandle",
",",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
",",
"cbCtx",
")",
":",
"cbCtx",
"[",
"'errorIndication'",
"]",
"=",
"errorIndication",
"cbCtx",
"[",
"'errorStatus'",
"]",
"=",
"errorStatus",
"cbCtx",
"[",
"'errorIndex'",
"]",
"=",
"errorIndex",
"cbCtx",
"[",
"'varBindTable'",
"]",
"=",
"varBindTable",
"lexicographicMode",
"=",
"options",
".",
"get",
"(",
"'lexicographicMode'",
",",
"True",
")",
"ignoreNonIncreasingOid",
"=",
"options",
".",
"get",
"(",
"'ignoreNonIncreasingOid'",
",",
"False",
")",
"maxRows",
"=",
"options",
".",
"get",
"(",
"'maxRows'",
",",
"0",
")",
"maxCalls",
"=",
"options",
".",
"get",
"(",
"'maxCalls'",
",",
"0",
")",
"cbCtx",
"=",
"{",
"}",
"vbProcessor",
"=",
"CommandGeneratorVarBinds",
"(",
")",
"initialVars",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"vbProcessor",
".",
"makeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
")",
"]",
"totalRows",
"=",
"totalCalls",
"=",
"0",
"while",
"True",
":",
"previousVarBinds",
"=",
"varBinds",
"if",
"varBinds",
":",
"cmdgen",
".",
"nextCmd",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"*",
"[",
"(",
"x",
"[",
"0",
"]",
",",
"Null",
"(",
"''",
")",
")",
"for",
"x",
"in",
"varBinds",
"]",
",",
"cbFun",
"=",
"cbFun",
",",
"cbCtx",
"=",
"cbCtx",
",",
"lookupMib",
"=",
"options",
".",
"get",
"(",
"'lookupMib'",
",",
"True",
")",
")",
"snmpEngine",
".",
"transportDispatcher",
".",
"runDispatcher",
"(",
")",
"errorIndication",
"=",
"cbCtx",
"[",
"'errorIndication'",
"]",
"errorStatus",
"=",
"cbCtx",
"[",
"'errorStatus'",
"]",
"errorIndex",
"=",
"cbCtx",
"[",
"'errorIndex'",
"]",
"if",
"ignoreNonIncreasingOid",
"and",
"errorIndication",
"and",
"isinstance",
"(",
"errorIndication",
",",
"errind",
".",
"OidNotIncreasing",
")",
":",
"errorIndication",
"=",
"None",
"if",
"errorIndication",
":",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
")",
"return",
"elif",
"errorStatus",
":",
"if",
"errorStatus",
"==",
"2",
":",
"# Hide SNMPv1 noSuchName error which leaks in here",
"# from SNMPv1 Agent through internal pysnmp proxy.",
"errorStatus",
"=",
"errorStatus",
".",
"clone",
"(",
"0",
")",
"errorIndex",
"=",
"errorIndex",
".",
"clone",
"(",
"0",
")",
"yield",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
")",
"return",
"else",
":",
"stopFlag",
"=",
"True",
"varBinds",
"=",
"cbCtx",
"[",
"'varBindTable'",
"]",
"and",
"cbCtx",
"[",
"'varBindTable'",
"]",
"[",
"0",
"]",
"for",
"col",
",",
"varBind",
"in",
"enumerate",
"(",
"varBinds",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"if",
"isinstance",
"(",
"val",
",",
"Null",
")",
":",
"varBinds",
"[",
"col",
"]",
"=",
"previousVarBinds",
"[",
"col",
"]",
"[",
"0",
"]",
",",
"endOfMibView",
"if",
"not",
"lexicographicMode",
"and",
"not",
"initialVars",
"[",
"col",
"]",
".",
"isPrefixOf",
"(",
"name",
")",
":",
"varBinds",
"[",
"col",
"]",
"=",
"previousVarBinds",
"[",
"col",
"]",
"[",
"0",
"]",
",",
"endOfMibView",
"if",
"stopFlag",
"and",
"varBinds",
"[",
"col",
"]",
"[",
"1",
"]",
"is",
"not",
"endOfMibView",
":",
"stopFlag",
"=",
"False",
"if",
"stopFlag",
":",
"return",
"totalRows",
"+=",
"1",
"totalCalls",
"+=",
"1",
"else",
":",
"errorIndication",
"=",
"errorStatus",
"=",
"errorIndex",
"=",
"None",
"varBinds",
"=",
"[",
"]",
"initialVarBinds",
"=",
"(",
"yield",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBinds",
")",
"if",
"initialVarBinds",
":",
"varBinds",
"=",
"initialVarBinds",
"initialVars",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"vbProcessor",
".",
"makeVarBinds",
"(",
"snmpEngine",
".",
"cache",
",",
"varBinds",
")",
"]",
"if",
"maxRows",
"and",
"totalRows",
">=",
"maxRows",
":",
"return",
"if",
"maxCalls",
"and",
"totalCalls",
">=",
"maxCalls",
":",
"return"
] | Creates a generator to perform one or more SNMP GETNEXT queries.
On each iteration, new SNMP GETNEXT request is send
(:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
to arrive or error to occur.
Parameters
----------
snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData : :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication : str
True value indicates SNMP engine error.
errorStatus : str
True value indicates SNMP PDU error.
errorIndex : int
Non-zero value refers to `varBinds[errorIndex-1]`
varBinds : tuple
A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `nextCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi import *
>>> g = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))])
>>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] )
(None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) | [
"Creates",
"a",
"generator",
"to",
"perform",
"one",
"or",
"more",
"SNMP",
"GETNEXT",
"queries",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/asyncore/sync/cmdgen.py#L229-L413 |
251,266 | etingof/pysnmp | pysnmp/entity/rfc3413/cmdrsp.py | CommandResponderBase._storeAccessContext | def _storeAccessContext(snmpEngine):
"""Copy received message metadata while it lasts"""
execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request')
return {
'securityModel': execCtx['securityModel'],
'securityName': execCtx['securityName'],
'securityLevel': execCtx['securityLevel'],
'contextName': execCtx['contextName'],
'pduType': execCtx['pdu'].getTagSet()
} | python | def _storeAccessContext(snmpEngine):
execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request')
return {
'securityModel': execCtx['securityModel'],
'securityName': execCtx['securityName'],
'securityLevel': execCtx['securityLevel'],
'contextName': execCtx['contextName'],
'pduType': execCtx['pdu'].getTagSet()
} | [
"def",
"_storeAccessContext",
"(",
"snmpEngine",
")",
":",
"execCtx",
"=",
"snmpEngine",
".",
"observer",
".",
"getExecutionContext",
"(",
"'rfc3412.receiveMessage:request'",
")",
"return",
"{",
"'securityModel'",
":",
"execCtx",
"[",
"'securityModel'",
"]",
",",
"'securityName'",
":",
"execCtx",
"[",
"'securityName'",
"]",
",",
"'securityLevel'",
":",
"execCtx",
"[",
"'securityLevel'",
"]",
",",
"'contextName'",
":",
"execCtx",
"[",
"'contextName'",
"]",
",",
"'pduType'",
":",
"execCtx",
"[",
"'pdu'",
"]",
".",
"getTagSet",
"(",
")",
"}"
] | Copy received message metadata while it lasts | [
"Copy",
"received",
"message",
"metadata",
"while",
"it",
"lasts"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/entity/rfc3413/cmdrsp.py#L174-L184 |
251,267 | etingof/pysnmp | pysnmp/entity/rfc3413/cmdrsp.py | NextCommandResponder._getManagedObjectsInstances | def _getManagedObjectsInstances(self, varBinds, **context):
"""Iterate over Managed Objects fulfilling SNMP query.
Returns
-------
:py:class:`list` - List of Managed Objects Instances to respond with or
`None` to indicate that not all objects have been gathered
so far.
"""
rspVarBinds = context['rspVarBinds']
varBindsMap = context['varBindsMap']
rtrVarBinds = []
for idx, varBind in enumerate(varBinds):
name, val = varBind
if (exval.noSuchObject.isSameTypeWith(val) or
exval.noSuchInstance.isSameTypeWith(val)):
varBindsMap[len(rtrVarBinds)] = varBindsMap.pop(idx, idx)
rtrVarBinds.append(varBind)
else:
rspVarBinds[varBindsMap.pop(idx, idx)] = varBind
if rtrVarBinds:
snmpEngine = context['snmpEngine']
# Need to unwind stack, can't recurse any more
def callLater(*args):
snmpEngine.transportDispatcher.unregisterTimerCbFun(callLater)
mgmtFun = context['mgmtFun']
mgmtFun(*varBinds, **context)
snmpEngine.transportDispatcher.registerTimerCbFun(callLater, 0.01)
else:
return rspVarBinds | python | def _getManagedObjectsInstances(self, varBinds, **context):
rspVarBinds = context['rspVarBinds']
varBindsMap = context['varBindsMap']
rtrVarBinds = []
for idx, varBind in enumerate(varBinds):
name, val = varBind
if (exval.noSuchObject.isSameTypeWith(val) or
exval.noSuchInstance.isSameTypeWith(val)):
varBindsMap[len(rtrVarBinds)] = varBindsMap.pop(idx, idx)
rtrVarBinds.append(varBind)
else:
rspVarBinds[varBindsMap.pop(idx, idx)] = varBind
if rtrVarBinds:
snmpEngine = context['snmpEngine']
# Need to unwind stack, can't recurse any more
def callLater(*args):
snmpEngine.transportDispatcher.unregisterTimerCbFun(callLater)
mgmtFun = context['mgmtFun']
mgmtFun(*varBinds, **context)
snmpEngine.transportDispatcher.registerTimerCbFun(callLater, 0.01)
else:
return rspVarBinds | [
"def",
"_getManagedObjectsInstances",
"(",
"self",
",",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"rspVarBinds",
"=",
"context",
"[",
"'rspVarBinds'",
"]",
"varBindsMap",
"=",
"context",
"[",
"'varBindsMap'",
"]",
"rtrVarBinds",
"=",
"[",
"]",
"for",
"idx",
",",
"varBind",
"in",
"enumerate",
"(",
"varBinds",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"if",
"(",
"exval",
".",
"noSuchObject",
".",
"isSameTypeWith",
"(",
"val",
")",
"or",
"exval",
".",
"noSuchInstance",
".",
"isSameTypeWith",
"(",
"val",
")",
")",
":",
"varBindsMap",
"[",
"len",
"(",
"rtrVarBinds",
")",
"]",
"=",
"varBindsMap",
".",
"pop",
"(",
"idx",
",",
"idx",
")",
"rtrVarBinds",
".",
"append",
"(",
"varBind",
")",
"else",
":",
"rspVarBinds",
"[",
"varBindsMap",
".",
"pop",
"(",
"idx",
",",
"idx",
")",
"]",
"=",
"varBind",
"if",
"rtrVarBinds",
":",
"snmpEngine",
"=",
"context",
"[",
"'snmpEngine'",
"]",
"# Need to unwind stack, can't recurse any more",
"def",
"callLater",
"(",
"*",
"args",
")",
":",
"snmpEngine",
".",
"transportDispatcher",
".",
"unregisterTimerCbFun",
"(",
"callLater",
")",
"mgmtFun",
"=",
"context",
"[",
"'mgmtFun'",
"]",
"mgmtFun",
"(",
"*",
"varBinds",
",",
"*",
"*",
"context",
")",
"snmpEngine",
".",
"transportDispatcher",
".",
"registerTimerCbFun",
"(",
"callLater",
",",
"0.01",
")",
"else",
":",
"return",
"rspVarBinds"
] | Iterate over Managed Objects fulfilling SNMP query.
Returns
-------
:py:class:`list` - List of Managed Objects Instances to respond with or
`None` to indicate that not all objects have been gathered
so far. | [
"Iterate",
"over",
"Managed",
"Objects",
"fulfilling",
"SNMP",
"query",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/entity/rfc3413/cmdrsp.py#L339-L375 |
251,268 | etingof/pysnmp | pysnmp/proto/rfc1155.py | NetworkAddress.clone | def clone(self, value=univ.noValue, **kwargs):
"""Clone this instance.
If *value* is specified, use its tag as the component type selector,
and itself as the component value.
:param value: (Optional) the component value.
:type value: :py:obj:`pyasn1.type.base.Asn1ItemBase`
:return: the cloned instance.
:rtype: :py:obj:`pysnmp.proto.rfc1155.NetworkAddress`
:raise: :py:obj:`pysnmp.smi.error.SmiError`:
if the type of *value* is not allowed for this Choice instance.
"""
cloned = univ.Choice.clone(self, **kwargs)
if value is not univ.noValue:
if isinstance(value, NetworkAddress):
value = value.getComponent()
elif not isinstance(value, IpAddress):
# IpAddress is the only supported type, perhaps forever because
# this is SNMPv1.
value = IpAddress(value)
try:
tagSet = value.tagSet
except AttributeError:
raise PyAsn1Error('component value %r has no tag set' % (value,))
cloned.setComponentByType(tagSet, value)
return cloned | python | def clone(self, value=univ.noValue, **kwargs):
cloned = univ.Choice.clone(self, **kwargs)
if value is not univ.noValue:
if isinstance(value, NetworkAddress):
value = value.getComponent()
elif not isinstance(value, IpAddress):
# IpAddress is the only supported type, perhaps forever because
# this is SNMPv1.
value = IpAddress(value)
try:
tagSet = value.tagSet
except AttributeError:
raise PyAsn1Error('component value %r has no tag set' % (value,))
cloned.setComponentByType(tagSet, value)
return cloned | [
"def",
"clone",
"(",
"self",
",",
"value",
"=",
"univ",
".",
"noValue",
",",
"*",
"*",
"kwargs",
")",
":",
"cloned",
"=",
"univ",
".",
"Choice",
".",
"clone",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"if",
"value",
"is",
"not",
"univ",
".",
"noValue",
":",
"if",
"isinstance",
"(",
"value",
",",
"NetworkAddress",
")",
":",
"value",
"=",
"value",
".",
"getComponent",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"IpAddress",
")",
":",
"# IpAddress is the only supported type, perhaps forever because",
"# this is SNMPv1.",
"value",
"=",
"IpAddress",
"(",
"value",
")",
"try",
":",
"tagSet",
"=",
"value",
".",
"tagSet",
"except",
"AttributeError",
":",
"raise",
"PyAsn1Error",
"(",
"'component value %r has no tag set'",
"%",
"(",
"value",
",",
")",
")",
"cloned",
".",
"setComponentByType",
"(",
"tagSet",
",",
"value",
")",
"return",
"cloned"
] | Clone this instance.
If *value* is specified, use its tag as the component type selector,
and itself as the component value.
:param value: (Optional) the component value.
:type value: :py:obj:`pyasn1.type.base.Asn1ItemBase`
:return: the cloned instance.
:rtype: :py:obj:`pysnmp.proto.rfc1155.NetworkAddress`
:raise: :py:obj:`pysnmp.smi.error.SmiError`:
if the type of *value* is not allowed for this Choice instance. | [
"Clone",
"this",
"instance",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1155.py#L63-L95 |
251,269 | etingof/pysnmp | pysnmp/smi/instrum.py | MibInstrumController._defaultErrorHandler | def _defaultErrorHandler(varBinds, **context):
"""Raise exception on any error if user callback is missing"""
errors = context.get('errors')
if errors:
err = errors[-1]
raise err['error'] | python | def _defaultErrorHandler(varBinds, **context):
errors = context.get('errors')
if errors:
err = errors[-1]
raise err['error'] | [
"def",
"_defaultErrorHandler",
"(",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"errors",
"=",
"context",
".",
"get",
"(",
"'errors'",
")",
"if",
"errors",
":",
"err",
"=",
"errors",
"[",
"-",
"1",
"]",
"raise",
"err",
"[",
"'error'",
"]"
] | Raise exception on any error if user callback is missing | [
"Raise",
"exception",
"on",
"any",
"error",
"if",
"user",
"callback",
"is",
"missing"
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L375-L381 |
251,270 | etingof/pysnmp | pysnmp/smi/instrum.py | MibInstrumController.readMibObjects | def readMibObjects(self, *varBinds, **context):
"""Read Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the referenced Managed Objects Instances.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be either
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated).
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_READ_VAR, *varBinds, **context) | python | def readMibObjects(self, *varBinds, **context):
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_READ_VAR, *varBinds, **context) | [
"def",
"readMibObjects",
"(",
"self",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"if",
"'cbFun'",
"not",
"in",
"context",
":",
"context",
"[",
"'cbFun'",
"]",
"=",
"self",
".",
"_defaultErrorHandler",
"self",
".",
"flipFlopFsm",
"(",
"self",
".",
"FSM_READ_VAR",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")"
] | Read Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the referenced Managed Objects Instances.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be either
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated). | [
"Read",
"Managed",
"Objects",
"Instances",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L383-L435 |
251,271 | etingof/pysnmp | pysnmp/smi/instrum.py | MibInstrumController.readNextMibObjects | def readNextMibObjects(self, *varBinds, **context):
"""Read Managed Objects Instances next to the given ones.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the Managed Objects Instances next to the referenced ones.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read next to.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated) or :py:class:`EndOfMibView` (when the last Managed Object
Instance has been read).
When :py:class:`NoSuchObject` or :py:class:`NoSuchInstance` values are
returned, the caller is expected to repeat the same call with some
or all `varBinds` returned to progress towards the end of the
implemented MIB.
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_READ_NEXT_VAR, *varBinds, **context) | python | def readNextMibObjects(self, *varBinds, **context):
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_READ_NEXT_VAR, *varBinds, **context) | [
"def",
"readNextMibObjects",
"(",
"self",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"if",
"'cbFun'",
"not",
"in",
"context",
":",
"context",
"[",
"'cbFun'",
"]",
"=",
"self",
".",
"_defaultErrorHandler",
"self",
".",
"flipFlopFsm",
"(",
"self",
".",
"FSM_READ_NEXT_VAR",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")"
] | Read Managed Objects Instances next to the given ones.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read
all or none of the Managed Objects Instances next to the referenced ones.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to read next to.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but is not
instantiated) or :py:class:`EndOfMibView` (when the last Managed Object
Instance has been read).
When :py:class:`NoSuchObject` or :py:class:`NoSuchInstance` values are
returned, the caller is expected to repeat the same call with some
or all `varBinds` returned to progress towards the end of the
implemented MIB. | [
"Read",
"Managed",
"Objects",
"Instances",
"next",
"to",
"the",
"given",
"ones",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L437-L495 |
251,272 | etingof/pysnmp | pysnmp/smi/instrum.py | MibInstrumController.writeMibObjects | def writeMibObjects(self, *varBinds, **context):
"""Create, destroy or modify Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create,
destroy or modify all or none of the referenced Managed Objects Instances.
If a non-existing Managed Object Instance is written, the new Managed Object
Instance will be created with the value given in the `varBinds`.
If existing Managed Object Instance is being written, its value is changed
to the new one.
Unless it's a :py:class:`RowStatus` object of a SMI table, in which case the
outcome of the *write* operation depends on the :py:class:`RowStatus`
transition. The whole table row could be created or destroyed or brought
on/offline.
When SMI table row is brought online (i.e. into the *active* state), all
columns will be checked for consistency. Error will be reported and write
operation will fail if inconsistency is found.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to modify.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but can't be
modified.
"""
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_WRITE_VAR, *varBinds, **context) | python | def writeMibObjects(self, *varBinds, **context):
if 'cbFun' not in context:
context['cbFun'] = self._defaultErrorHandler
self.flipFlopFsm(self.FSM_WRITE_VAR, *varBinds, **context) | [
"def",
"writeMibObjects",
"(",
"self",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")",
":",
"if",
"'cbFun'",
"not",
"in",
"context",
":",
"context",
"[",
"'cbFun'",
"]",
"=",
"self",
".",
"_defaultErrorHandler",
"self",
".",
"flipFlopFsm",
"(",
"self",
".",
"FSM_WRITE_VAR",
",",
"*",
"varBinds",
",",
"*",
"*",
"context",
")"
] | Create, destroy or modify Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create,
destroy or modify all or none of the referenced Managed Objects Instances.
If a non-existing Managed Object Instance is written, the new Managed Object
Instance will be created with the value given in the `varBinds`.
If existing Managed Object Instance is being written, its value is changed
to the new one.
Unless it's a :py:class:`RowStatus` object of a SMI table, in which case the
outcome of the *write* operation depends on the :py:class:`RowStatus`
transition. The whole table row could be created or destroyed or brought
on/offline.
When SMI table row is brought online (i.e. into the *active* state), all
columns will be checked for consistency. Error will be reported and write
operation will fail if inconsistency is found.
Parameters
----------
varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects
representing Managed Objects Instances to modify.
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked to
pass the new value of the Managed Object Instance or an error.
If not provided, default function will raise exception in case
of an error.
* `acFun` (callable) - user-supplied callable that is invoked to
authorize access to the requested Managed Object Instance. If
not supplied, no access control will be performed.
Notes
-----
The signature of the callback functions (e.g. `cbFun`, `acFun`) is this:
.. code-block: python
def cbFun(varBinds, **context):
errors = context.get(errors)
if errors:
print(errors[0].error)
else:
print(', '.join('%s = %s' % varBind for varBind in varBinds))
In case of errors, the `errors` key in the `context` dict will contain
a sequence of `dict` objects describing one or more errors that occur.
If a non-existing Managed Object is referenced, no error will be
reported, but the values returned in the `varBinds` would be one of:
:py:class:`NoSuchObject` (indicating non-existent Managed Object) or
:py:class:`NoSuchInstance` (if Managed Object exists, but can't be
modified. | [
"Create",
"destroy",
"or",
"modify",
"Managed",
"Objects",
"Instances",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L497-L564 |
251,273 | etingof/pysnmp | pysnmp/hlapi/v1arch/asyncore/cmdgen.py | bulkCmd | def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
"""Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher`
Class instance representing SNMP dispatcher.
authData: :py:class:`~pysnmp.hlapi.v1arch.CommunityData` or :py:class:`~pysnmp.hlapi.v1arch.UsmUserData`
Class instance representing SNMP credentials.
transportTarget: :py:class:`~pysnmp.hlapi.v1arch.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.v1arch.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer
address.
nonRepeaters: int
One MIB variable is requested in response for the first
`nonRepeaters` MIB variables in request.
maxRepetitions: int
`maxRepetitions` MIB variables are requested in response for each
of the remaining MIB variables in the request (e.g. excluding
`nonRepeaters`). Remote SNMP dispatcher may choose lesser value than
requested.
\*varBinds: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `cbFun` (callable) - user-supplied callable that is invoked
to pass SNMP response data or error to user at a later point
of time. Default is `None`.
* `cbCtx` (object) - user-supplied object passing additional
parameters to/from `cbFun`. Default is `None`.
Notes
-----
User-supplied `cbFun` callable must have the following call
signature:
* snmpDispatcher (:py:class:`~pysnmp.hlapi.v1arch.snmpDispatcher`):
Class instance representing SNMP dispatcher.
* stateHandle (int): Unique request identifier. Can be used
for matching multiple ongoing requests with received responses.
* errorIndication (str): True value indicates SNMP dispatcher error.
* errorStatus (str): True value indicates SNMP PDU error.
* errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]`
* varBindTable (tuple): A sequence of sequences (e.g. 2-D array) of
variable-bindings represented as :class:`tuple` or
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response, with
up to ``maxRepetitions`` rows, i.e. ``len(varBindTable) <= maxRepetitions``.
For ``0 <= i < len(varBindTable)`` and ``0 <= j < len(varBinds)``,
``varBindTable[i][j]`` represents:
- For non-repeaters (``j < nonRepeaters``), the first lexicographic
successor of ``varBinds[j]``, regardless the value of ``i``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists;
- For repeaters (``j >= nonRepeaters``), the ``i``-th lexicographic
successor of ``varBinds[j]``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists.
See :rfc:`3416#section-4.2.3` for details on the underlying
``GetBulkRequest-PDU`` and the associated ``GetResponse-PDU``, such as
specific conditions under which the server may truncate the response,
causing ``varBindTable`` to have less than ``maxRepetitions`` rows.
* `cbCtx` (object): Original user-supplied object.
Returns
-------
stateHandle : int
Unique request identifier. Can be used for matching received
responses with ongoing requests.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Examples
--------
>>> from pysnmp.hlapi.v1arch.asyncore import *
>>>
>>> def cbFun(snmpDispatcher, stateHandle, errorIndication,
>>> errorStatus, errorIndex, varBinds, cbCtx):
>>> print(errorIndication, errorStatus, errorIndex, varBinds)
>>>
>>> snmpDispatcher = snmpDispatcher()
>>>
>>> stateHandle = bulkCmd(
>>> snmpDispatcher,
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> 0, 2,
>>> ('1.3.6.1.2.1.1', None),
>>> cbFun=cbFun
>>> )
>>>
>>> snmpDispatcher.transportDispatcher.runDispatcher()
"""
def _cbFun(snmpDispatcher, stateHandle, errorIndication, rspPdu, _cbCtx):
if not cbFun:
return
if errorIndication:
cbFun(errorIndication, pMod.Integer(0), pMod.Integer(0), None,
cbCtx=cbCtx, snmpDispatcher=snmpDispatcher, stateHandle=stateHandle)
return
errorStatus = pMod.apiBulkPDU.getErrorStatus(rspPdu)
errorIndex = pMod.apiBulkPDU.getErrorIndex(rspPdu)
varBindTable = pMod.apiBulkPDU.getVarBindTable(reqPdu, rspPdu)
errorIndication, nextVarBinds = pMod.apiBulkPDU.getNextVarBinds(
varBindTable[-1], errorIndex=errorIndex
)
if options.get('lookupMib'):
varBindTable = [
VB_PROCESSOR.unmakeVarBinds(snmpDispatcher.cache, vbs) for vbs in varBindTable
]
nextStateHandle = pMod.getNextRequestID()
nextVarBinds = cbFun(errorIndication, errorStatus, errorIndex, varBindTable,
cbCtx=cbCtx,
snmpDispatcher=snmpDispatcher,
stateHandle=stateHandle,
nextStateHandle=nextStateHandle,
nextVarBinds=nextVarBinds)
if not nextVarBinds:
return
pMod.apiBulkPDU.setRequestID(reqPdu, nextStateHandle)
pMod.apiBulkPDU.setVarBinds(reqPdu, nextVarBinds)
return snmpDispatcher.sendPdu(authData, transportTarget, reqPdu, cbFun=_cbFun)
if authData.mpModel < 1:
raise error.PySnmpError('GETBULK PDU is only supported in SNMPv2c and SNMPv3')
lookupMib, cbFun, cbCtx = [options.get(x) for x in ('lookupMib', 'cbFun', 'cbCtx')]
if lookupMib:
varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqPdu = pMod.GetBulkRequestPDU()
pMod.apiBulkPDU.setDefaults(reqPdu)
pMod.apiBulkPDU.setNonRepeaters(reqPdu, nonRepeaters)
pMod.apiBulkPDU.setMaxRepetitions(reqPdu, maxRepetitions)
pMod.apiBulkPDU.setVarBinds(reqPdu, varBinds)
return snmpDispatcher.sendPdu(authData, transportTarget, reqPdu, cbFun=_cbFun) | python | def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
def _cbFun(snmpDispatcher, stateHandle, errorIndication, rspPdu, _cbCtx):
if not cbFun:
return
if errorIndication:
cbFun(errorIndication, pMod.Integer(0), pMod.Integer(0), None,
cbCtx=cbCtx, snmpDispatcher=snmpDispatcher, stateHandle=stateHandle)
return
errorStatus = pMod.apiBulkPDU.getErrorStatus(rspPdu)
errorIndex = pMod.apiBulkPDU.getErrorIndex(rspPdu)
varBindTable = pMod.apiBulkPDU.getVarBindTable(reqPdu, rspPdu)
errorIndication, nextVarBinds = pMod.apiBulkPDU.getNextVarBinds(
varBindTable[-1], errorIndex=errorIndex
)
if options.get('lookupMib'):
varBindTable = [
VB_PROCESSOR.unmakeVarBinds(snmpDispatcher.cache, vbs) for vbs in varBindTable
]
nextStateHandle = pMod.getNextRequestID()
nextVarBinds = cbFun(errorIndication, errorStatus, errorIndex, varBindTable,
cbCtx=cbCtx,
snmpDispatcher=snmpDispatcher,
stateHandle=stateHandle,
nextStateHandle=nextStateHandle,
nextVarBinds=nextVarBinds)
if not nextVarBinds:
return
pMod.apiBulkPDU.setRequestID(reqPdu, nextStateHandle)
pMod.apiBulkPDU.setVarBinds(reqPdu, nextVarBinds)
return snmpDispatcher.sendPdu(authData, transportTarget, reqPdu, cbFun=_cbFun)
if authData.mpModel < 1:
raise error.PySnmpError('GETBULK PDU is only supported in SNMPv2c and SNMPv3')
lookupMib, cbFun, cbCtx = [options.get(x) for x in ('lookupMib', 'cbFun', 'cbCtx')]
if lookupMib:
varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqPdu = pMod.GetBulkRequestPDU()
pMod.apiBulkPDU.setDefaults(reqPdu)
pMod.apiBulkPDU.setNonRepeaters(reqPdu, nonRepeaters)
pMod.apiBulkPDU.setMaxRepetitions(reqPdu, maxRepetitions)
pMod.apiBulkPDU.setVarBinds(reqPdu, varBinds)
return snmpDispatcher.sendPdu(authData, transportTarget, reqPdu, cbFun=_cbFun) | [
"def",
"bulkCmd",
"(",
"snmpDispatcher",
",",
"authData",
",",
"transportTarget",
",",
"nonRepeaters",
",",
"maxRepetitions",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"def",
"_cbFun",
"(",
"snmpDispatcher",
",",
"stateHandle",
",",
"errorIndication",
",",
"rspPdu",
",",
"_cbCtx",
")",
":",
"if",
"not",
"cbFun",
":",
"return",
"if",
"errorIndication",
":",
"cbFun",
"(",
"errorIndication",
",",
"pMod",
".",
"Integer",
"(",
"0",
")",
",",
"pMod",
".",
"Integer",
"(",
"0",
")",
",",
"None",
",",
"cbCtx",
"=",
"cbCtx",
",",
"snmpDispatcher",
"=",
"snmpDispatcher",
",",
"stateHandle",
"=",
"stateHandle",
")",
"return",
"errorStatus",
"=",
"pMod",
".",
"apiBulkPDU",
".",
"getErrorStatus",
"(",
"rspPdu",
")",
"errorIndex",
"=",
"pMod",
".",
"apiBulkPDU",
".",
"getErrorIndex",
"(",
"rspPdu",
")",
"varBindTable",
"=",
"pMod",
".",
"apiBulkPDU",
".",
"getVarBindTable",
"(",
"reqPdu",
",",
"rspPdu",
")",
"errorIndication",
",",
"nextVarBinds",
"=",
"pMod",
".",
"apiBulkPDU",
".",
"getNextVarBinds",
"(",
"varBindTable",
"[",
"-",
"1",
"]",
",",
"errorIndex",
"=",
"errorIndex",
")",
"if",
"options",
".",
"get",
"(",
"'lookupMib'",
")",
":",
"varBindTable",
"=",
"[",
"VB_PROCESSOR",
".",
"unmakeVarBinds",
"(",
"snmpDispatcher",
".",
"cache",
",",
"vbs",
")",
"for",
"vbs",
"in",
"varBindTable",
"]",
"nextStateHandle",
"=",
"pMod",
".",
"getNextRequestID",
"(",
")",
"nextVarBinds",
"=",
"cbFun",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"varBindTable",
",",
"cbCtx",
"=",
"cbCtx",
",",
"snmpDispatcher",
"=",
"snmpDispatcher",
",",
"stateHandle",
"=",
"stateHandle",
",",
"nextStateHandle",
"=",
"nextStateHandle",
",",
"nextVarBinds",
"=",
"nextVarBinds",
")",
"if",
"not",
"nextVarBinds",
":",
"return",
"pMod",
".",
"apiBulkPDU",
".",
"setRequestID",
"(",
"reqPdu",
",",
"nextStateHandle",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setVarBinds",
"(",
"reqPdu",
",",
"nextVarBinds",
")",
"return",
"snmpDispatcher",
".",
"sendPdu",
"(",
"authData",
",",
"transportTarget",
",",
"reqPdu",
",",
"cbFun",
"=",
"_cbFun",
")",
"if",
"authData",
".",
"mpModel",
"<",
"1",
":",
"raise",
"error",
".",
"PySnmpError",
"(",
"'GETBULK PDU is only supported in SNMPv2c and SNMPv3'",
")",
"lookupMib",
",",
"cbFun",
",",
"cbCtx",
"=",
"[",
"options",
".",
"get",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"'lookupMib'",
",",
"'cbFun'",
",",
"'cbCtx'",
")",
"]",
"if",
"lookupMib",
":",
"varBinds",
"=",
"VB_PROCESSOR",
".",
"makeVarBinds",
"(",
"snmpDispatcher",
".",
"cache",
",",
"varBinds",
")",
"pMod",
"=",
"api",
".",
"PROTOCOL_MODULES",
"[",
"authData",
".",
"mpModel",
"]",
"reqPdu",
"=",
"pMod",
".",
"GetBulkRequestPDU",
"(",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setDefaults",
"(",
"reqPdu",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setNonRepeaters",
"(",
"reqPdu",
",",
"nonRepeaters",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setMaxRepetitions",
"(",
"reqPdu",
",",
"maxRepetitions",
")",
"pMod",
".",
"apiBulkPDU",
".",
"setVarBinds",
"(",
"reqPdu",
",",
"varBinds",
")",
"return",
"snmpDispatcher",
".",
"sendPdu",
"(",
"authData",
",",
"transportTarget",
",",
"reqPdu",
",",
"cbFun",
"=",
"_cbFun",
")"
] | Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher`
Class instance representing SNMP dispatcher.
authData: :py:class:`~pysnmp.hlapi.v1arch.CommunityData` or :py:class:`~pysnmp.hlapi.v1arch.UsmUserData`
Class instance representing SNMP credentials.
transportTarget: :py:class:`~pysnmp.hlapi.v1arch.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.v1arch.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer
address.
nonRepeaters: int
One MIB variable is requested in response for the first
`nonRepeaters` MIB variables in request.
maxRepetitions: int
`maxRepetitions` MIB variables are requested in response for each
of the remaining MIB variables in the request (e.g. excluding
`nonRepeaters`). Remote SNMP dispatcher may choose lesser value than
requested.
\*varBinds: :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
* `cbFun` (callable) - user-supplied callable that is invoked
to pass SNMP response data or error to user at a later point
of time. Default is `None`.
* `cbCtx` (object) - user-supplied object passing additional
parameters to/from `cbFun`. Default is `None`.
Notes
-----
User-supplied `cbFun` callable must have the following call
signature:
* snmpDispatcher (:py:class:`~pysnmp.hlapi.v1arch.snmpDispatcher`):
Class instance representing SNMP dispatcher.
* stateHandle (int): Unique request identifier. Can be used
for matching multiple ongoing requests with received responses.
* errorIndication (str): True value indicates SNMP dispatcher error.
* errorStatus (str): True value indicates SNMP PDU error.
* errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]`
* varBindTable (tuple): A sequence of sequences (e.g. 2-D array) of
variable-bindings represented as :class:`tuple` or
:py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
representing a table of MIB variables returned in SNMP response, with
up to ``maxRepetitions`` rows, i.e. ``len(varBindTable) <= maxRepetitions``.
For ``0 <= i < len(varBindTable)`` and ``0 <= j < len(varBinds)``,
``varBindTable[i][j]`` represents:
- For non-repeaters (``j < nonRepeaters``), the first lexicographic
successor of ``varBinds[j]``, regardless the value of ``i``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists;
- For repeaters (``j >= nonRepeaters``), the ``i``-th lexicographic
successor of ``varBinds[j]``, or an
:py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the
:py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor
exists.
See :rfc:`3416#section-4.2.3` for details on the underlying
``GetBulkRequest-PDU`` and the associated ``GetResponse-PDU``, such as
specific conditions under which the server may truncate the response,
causing ``varBindTable`` to have less than ``maxRepetitions`` rows.
* `cbCtx` (object): Original user-supplied object.
Returns
-------
stateHandle : int
Unique request identifier. Can be used for matching received
responses with ongoing requests.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Examples
--------
>>> from pysnmp.hlapi.v1arch.asyncore import *
>>>
>>> def cbFun(snmpDispatcher, stateHandle, errorIndication,
>>> errorStatus, errorIndex, varBinds, cbCtx):
>>> print(errorIndication, errorStatus, errorIndex, varBinds)
>>>
>>> snmpDispatcher = snmpDispatcher()
>>>
>>> stateHandle = bulkCmd(
>>> snmpDispatcher,
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> 0, 2,
>>> ('1.3.6.1.2.1.1', None),
>>> cbFun=cbFun
>>> )
>>>
>>> snmpDispatcher.transportDispatcher.runDispatcher() | [
"Initiate",
"SNMP",
"GETBULK",
"query",
"over",
"SNMPv2c",
"."
] | cde062dd42f67dfd2d7686286a322d40e9c3a4b7 | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v1arch/asyncore/cmdgen.py#L451-L626 |
251,274 | markreidvfx/pyaaf2 | aaf2/file.py | AAFFile.save | def save(self):
"""
Writes current changes to disk and flushes modified objects in the
AAFObjectManager
"""
if self.mode in ("wb+", 'rb+'):
if not self.is_open:
raise IOError("file closed")
self.write_reference_properties()
self.manager.write_objects() | python | def save(self):
if self.mode in ("wb+", 'rb+'):
if not self.is_open:
raise IOError("file closed")
self.write_reference_properties()
self.manager.write_objects() | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"in",
"(",
"\"wb+\"",
",",
"'rb+'",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"IOError",
"(",
"\"file closed\"",
")",
"self",
".",
"write_reference_properties",
"(",
")",
"self",
".",
"manager",
".",
"write_objects",
"(",
")"
] | Writes current changes to disk and flushes modified objects in the
AAFObjectManager | [
"Writes",
"current",
"changes",
"to",
"disk",
"and",
"flushes",
"modified",
"objects",
"in",
"the",
"AAFObjectManager"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/file.py#L339-L348 |
251,275 | markreidvfx/pyaaf2 | aaf2/file.py | AAFFile.close | def close(self):
"""
Close the file. A closed file cannot be read or written any more.
"""
self.save()
self.manager.remove_temp()
self.cfb.close()
self.is_open = False
self.f.close() | python | def close(self):
self.save()
self.manager.remove_temp()
self.cfb.close()
self.is_open = False
self.f.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"save",
"(",
")",
"self",
".",
"manager",
".",
"remove_temp",
"(",
")",
"self",
".",
"cfb",
".",
"close",
"(",
")",
"self",
".",
"is_open",
"=",
"False",
"self",
".",
"f",
".",
"close",
"(",
")"
] | Close the file. A closed file cannot be read or written any more. | [
"Close",
"the",
"file",
".",
"A",
"closed",
"file",
"cannot",
"be",
"read",
"or",
"written",
"any",
"more",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/file.py#L350-L358 |
251,276 | markreidvfx/pyaaf2 | docs/source/conf.py | run_apidoc | def run_apidoc(_):
"""This method is required by the setup method below."""
import os
dirname = os.path.dirname(__file__)
ignore_paths = [os.path.join(dirname, '../../aaf2/model'),]
# https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py
argv = [
'--force',
'--no-toc',
'--separate',
'--module-first',
'--output-dir',
os.path.join(dirname, 'api'),
os.path.join(dirname, '../../aaf2'),
] + ignore_paths
from sphinx.ext import apidoc
apidoc.main(argv) | python | def run_apidoc(_):
import os
dirname = os.path.dirname(__file__)
ignore_paths = [os.path.join(dirname, '../../aaf2/model'),]
# https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py
argv = [
'--force',
'--no-toc',
'--separate',
'--module-first',
'--output-dir',
os.path.join(dirname, 'api'),
os.path.join(dirname, '../../aaf2'),
] + ignore_paths
from sphinx.ext import apidoc
apidoc.main(argv) | [
"def",
"run_apidoc",
"(",
"_",
")",
":",
"import",
"os",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"ignore_paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'../../aaf2/model'",
")",
",",
"]",
"# https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py",
"argv",
"=",
"[",
"'--force'",
",",
"'--no-toc'",
",",
"'--separate'",
",",
"'--module-first'",
",",
"'--output-dir'",
",",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'api'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'../../aaf2'",
")",
",",
"]",
"+",
"ignore_paths",
"from",
"sphinx",
".",
"ext",
"import",
"apidoc",
"apidoc",
".",
"main",
"(",
"argv",
")"
] | This method is required by the setup method below. | [
"This",
"method",
"is",
"required",
"by",
"the",
"setup",
"method",
"below",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/docs/source/conf.py#L182-L199 |
251,277 | markreidvfx/pyaaf2 | aaf2/mobid.py | MobID.from_dict | def from_dict(self, d):
"""
Set MobID from a dict
"""
self.length = d.get("length", 0)
self.instanceHigh = d.get("instanceHigh", 0)
self.instanceMid = d.get("instanceMid", 0)
self.instanceLow = d.get("instanceLow", 0)
material = d.get("material", {'Data1':0, 'Data2':0, 'Data3':0, 'Data4': [0 for i in range(8)]})
self.Data1 = material.get('Data1', 0)
self.Data2 = material.get('Data2', 0)
self.Data3 = material.get('Data3', 0)
self.Data4 = material.get("Data4", [0 for i in range(8)])
self.SMPTELabel = d.get("SMPTELabel", [0 for i in range(12)]) | python | def from_dict(self, d):
self.length = d.get("length", 0)
self.instanceHigh = d.get("instanceHigh", 0)
self.instanceMid = d.get("instanceMid", 0)
self.instanceLow = d.get("instanceLow", 0)
material = d.get("material", {'Data1':0, 'Data2':0, 'Data3':0, 'Data4': [0 for i in range(8)]})
self.Data1 = material.get('Data1', 0)
self.Data2 = material.get('Data2', 0)
self.Data3 = material.get('Data3', 0)
self.Data4 = material.get("Data4", [0 for i in range(8)])
self.SMPTELabel = d.get("SMPTELabel", [0 for i in range(12)]) | [
"def",
"from_dict",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"length",
"=",
"d",
".",
"get",
"(",
"\"length\"",
",",
"0",
")",
"self",
".",
"instanceHigh",
"=",
"d",
".",
"get",
"(",
"\"instanceHigh\"",
",",
"0",
")",
"self",
".",
"instanceMid",
"=",
"d",
".",
"get",
"(",
"\"instanceMid\"",
",",
"0",
")",
"self",
".",
"instanceLow",
"=",
"d",
".",
"get",
"(",
"\"instanceLow\"",
",",
"0",
")",
"material",
"=",
"d",
".",
"get",
"(",
"\"material\"",
",",
"{",
"'Data1'",
":",
"0",
",",
"'Data2'",
":",
"0",
",",
"'Data3'",
":",
"0",
",",
"'Data4'",
":",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"8",
")",
"]",
"}",
")",
"self",
".",
"Data1",
"=",
"material",
".",
"get",
"(",
"'Data1'",
",",
"0",
")",
"self",
".",
"Data2",
"=",
"material",
".",
"get",
"(",
"'Data2'",
",",
"0",
")",
"self",
".",
"Data3",
"=",
"material",
".",
"get",
"(",
"'Data3'",
",",
"0",
")",
"self",
".",
"Data4",
"=",
"material",
".",
"get",
"(",
"\"Data4\"",
",",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"8",
")",
"]",
")",
"self",
".",
"SMPTELabel",
"=",
"d",
".",
"get",
"(",
"\"SMPTELabel\"",
",",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"12",
")",
"]",
")"
] | Set MobID from a dict | [
"Set",
"MobID",
"from",
"a",
"dict"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L280-L296 |
251,278 | markreidvfx/pyaaf2 | aaf2/mobid.py | MobID.to_dict | def to_dict(self):
"""
MobID representation as dict
"""
material = {'Data1': self.Data1,
'Data2': self.Data2,
'Data3': self.Data3,
'Data4': list(self.Data4)
}
return {'material':material,
'length': self.length,
'instanceHigh': self.instanceHigh,
'instanceMid': self.instanceMid,
'instanceLow': self.instanceLow,
'SMPTELabel': list(self.SMPTELabel)
} | python | def to_dict(self):
material = {'Data1': self.Data1,
'Data2': self.Data2,
'Data3': self.Data3,
'Data4': list(self.Data4)
}
return {'material':material,
'length': self.length,
'instanceHigh': self.instanceHigh,
'instanceMid': self.instanceMid,
'instanceLow': self.instanceLow,
'SMPTELabel': list(self.SMPTELabel)
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"material",
"=",
"{",
"'Data1'",
":",
"self",
".",
"Data1",
",",
"'Data2'",
":",
"self",
".",
"Data2",
",",
"'Data3'",
":",
"self",
".",
"Data3",
",",
"'Data4'",
":",
"list",
"(",
"self",
".",
"Data4",
")",
"}",
"return",
"{",
"'material'",
":",
"material",
",",
"'length'",
":",
"self",
".",
"length",
",",
"'instanceHigh'",
":",
"self",
".",
"instanceHigh",
",",
"'instanceMid'",
":",
"self",
".",
"instanceMid",
",",
"'instanceLow'",
":",
"self",
".",
"instanceLow",
",",
"'SMPTELabel'",
":",
"list",
"(",
"self",
".",
"SMPTELabel",
")",
"}"
] | MobID representation as dict | [
"MobID",
"representation",
"as",
"dict"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/mobid.py#L298-L315 |
251,279 | markreidvfx/pyaaf2 | aaf2/ama.py | wave_infochunk | def wave_infochunk(path):
"""
Returns a bytearray of the WAVE RIFF header and fmt
chunk for a `WAVEDescriptor` `Summary`
"""
with open(path,'rb') as file:
if file.read(4) != b"RIFF":
return None
data_size = file.read(4) # container size
if file.read(4) != b"WAVE":
return None
while True:
chunkid = file.read(4)
sizebuf = file.read(4)
if len(sizebuf) < 4 or len(chunkid) < 4:
return None
size = struct.unpack(b'<L', sizebuf )[0]
if chunkid[0:3] != b"fmt":
if size % 2 == 1:
seek = size + 1
else:
seek = size
file.seek(size,1)
else:
return bytearray(b"RIFF" + data_size + b"WAVE" + chunkid + sizebuf + file.read(size)) | python | def wave_infochunk(path):
with open(path,'rb') as file:
if file.read(4) != b"RIFF":
return None
data_size = file.read(4) # container size
if file.read(4) != b"WAVE":
return None
while True:
chunkid = file.read(4)
sizebuf = file.read(4)
if len(sizebuf) < 4 or len(chunkid) < 4:
return None
size = struct.unpack(b'<L', sizebuf )[0]
if chunkid[0:3] != b"fmt":
if size % 2 == 1:
seek = size + 1
else:
seek = size
file.seek(size,1)
else:
return bytearray(b"RIFF" + data_size + b"WAVE" + chunkid + sizebuf + file.read(size)) | [
"def",
"wave_infochunk",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"file",
":",
"if",
"file",
".",
"read",
"(",
"4",
")",
"!=",
"b\"RIFF\"",
":",
"return",
"None",
"data_size",
"=",
"file",
".",
"read",
"(",
"4",
")",
"# container size",
"if",
"file",
".",
"read",
"(",
"4",
")",
"!=",
"b\"WAVE\"",
":",
"return",
"None",
"while",
"True",
":",
"chunkid",
"=",
"file",
".",
"read",
"(",
"4",
")",
"sizebuf",
"=",
"file",
".",
"read",
"(",
"4",
")",
"if",
"len",
"(",
"sizebuf",
")",
"<",
"4",
"or",
"len",
"(",
"chunkid",
")",
"<",
"4",
":",
"return",
"None",
"size",
"=",
"struct",
".",
"unpack",
"(",
"b'<L'",
",",
"sizebuf",
")",
"[",
"0",
"]",
"if",
"chunkid",
"[",
"0",
":",
"3",
"]",
"!=",
"b\"fmt\"",
":",
"if",
"size",
"%",
"2",
"==",
"1",
":",
"seek",
"=",
"size",
"+",
"1",
"else",
":",
"seek",
"=",
"size",
"file",
".",
"seek",
"(",
"size",
",",
"1",
")",
"else",
":",
"return",
"bytearray",
"(",
"b\"RIFF\"",
"+",
"data_size",
"+",
"b\"WAVE\"",
"+",
"chunkid",
"+",
"sizebuf",
"+",
"file",
".",
"read",
"(",
"size",
")",
")"
] | Returns a bytearray of the WAVE RIFF header and fmt
chunk for a `WAVEDescriptor` `Summary` | [
"Returns",
"a",
"bytearray",
"of",
"the",
"WAVE",
"RIFF",
"header",
"and",
"fmt",
"chunk",
"for",
"a",
"WAVEDescriptor",
"Summary"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/ama.py#L329-L353 |
251,280 | markreidvfx/pyaaf2 | aaf2/cfb.py | DirEntry.pop | def pop(self):
"""
remove self from binary search tree
"""
entry = self
parent = self.parent
root = parent.child()
dir_per_sector = self.storage.sector_size // 128
max_dirs_entries = self.storage.dir_sector_count * dir_per_sector
count = 0
if root.dir_id == entry.dir_id:
parent.child_id = None
else:
# find dir entry pointing to self
while True:
if count > max_dirs_entries:
raise CompoundFileBinaryError("max dir entries limit reached")
if entry < root:
if root.left_id == entry.dir_id:
root.left_id = None
break
root = root.left()
else:
if root.right_id == entry.dir_id:
# root right is pointing to self
root.right_id = None
break
root = root.right()
count += 1
left = entry.left()
right = entry.right()
# clear from cache
if parent.dir_id in self.storage.children_cache:
del self.storage.children_cache[parent.dir_id][entry.name]
if left:
del self.storage.children_cache[parent.dir_id][left.name]
if right:
del self.storage.children_cache[parent.dir_id][right.name]
if left is not None:
parent.add_child(left)
if right is not None:
parent.add_child(right)
# clear parent and left and right
self.left_id = None
self.right_id = None
self.parent = None | python | def pop(self):
entry = self
parent = self.parent
root = parent.child()
dir_per_sector = self.storage.sector_size // 128
max_dirs_entries = self.storage.dir_sector_count * dir_per_sector
count = 0
if root.dir_id == entry.dir_id:
parent.child_id = None
else:
# find dir entry pointing to self
while True:
if count > max_dirs_entries:
raise CompoundFileBinaryError("max dir entries limit reached")
if entry < root:
if root.left_id == entry.dir_id:
root.left_id = None
break
root = root.left()
else:
if root.right_id == entry.dir_id:
# root right is pointing to self
root.right_id = None
break
root = root.right()
count += 1
left = entry.left()
right = entry.right()
# clear from cache
if parent.dir_id in self.storage.children_cache:
del self.storage.children_cache[parent.dir_id][entry.name]
if left:
del self.storage.children_cache[parent.dir_id][left.name]
if right:
del self.storage.children_cache[parent.dir_id][right.name]
if left is not None:
parent.add_child(left)
if right is not None:
parent.add_child(right)
# clear parent and left and right
self.left_id = None
self.right_id = None
self.parent = None | [
"def",
"pop",
"(",
"self",
")",
":",
"entry",
"=",
"self",
"parent",
"=",
"self",
".",
"parent",
"root",
"=",
"parent",
".",
"child",
"(",
")",
"dir_per_sector",
"=",
"self",
".",
"storage",
".",
"sector_size",
"//",
"128",
"max_dirs_entries",
"=",
"self",
".",
"storage",
".",
"dir_sector_count",
"*",
"dir_per_sector",
"count",
"=",
"0",
"if",
"root",
".",
"dir_id",
"==",
"entry",
".",
"dir_id",
":",
"parent",
".",
"child_id",
"=",
"None",
"else",
":",
"# find dir entry pointing to self",
"while",
"True",
":",
"if",
"count",
">",
"max_dirs_entries",
":",
"raise",
"CompoundFileBinaryError",
"(",
"\"max dir entries limit reached\"",
")",
"if",
"entry",
"<",
"root",
":",
"if",
"root",
".",
"left_id",
"==",
"entry",
".",
"dir_id",
":",
"root",
".",
"left_id",
"=",
"None",
"break",
"root",
"=",
"root",
".",
"left",
"(",
")",
"else",
":",
"if",
"root",
".",
"right_id",
"==",
"entry",
".",
"dir_id",
":",
"# root right is pointing to self",
"root",
".",
"right_id",
"=",
"None",
"break",
"root",
"=",
"root",
".",
"right",
"(",
")",
"count",
"+=",
"1",
"left",
"=",
"entry",
".",
"left",
"(",
")",
"right",
"=",
"entry",
".",
"right",
"(",
")",
"# clear from cache",
"if",
"parent",
".",
"dir_id",
"in",
"self",
".",
"storage",
".",
"children_cache",
":",
"del",
"self",
".",
"storage",
".",
"children_cache",
"[",
"parent",
".",
"dir_id",
"]",
"[",
"entry",
".",
"name",
"]",
"if",
"left",
":",
"del",
"self",
".",
"storage",
".",
"children_cache",
"[",
"parent",
".",
"dir_id",
"]",
"[",
"left",
".",
"name",
"]",
"if",
"right",
":",
"del",
"self",
".",
"storage",
".",
"children_cache",
"[",
"parent",
".",
"dir_id",
"]",
"[",
"right",
".",
"name",
"]",
"if",
"left",
"is",
"not",
"None",
":",
"parent",
".",
"add_child",
"(",
"left",
")",
"if",
"right",
"is",
"not",
"None",
":",
"parent",
".",
"add_child",
"(",
"right",
")",
"# clear parent and left and right",
"self",
".",
"left_id",
"=",
"None",
"self",
".",
"right_id",
"=",
"None",
"self",
".",
"parent",
"=",
"None"
] | remove self from binary search tree | [
"remove",
"self",
"from",
"binary",
"search",
"tree"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L609-L664 |
251,281 | markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.remove | def remove(self, path):
"""
Removes both streams and storage DirEntry types from file.
storage type entries need to be empty dirs.
"""
entry = self.find(path)
if not entry:
raise ValueError("%s does not exists" % path)
if entry.type == 'root storage':
raise ValueError("can no remove root entry")
if entry.type == "storage" and not entry.child_id is None:
raise ValueError("storage contains children")
entry.pop()
# remove stream data
if entry.type == "stream":
self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)
self.free_dir_entry(entry) | python | def remove(self, path):
entry = self.find(path)
if not entry:
raise ValueError("%s does not exists" % path)
if entry.type == 'root storage':
raise ValueError("can no remove root entry")
if entry.type == "storage" and not entry.child_id is None:
raise ValueError("storage contains children")
entry.pop()
# remove stream data
if entry.type == "stream":
self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)
self.free_dir_entry(entry) | [
"def",
"remove",
"(",
"self",
",",
"path",
")",
":",
"entry",
"=",
"self",
".",
"find",
"(",
"path",
")",
"if",
"not",
"entry",
":",
"raise",
"ValueError",
"(",
"\"%s does not exists\"",
"%",
"path",
")",
"if",
"entry",
".",
"type",
"==",
"'root storage'",
":",
"raise",
"ValueError",
"(",
"\"can no remove root entry\"",
")",
"if",
"entry",
".",
"type",
"==",
"\"storage\"",
"and",
"not",
"entry",
".",
"child_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"storage contains children\"",
")",
"entry",
".",
"pop",
"(",
")",
"# remove stream data",
"if",
"entry",
".",
"type",
"==",
"\"stream\"",
":",
"self",
".",
"free_fat_chain",
"(",
"entry",
".",
"sector_id",
",",
"entry",
".",
"byte_size",
"<",
"self",
".",
"min_stream_max_size",
")",
"self",
".",
"free_dir_entry",
"(",
"entry",
")"
] | Removes both streams and storage DirEntry types from file.
storage type entries need to be empty dirs. | [
"Removes",
"both",
"streams",
"and",
"storage",
"DirEntry",
"types",
"from",
"file",
".",
"storage",
"type",
"entries",
"need",
"to",
"be",
"empty",
"dirs",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1606-L1629 |
251,282 | markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.rmtree | def rmtree(self, path):
"""
Removes directory structure, similar to shutil.rmtree.
"""
for root, storage, streams in self.walk(path, topdown=False):
for item in streams:
self.free_fat_chain(item.sector_id, item.byte_size < self.min_stream_max_size)
self.free_dir_entry(item)
for item in storage:
self.free_dir_entry(item)
root.child_id = None
# remove root item
self.remove(path) | python | def rmtree(self, path):
for root, storage, streams in self.walk(path, topdown=False):
for item in streams:
self.free_fat_chain(item.sector_id, item.byte_size < self.min_stream_max_size)
self.free_dir_entry(item)
for item in storage:
self.free_dir_entry(item)
root.child_id = None
# remove root item
self.remove(path) | [
"def",
"rmtree",
"(",
"self",
",",
"path",
")",
":",
"for",
"root",
",",
"storage",
",",
"streams",
"in",
"self",
".",
"walk",
"(",
"path",
",",
"topdown",
"=",
"False",
")",
":",
"for",
"item",
"in",
"streams",
":",
"self",
".",
"free_fat_chain",
"(",
"item",
".",
"sector_id",
",",
"item",
".",
"byte_size",
"<",
"self",
".",
"min_stream_max_size",
")",
"self",
".",
"free_dir_entry",
"(",
"item",
")",
"for",
"item",
"in",
"storage",
":",
"self",
".",
"free_dir_entry",
"(",
"item",
")",
"root",
".",
"child_id",
"=",
"None",
"# remove root item",
"self",
".",
"remove",
"(",
"path",
")"
] | Removes directory structure, similar to shutil.rmtree. | [
"Removes",
"directory",
"structure",
"similar",
"to",
"shutil",
".",
"rmtree",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1632-L1648 |
251,283 | markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.listdir_dict | def listdir_dict(self, path = None):
"""
Return a dict containing the ``DirEntry`` objects in the directory
given by path with name of the dir as key.
"""
if path is None:
path = self.root
root = self.find(path)
if root is None:
raise ValueError("unable to find dir: %s" % str(path))
if not root.isdir():
raise ValueError("can only list storage types")
children = self.children_cache.get(root.dir_id, None)
if children is not None:
return children
child = root.child()
result = {}
if not child:
self.children_cache[root.dir_id] = result
return result
dir_per_sector = self.sector_size // 128
max_dirs_entries = self.dir_sector_count * dir_per_sector
stack = deque([child])
count = 0
while stack:
current = stack.pop()
result[current.name] = current
count += 1
if count > max_dirs_entries:
raise CompoundFileBinaryError("corrupt folder structure")
left = current.left()
if left:
stack.append(left)
right = current.right()
if right:
stack.append(right)
self.children_cache[root.dir_id] = result
return result | python | def listdir_dict(self, path = None):
if path is None:
path = self.root
root = self.find(path)
if root is None:
raise ValueError("unable to find dir: %s" % str(path))
if not root.isdir():
raise ValueError("can only list storage types")
children = self.children_cache.get(root.dir_id, None)
if children is not None:
return children
child = root.child()
result = {}
if not child:
self.children_cache[root.dir_id] = result
return result
dir_per_sector = self.sector_size // 128
max_dirs_entries = self.dir_sector_count * dir_per_sector
stack = deque([child])
count = 0
while stack:
current = stack.pop()
result[current.name] = current
count += 1
if count > max_dirs_entries:
raise CompoundFileBinaryError("corrupt folder structure")
left = current.left()
if left:
stack.append(left)
right = current.right()
if right:
stack.append(right)
self.children_cache[root.dir_id] = result
return result | [
"def",
"listdir_dict",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"root",
"root",
"=",
"self",
".",
"find",
"(",
"path",
")",
"if",
"root",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"unable to find dir: %s\"",
"%",
"str",
"(",
"path",
")",
")",
"if",
"not",
"root",
".",
"isdir",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"can only list storage types\"",
")",
"children",
"=",
"self",
".",
"children_cache",
".",
"get",
"(",
"root",
".",
"dir_id",
",",
"None",
")",
"if",
"children",
"is",
"not",
"None",
":",
"return",
"children",
"child",
"=",
"root",
".",
"child",
"(",
")",
"result",
"=",
"{",
"}",
"if",
"not",
"child",
":",
"self",
".",
"children_cache",
"[",
"root",
".",
"dir_id",
"]",
"=",
"result",
"return",
"result",
"dir_per_sector",
"=",
"self",
".",
"sector_size",
"//",
"128",
"max_dirs_entries",
"=",
"self",
".",
"dir_sector_count",
"*",
"dir_per_sector",
"stack",
"=",
"deque",
"(",
"[",
"child",
"]",
")",
"count",
"=",
"0",
"while",
"stack",
":",
"current",
"=",
"stack",
".",
"pop",
"(",
")",
"result",
"[",
"current",
".",
"name",
"]",
"=",
"current",
"count",
"+=",
"1",
"if",
"count",
">",
"max_dirs_entries",
":",
"raise",
"CompoundFileBinaryError",
"(",
"\"corrupt folder structure\"",
")",
"left",
"=",
"current",
".",
"left",
"(",
")",
"if",
"left",
":",
"stack",
".",
"append",
"(",
"left",
")",
"right",
"=",
"current",
".",
"right",
"(",
")",
"if",
"right",
":",
"stack",
".",
"append",
"(",
"right",
")",
"self",
".",
"children_cache",
"[",
"root",
".",
"dir_id",
"]",
"=",
"result",
"return",
"result"
] | Return a dict containing the ``DirEntry`` objects in the directory
given by path with name of the dir as key. | [
"Return",
"a",
"dict",
"containing",
"the",
"DirEntry",
"objects",
"in",
"the",
"directory",
"given",
"by",
"path",
"with",
"name",
"of",
"the",
"dir",
"as",
"key",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1660-L1709 |
251,284 | markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.makedir | def makedir(self, path, class_id=None):
"""
Create a storage DirEntry name path
"""
return self.create_dir_entry(path, dir_type='storage', class_id=class_id) | python | def makedir(self, path, class_id=None):
return self.create_dir_entry(path, dir_type='storage', class_id=class_id) | [
"def",
"makedir",
"(",
"self",
",",
"path",
",",
"class_id",
"=",
"None",
")",
":",
"return",
"self",
".",
"create_dir_entry",
"(",
"path",
",",
"dir_type",
"=",
"'storage'",
",",
"class_id",
"=",
"class_id",
")"
] | Create a storage DirEntry name path | [
"Create",
"a",
"storage",
"DirEntry",
"name",
"path"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1800-L1804 |
251,285 | markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.makedirs | def makedirs(self, path):
"""
Recursive storage DirEntry creation function.
"""
root = ""
assert path.startswith('/')
p = path.strip('/')
for item in p.split('/'):
root += "/" + item
if not self.exists(root):
self.makedir(root)
return self.find(path) | python | def makedirs(self, path):
root = ""
assert path.startswith('/')
p = path.strip('/')
for item in p.split('/'):
root += "/" + item
if not self.exists(root):
self.makedir(root)
return self.find(path) | [
"def",
"makedirs",
"(",
"self",
",",
"path",
")",
":",
"root",
"=",
"\"\"",
"assert",
"path",
".",
"startswith",
"(",
"'/'",
")",
"p",
"=",
"path",
".",
"strip",
"(",
"'/'",
")",
"for",
"item",
"in",
"p",
".",
"split",
"(",
"'/'",
")",
":",
"root",
"+=",
"\"/\"",
"+",
"item",
"if",
"not",
"self",
".",
"exists",
"(",
"root",
")",
":",
"self",
".",
"makedir",
"(",
"root",
")",
"return",
"self",
".",
"find",
"(",
"path",
")"
] | Recursive storage DirEntry creation function. | [
"Recursive",
"storage",
"DirEntry",
"creation",
"function",
"."
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1806-L1819 |
251,286 | markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.move | def move(self, src, dst):
"""
Moves ``DirEntry`` from src to dst
"""
src_entry = self.find(src)
if src_entry is None:
raise ValueError("src path does not exist: %s" % src)
if dst.endswith('/'):
dst += src_entry.name
if self.exists(dst):
raise ValueError("dst path already exist: %s" % dst)
if dst == '/' or src == '/':
raise ValueError("cannot overwrite root dir")
split_path = dst.strip('/').split('/')
dst_basename = split_path[-1]
dst_dirname = '/' + '/'.join(split_path[:-1])
# print(dst)
# print(dst_basename, dst_dirname)
dst_entry = self.find(dst_dirname)
if dst_entry is None:
raise ValueError("src path does not exist: %s" % dst_dirname)
if not dst_entry.isdir():
raise ValueError("dst dirname cannot be stream: %s" % dst_dirname)
# src_entry.parent.remove_child(src_entry)
src_entry.pop()
src_entry.parent = None
src_entry.name = dst_basename
dst_entry.add_child(src_entry)
self.children_cache[dst_entry.dir_id][src_entry.name] = src_entry
return src_entry | python | def move(self, src, dst):
src_entry = self.find(src)
if src_entry is None:
raise ValueError("src path does not exist: %s" % src)
if dst.endswith('/'):
dst += src_entry.name
if self.exists(dst):
raise ValueError("dst path already exist: %s" % dst)
if dst == '/' or src == '/':
raise ValueError("cannot overwrite root dir")
split_path = dst.strip('/').split('/')
dst_basename = split_path[-1]
dst_dirname = '/' + '/'.join(split_path[:-1])
# print(dst)
# print(dst_basename, dst_dirname)
dst_entry = self.find(dst_dirname)
if dst_entry is None:
raise ValueError("src path does not exist: %s" % dst_dirname)
if not dst_entry.isdir():
raise ValueError("dst dirname cannot be stream: %s" % dst_dirname)
# src_entry.parent.remove_child(src_entry)
src_entry.pop()
src_entry.parent = None
src_entry.name = dst_basename
dst_entry.add_child(src_entry)
self.children_cache[dst_entry.dir_id][src_entry.name] = src_entry
return src_entry | [
"def",
"move",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"src_entry",
"=",
"self",
".",
"find",
"(",
"src",
")",
"if",
"src_entry",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"src path does not exist: %s\"",
"%",
"src",
")",
"if",
"dst",
".",
"endswith",
"(",
"'/'",
")",
":",
"dst",
"+=",
"src_entry",
".",
"name",
"if",
"self",
".",
"exists",
"(",
"dst",
")",
":",
"raise",
"ValueError",
"(",
"\"dst path already exist: %s\"",
"%",
"dst",
")",
"if",
"dst",
"==",
"'/'",
"or",
"src",
"==",
"'/'",
":",
"raise",
"ValueError",
"(",
"\"cannot overwrite root dir\"",
")",
"split_path",
"=",
"dst",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"dst_basename",
"=",
"split_path",
"[",
"-",
"1",
"]",
"dst_dirname",
"=",
"'/'",
"+",
"'/'",
".",
"join",
"(",
"split_path",
"[",
":",
"-",
"1",
"]",
")",
"# print(dst)",
"# print(dst_basename, dst_dirname)",
"dst_entry",
"=",
"self",
".",
"find",
"(",
"dst_dirname",
")",
"if",
"dst_entry",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"src path does not exist: %s\"",
"%",
"dst_dirname",
")",
"if",
"not",
"dst_entry",
".",
"isdir",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"dst dirname cannot be stream: %s\"",
"%",
"dst_dirname",
")",
"# src_entry.parent.remove_child(src_entry)",
"src_entry",
".",
"pop",
"(",
")",
"src_entry",
".",
"parent",
"=",
"None",
"src_entry",
".",
"name",
"=",
"dst_basename",
"dst_entry",
".",
"add_child",
"(",
"src_entry",
")",
"self",
".",
"children_cache",
"[",
"dst_entry",
".",
"dir_id",
"]",
"[",
"src_entry",
".",
"name",
"]",
"=",
"src_entry",
"return",
"src_entry"
] | Moves ``DirEntry`` from src to dst | [
"Moves",
"DirEntry",
"from",
"src",
"to",
"dst"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1821-L1862 |
251,287 | markreidvfx/pyaaf2 | aaf2/cfb.py | CompoundFileBinary.open | def open(self, path, mode='r'):
"""Open stream, returning ``Stream`` object"""
entry = self.find(path)
if entry is None:
if mode == 'r':
raise ValueError("stream does not exists: %s" % path)
entry = self.create_dir_entry(path, 'stream', None)
else:
if not entry.isfile():
raise ValueError("can only open stream type DirEntry's")
if mode == 'w':
logging.debug("stream: %s exists, overwriting" % path)
self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)
entry.sector_id = None
entry.byte_size = 0
entry.class_id = None
elif mode == 'rw':
pass
s = Stream(self, entry, mode)
return s | python | def open(self, path, mode='r'):
entry = self.find(path)
if entry is None:
if mode == 'r':
raise ValueError("stream does not exists: %s" % path)
entry = self.create_dir_entry(path, 'stream', None)
else:
if not entry.isfile():
raise ValueError("can only open stream type DirEntry's")
if mode == 'w':
logging.debug("stream: %s exists, overwriting" % path)
self.free_fat_chain(entry.sector_id, entry.byte_size < self.min_stream_max_size)
entry.sector_id = None
entry.byte_size = 0
entry.class_id = None
elif mode == 'rw':
pass
s = Stream(self, entry, mode)
return s | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"'r'",
")",
":",
"entry",
"=",
"self",
".",
"find",
"(",
"path",
")",
"if",
"entry",
"is",
"None",
":",
"if",
"mode",
"==",
"'r'",
":",
"raise",
"ValueError",
"(",
"\"stream does not exists: %s\"",
"%",
"path",
")",
"entry",
"=",
"self",
".",
"create_dir_entry",
"(",
"path",
",",
"'stream'",
",",
"None",
")",
"else",
":",
"if",
"not",
"entry",
".",
"isfile",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"can only open stream type DirEntry's\"",
")",
"if",
"mode",
"==",
"'w'",
":",
"logging",
".",
"debug",
"(",
"\"stream: %s exists, overwriting\"",
"%",
"path",
")",
"self",
".",
"free_fat_chain",
"(",
"entry",
".",
"sector_id",
",",
"entry",
".",
"byte_size",
"<",
"self",
".",
"min_stream_max_size",
")",
"entry",
".",
"sector_id",
"=",
"None",
"entry",
".",
"byte_size",
"=",
"0",
"entry",
".",
"class_id",
"=",
"None",
"elif",
"mode",
"==",
"'rw'",
":",
"pass",
"s",
"=",
"Stream",
"(",
"self",
",",
"entry",
",",
"mode",
")",
"return",
"s"
] | Open stream, returning ``Stream`` object | [
"Open",
"stream",
"returning",
"Stream",
"object"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/cfb.py#L1864-L1887 |
251,288 | markreidvfx/pyaaf2 | aaf2/properties.py | add2set | def add2set(self, pid, key, value):
"""low level add to StrongRefSetProperty"""
prop = self.property_entries[pid]
current = prop.objects.get(key, None)
current_local_key = prop.references.get(key, None)
if current and current is not value:
current.detach()
if current_local_key is None:
prop.references[key] = prop.next_free_key
prop.next_free_key += 1
prop.objects[key] = value
if prop.parent.dir:
ref = prop.index_ref_name(key)
dir_entry = prop.parent.dir.get(ref)
if dir_entry is None:
dir_entry = prop.parent.dir.makedir(ref)
if value.dir != dir_entry:
value.attach(dir_entry)
prop.mark_modified() | python | def add2set(self, pid, key, value):
prop = self.property_entries[pid]
current = prop.objects.get(key, None)
current_local_key = prop.references.get(key, None)
if current and current is not value:
current.detach()
if current_local_key is None:
prop.references[key] = prop.next_free_key
prop.next_free_key += 1
prop.objects[key] = value
if prop.parent.dir:
ref = prop.index_ref_name(key)
dir_entry = prop.parent.dir.get(ref)
if dir_entry is None:
dir_entry = prop.parent.dir.makedir(ref)
if value.dir != dir_entry:
value.attach(dir_entry)
prop.mark_modified() | [
"def",
"add2set",
"(",
"self",
",",
"pid",
",",
"key",
",",
"value",
")",
":",
"prop",
"=",
"self",
".",
"property_entries",
"[",
"pid",
"]",
"current",
"=",
"prop",
".",
"objects",
".",
"get",
"(",
"key",
",",
"None",
")",
"current_local_key",
"=",
"prop",
".",
"references",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"current",
"and",
"current",
"is",
"not",
"value",
":",
"current",
".",
"detach",
"(",
")",
"if",
"current_local_key",
"is",
"None",
":",
"prop",
".",
"references",
"[",
"key",
"]",
"=",
"prop",
".",
"next_free_key",
"prop",
".",
"next_free_key",
"+=",
"1",
"prop",
".",
"objects",
"[",
"key",
"]",
"=",
"value",
"if",
"prop",
".",
"parent",
".",
"dir",
":",
"ref",
"=",
"prop",
".",
"index_ref_name",
"(",
"key",
")",
"dir_entry",
"=",
"prop",
".",
"parent",
".",
"dir",
".",
"get",
"(",
"ref",
")",
"if",
"dir_entry",
"is",
"None",
":",
"dir_entry",
"=",
"prop",
".",
"parent",
".",
"dir",
".",
"makedir",
"(",
"ref",
")",
"if",
"value",
".",
"dir",
"!=",
"dir_entry",
":",
"value",
".",
"attach",
"(",
"dir_entry",
")",
"prop",
".",
"mark_modified",
"(",
")"
] | low level add to StrongRefSetProperty | [
"low",
"level",
"add",
"to",
"StrongRefSetProperty"
] | 37de8c10d3c3495cc00c705eb6c5048bc4a7e51f | https://github.com/markreidvfx/pyaaf2/blob/37de8c10d3c3495cc00c705eb6c5048bc4a7e51f/aaf2/properties.py#L1313-L1336 |
251,289 | MillionIntegrals/vel | vel/rl/modules/q_distributional_head.py | QDistributionalHead.histogram_info | def histogram_info(self) -> dict:
""" Return extra information about histogram """
return {
'support_atoms': self.support_atoms,
'atom_delta': self.atom_delta,
'vmin': self.vmin,
'vmax': self.vmax,
'num_atoms': self.atoms
} | python | def histogram_info(self) -> dict:
return {
'support_atoms': self.support_atoms,
'atom_delta': self.atom_delta,
'vmin': self.vmin,
'vmax': self.vmax,
'num_atoms': self.atoms
} | [
"def",
"histogram_info",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"'support_atoms'",
":",
"self",
".",
"support_atoms",
",",
"'atom_delta'",
":",
"self",
".",
"atom_delta",
",",
"'vmin'",
":",
"self",
".",
"vmin",
",",
"'vmax'",
":",
"self",
".",
"vmax",
",",
"'num_atoms'",
":",
"self",
".",
"atoms",
"}"
] | Return extra information about histogram | [
"Return",
"extra",
"information",
"about",
"histogram"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/q_distributional_head.py#L31-L39 |
251,290 | MillionIntegrals/vel | vel/rl/modules/q_distributional_head.py | QDistributionalHead.sample | def sample(self, histogram_logits):
""" Sample from a greedy strategy with given q-value histogram """
histogram_probs = histogram_logits.exp() # Batch size * actions * atoms
atoms = self.support_atoms.view(1, 1, self.atoms) # Need to introduce two new dimensions
return (histogram_probs * atoms).sum(dim=-1).argmax(dim=1) | python | def sample(self, histogram_logits):
histogram_probs = histogram_logits.exp() # Batch size * actions * atoms
atoms = self.support_atoms.view(1, 1, self.atoms) # Need to introduce two new dimensions
return (histogram_probs * atoms).sum(dim=-1).argmax(dim=1) | [
"def",
"sample",
"(",
"self",
",",
"histogram_logits",
")",
":",
"histogram_probs",
"=",
"histogram_logits",
".",
"exp",
"(",
")",
"# Batch size * actions * atoms",
"atoms",
"=",
"self",
".",
"support_atoms",
".",
"view",
"(",
"1",
",",
"1",
",",
"self",
".",
"atoms",
")",
"# Need to introduce two new dimensions",
"return",
"(",
"histogram_probs",
"*",
"atoms",
")",
".",
"sum",
"(",
"dim",
"=",
"-",
"1",
")",
".",
"argmax",
"(",
"dim",
"=",
"1",
")"
] | Sample from a greedy strategy with given q-value histogram | [
"Sample",
"from",
"a",
"greedy",
"strategy",
"with",
"given",
"q",
"-",
"value",
"histogram"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/q_distributional_head.py#L52-L56 |
251,291 | MillionIntegrals/vel | vel/sources/nlp/text_url.py | TextUrlSource.download | def download(self):
""" Make sure data file is downloaded and stored properly """
if not os.path.exists(self.data_path):
# Create if it doesn't exist
pathlib.Path(self.data_path).mkdir(parents=True, exist_ok=True)
if not os.path.exists(self.text_path):
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
with open(self.text_path, 'wt') as fp:
request = http.request('GET', self.url)
content = request.data.decode('utf8')
fp.write(content)
if not os.path.exists(self.processed_path):
with open(self.text_path, 'rt') as fp:
content = fp.read()
alphabet = sorted(set(content))
index_to_character = {idx: c for idx, c in enumerate(alphabet, 1)}
character_to_index = {c: idx for idx, c in enumerate(alphabet, 1)}
content_encoded = np.array([character_to_index[c] for c in content], dtype=np.uint8)
data_dict = {
'alphabet': alphabet,
'index_to_character': index_to_character,
'character_to_index': character_to_index,
'content_encoded': content_encoded
}
with open(self.processed_path, 'wb') as fp:
torch.save(data_dict, fp)
else:
with open(self.processed_path, 'rb') as fp:
data_dict = torch.load(fp)
return data_dict | python | def download(self):
if not os.path.exists(self.data_path):
# Create if it doesn't exist
pathlib.Path(self.data_path).mkdir(parents=True, exist_ok=True)
if not os.path.exists(self.text_path):
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
with open(self.text_path, 'wt') as fp:
request = http.request('GET', self.url)
content = request.data.decode('utf8')
fp.write(content)
if not os.path.exists(self.processed_path):
with open(self.text_path, 'rt') as fp:
content = fp.read()
alphabet = sorted(set(content))
index_to_character = {idx: c for idx, c in enumerate(alphabet, 1)}
character_to_index = {c: idx for idx, c in enumerate(alphabet, 1)}
content_encoded = np.array([character_to_index[c] for c in content], dtype=np.uint8)
data_dict = {
'alphabet': alphabet,
'index_to_character': index_to_character,
'character_to_index': character_to_index,
'content_encoded': content_encoded
}
with open(self.processed_path, 'wb') as fp:
torch.save(data_dict, fp)
else:
with open(self.processed_path, 'rb') as fp:
data_dict = torch.load(fp)
return data_dict | [
"def",
"download",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"data_path",
")",
":",
"# Create if it doesn't exist",
"pathlib",
".",
"Path",
"(",
"self",
".",
"data_path",
")",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"text_path",
")",
":",
"http",
"=",
"urllib3",
".",
"PoolManager",
"(",
"cert_reqs",
"=",
"'CERT_REQUIRED'",
",",
"ca_certs",
"=",
"certifi",
".",
"where",
"(",
")",
")",
"with",
"open",
"(",
"self",
".",
"text_path",
",",
"'wt'",
")",
"as",
"fp",
":",
"request",
"=",
"http",
".",
"request",
"(",
"'GET'",
",",
"self",
".",
"url",
")",
"content",
"=",
"request",
".",
"data",
".",
"decode",
"(",
"'utf8'",
")",
"fp",
".",
"write",
"(",
"content",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"processed_path",
")",
":",
"with",
"open",
"(",
"self",
".",
"text_path",
",",
"'rt'",
")",
"as",
"fp",
":",
"content",
"=",
"fp",
".",
"read",
"(",
")",
"alphabet",
"=",
"sorted",
"(",
"set",
"(",
"content",
")",
")",
"index_to_character",
"=",
"{",
"idx",
":",
"c",
"for",
"idx",
",",
"c",
"in",
"enumerate",
"(",
"alphabet",
",",
"1",
")",
"}",
"character_to_index",
"=",
"{",
"c",
":",
"idx",
"for",
"idx",
",",
"c",
"in",
"enumerate",
"(",
"alphabet",
",",
"1",
")",
"}",
"content_encoded",
"=",
"np",
".",
"array",
"(",
"[",
"character_to_index",
"[",
"c",
"]",
"for",
"c",
"in",
"content",
"]",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"data_dict",
"=",
"{",
"'alphabet'",
":",
"alphabet",
",",
"'index_to_character'",
":",
"index_to_character",
",",
"'character_to_index'",
":",
"character_to_index",
",",
"'content_encoded'",
":",
"content_encoded",
"}",
"with",
"open",
"(",
"self",
".",
"processed_path",
",",
"'wb'",
")",
"as",
"fp",
":",
"torch",
".",
"save",
"(",
"data_dict",
",",
"fp",
")",
"else",
":",
"with",
"open",
"(",
"self",
".",
"processed_path",
",",
"'rb'",
")",
"as",
"fp",
":",
"data_dict",
"=",
"torch",
".",
"load",
"(",
"fp",
")",
"return",
"data_dict"
] | Make sure data file is downloaded and stored properly | [
"Make",
"sure",
"data",
"file",
"is",
"downloaded",
"and",
"stored",
"properly"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/nlp/text_url.py#L148-L186 |
251,292 | MillionIntegrals/vel | vel/math/functions.py | explained_variance | def explained_variance(returns, values):
""" Calculate how much variance in returns do the values explain """
exp_var = 1 - torch.var(returns - values) / torch.var(returns)
return exp_var.item() | python | def explained_variance(returns, values):
exp_var = 1 - torch.var(returns - values) / torch.var(returns)
return exp_var.item() | [
"def",
"explained_variance",
"(",
"returns",
",",
"values",
")",
":",
"exp_var",
"=",
"1",
"-",
"torch",
".",
"var",
"(",
"returns",
"-",
"values",
")",
"/",
"torch",
".",
"var",
"(",
"returns",
")",
"return",
"exp_var",
".",
"item",
"(",
")"
] | Calculate how much variance in returns do the values explain | [
"Calculate",
"how",
"much",
"variance",
"in",
"returns",
"do",
"the",
"values",
"explain"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/math/functions.py#L4-L7 |
251,293 | MillionIntegrals/vel | vel/sources/img_dir_source.py | create | def create(model_config, path, num_workers, batch_size, augmentations=None, tta=None):
""" Create an ImageDirSource with supplied arguments """
if not os.path.isabs(path):
path = model_config.project_top_dir(path)
train_path = os.path.join(path, 'train')
valid_path = os.path.join(path, 'valid')
train_ds = ImageDirSource(train_path)
val_ds = ImageDirSource(valid_path)
return TrainingData(
train_ds,
val_ds,
num_workers=num_workers,
batch_size=batch_size,
augmentations=augmentations,
# test_time_augmentation=tta
) | python | def create(model_config, path, num_workers, batch_size, augmentations=None, tta=None):
if not os.path.isabs(path):
path = model_config.project_top_dir(path)
train_path = os.path.join(path, 'train')
valid_path = os.path.join(path, 'valid')
train_ds = ImageDirSource(train_path)
val_ds = ImageDirSource(valid_path)
return TrainingData(
train_ds,
val_ds,
num_workers=num_workers,
batch_size=batch_size,
augmentations=augmentations,
# test_time_augmentation=tta
) | [
"def",
"create",
"(",
"model_config",
",",
"path",
",",
"num_workers",
",",
"batch_size",
",",
"augmentations",
"=",
"None",
",",
"tta",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"path",
"=",
"model_config",
".",
"project_top_dir",
"(",
"path",
")",
"train_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'train'",
")",
"valid_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'valid'",
")",
"train_ds",
"=",
"ImageDirSource",
"(",
"train_path",
")",
"val_ds",
"=",
"ImageDirSource",
"(",
"valid_path",
")",
"return",
"TrainingData",
"(",
"train_ds",
",",
"val_ds",
",",
"num_workers",
"=",
"num_workers",
",",
"batch_size",
"=",
"batch_size",
",",
"augmentations",
"=",
"augmentations",
",",
"# test_time_augmentation=tta",
")"
] | Create an ImageDirSource with supplied arguments | [
"Create",
"an",
"ImageDirSource",
"with",
"supplied",
"arguments"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/img_dir_source.py#L12-L30 |
251,294 | MillionIntegrals/vel | vel/rl/models/q_model.py | QModel.reset_weights | def reset_weights(self):
""" Initialize weights to reasonable defaults """
self.input_block.reset_weights()
self.backbone.reset_weights()
self.q_head.reset_weights() | python | def reset_weights(self):
self.input_block.reset_weights()
self.backbone.reset_weights()
self.q_head.reset_weights() | [
"def",
"reset_weights",
"(",
"self",
")",
":",
"self",
".",
"input_block",
".",
"reset_weights",
"(",
")",
"self",
".",
"backbone",
".",
"reset_weights",
"(",
")",
"self",
".",
"q_head",
".",
"reset_weights",
"(",
")"
] | Initialize weights to reasonable defaults | [
"Initialize",
"weights",
"to",
"reasonable",
"defaults"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/models/q_model.py#L50-L54 |
251,295 | MillionIntegrals/vel | vel/util/tensor_accumulator.py | TensorAccumulator.result | def result(self):
""" Concatenate accumulated tensors """
return {k: torch.stack(v) for k, v in self.accumulants.items()} | python | def result(self):
return {k: torch.stack(v) for k, v in self.accumulants.items()} | [
"def",
"result",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"torch",
".",
"stack",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"accumulants",
".",
"items",
"(",
")",
"}"
] | Concatenate accumulated tensors | [
"Concatenate",
"accumulated",
"tensors"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/tensor_accumulator.py#L14-L16 |
251,296 | MillionIntegrals/vel | vel/internals/provider.py | Provider.resolve_parameters | def resolve_parameters(self, func, extra_env=None):
""" Resolve parameter dictionary for the supplied function """
parameter_list = [
(k, v.default == inspect.Parameter.empty) for k, v in inspect.signature(func).parameters.items()
]
extra_env = extra_env if extra_env is not None else {}
kwargs = {}
for parameter_name, is_required in parameter_list:
# extra_env is a 'local' object data defined in-place
if parameter_name in extra_env:
kwargs[parameter_name] = self.instantiate_from_data(extra_env[parameter_name])
continue
if parameter_name in self.instances:
kwargs[parameter_name] = self.instances[parameter_name]
continue
if parameter_name in self.environment:
kwargs[parameter_name] = self.instantiate_by_name(parameter_name)
continue
if is_required:
funcname = f"{inspect.getmodule(func).__name__}.{func.__name__}"
raise RuntimeError("Required argument '{}' cannot be resolved for function '{}'".format(
parameter_name, funcname
))
return kwargs | python | def resolve_parameters(self, func, extra_env=None):
parameter_list = [
(k, v.default == inspect.Parameter.empty) for k, v in inspect.signature(func).parameters.items()
]
extra_env = extra_env if extra_env is not None else {}
kwargs = {}
for parameter_name, is_required in parameter_list:
# extra_env is a 'local' object data defined in-place
if parameter_name in extra_env:
kwargs[parameter_name] = self.instantiate_from_data(extra_env[parameter_name])
continue
if parameter_name in self.instances:
kwargs[parameter_name] = self.instances[parameter_name]
continue
if parameter_name in self.environment:
kwargs[parameter_name] = self.instantiate_by_name(parameter_name)
continue
if is_required:
funcname = f"{inspect.getmodule(func).__name__}.{func.__name__}"
raise RuntimeError("Required argument '{}' cannot be resolved for function '{}'".format(
parameter_name, funcname
))
return kwargs | [
"def",
"resolve_parameters",
"(",
"self",
",",
"func",
",",
"extra_env",
"=",
"None",
")",
":",
"parameter_list",
"=",
"[",
"(",
"k",
",",
"v",
".",
"default",
"==",
"inspect",
".",
"Parameter",
".",
"empty",
")",
"for",
"k",
",",
"v",
"in",
"inspect",
".",
"signature",
"(",
"func",
")",
".",
"parameters",
".",
"items",
"(",
")",
"]",
"extra_env",
"=",
"extra_env",
"if",
"extra_env",
"is",
"not",
"None",
"else",
"{",
"}",
"kwargs",
"=",
"{",
"}",
"for",
"parameter_name",
",",
"is_required",
"in",
"parameter_list",
":",
"# extra_env is a 'local' object data defined in-place",
"if",
"parameter_name",
"in",
"extra_env",
":",
"kwargs",
"[",
"parameter_name",
"]",
"=",
"self",
".",
"instantiate_from_data",
"(",
"extra_env",
"[",
"parameter_name",
"]",
")",
"continue",
"if",
"parameter_name",
"in",
"self",
".",
"instances",
":",
"kwargs",
"[",
"parameter_name",
"]",
"=",
"self",
".",
"instances",
"[",
"parameter_name",
"]",
"continue",
"if",
"parameter_name",
"in",
"self",
".",
"environment",
":",
"kwargs",
"[",
"parameter_name",
"]",
"=",
"self",
".",
"instantiate_by_name",
"(",
"parameter_name",
")",
"continue",
"if",
"is_required",
":",
"funcname",
"=",
"f\"{inspect.getmodule(func).__name__}.{func.__name__}\"",
"raise",
"RuntimeError",
"(",
"\"Required argument '{}' cannot be resolved for function '{}'\"",
".",
"format",
"(",
"parameter_name",
",",
"funcname",
")",
")",
"return",
"kwargs"
] | Resolve parameter dictionary for the supplied function | [
"Resolve",
"parameter",
"dictionary",
"for",
"the",
"supplied",
"function"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L24-L52 |
251,297 | MillionIntegrals/vel | vel/internals/provider.py | Provider.resolve_and_call | def resolve_and_call(self, func, extra_env=None):
""" Resolve function arguments and call them, possibily filling from the environment """
kwargs = self.resolve_parameters(func, extra_env=extra_env)
return func(**kwargs) | python | def resolve_and_call(self, func, extra_env=None):
kwargs = self.resolve_parameters(func, extra_env=extra_env)
return func(**kwargs) | [
"def",
"resolve_and_call",
"(",
"self",
",",
"func",
",",
"extra_env",
"=",
"None",
")",
":",
"kwargs",
"=",
"self",
".",
"resolve_parameters",
"(",
"func",
",",
"extra_env",
"=",
"extra_env",
")",
"return",
"func",
"(",
"*",
"*",
"kwargs",
")"
] | Resolve function arguments and call them, possibily filling from the environment | [
"Resolve",
"function",
"arguments",
"and",
"call",
"them",
"possibily",
"filling",
"from",
"the",
"environment"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L54-L57 |
251,298 | MillionIntegrals/vel | vel/internals/provider.py | Provider.instantiate_from_data | def instantiate_from_data(self, object_data):
""" Instantiate object from the supplied data, additional args may come from the environment """
if isinstance(object_data, dict) and 'name' in object_data:
name = object_data['name']
module = importlib.import_module(name)
return self.resolve_and_call(module.create, extra_env=object_data)
if isinstance(object_data, dict) and 'factory' in object_data:
factory = object_data['factory']
module = importlib.import_module(factory)
params = self.resolve_parameters(module.create, extra_env=object_data)
return GenericFactory(module.create, params)
elif isinstance(object_data, dict):
return {k: self.instantiate_from_data(v) for k, v in object_data.items()}
elif isinstance(object_data, list):
return [self.instantiate_from_data(x) for x in object_data]
elif isinstance(object_data, Variable):
return object_data.resolve(self.parameters)
else:
return object_data | python | def instantiate_from_data(self, object_data):
if isinstance(object_data, dict) and 'name' in object_data:
name = object_data['name']
module = importlib.import_module(name)
return self.resolve_and_call(module.create, extra_env=object_data)
if isinstance(object_data, dict) and 'factory' in object_data:
factory = object_data['factory']
module = importlib.import_module(factory)
params = self.resolve_parameters(module.create, extra_env=object_data)
return GenericFactory(module.create, params)
elif isinstance(object_data, dict):
return {k: self.instantiate_from_data(v) for k, v in object_data.items()}
elif isinstance(object_data, list):
return [self.instantiate_from_data(x) for x in object_data]
elif isinstance(object_data, Variable):
return object_data.resolve(self.parameters)
else:
return object_data | [
"def",
"instantiate_from_data",
"(",
"self",
",",
"object_data",
")",
":",
"if",
"isinstance",
"(",
"object_data",
",",
"dict",
")",
"and",
"'name'",
"in",
"object_data",
":",
"name",
"=",
"object_data",
"[",
"'name'",
"]",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"name",
")",
"return",
"self",
".",
"resolve_and_call",
"(",
"module",
".",
"create",
",",
"extra_env",
"=",
"object_data",
")",
"if",
"isinstance",
"(",
"object_data",
",",
"dict",
")",
"and",
"'factory'",
"in",
"object_data",
":",
"factory",
"=",
"object_data",
"[",
"'factory'",
"]",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"factory",
")",
"params",
"=",
"self",
".",
"resolve_parameters",
"(",
"module",
".",
"create",
",",
"extra_env",
"=",
"object_data",
")",
"return",
"GenericFactory",
"(",
"module",
".",
"create",
",",
"params",
")",
"elif",
"isinstance",
"(",
"object_data",
",",
"dict",
")",
":",
"return",
"{",
"k",
":",
"self",
".",
"instantiate_from_data",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"object_data",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"object_data",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"instantiate_from_data",
"(",
"x",
")",
"for",
"x",
"in",
"object_data",
"]",
"elif",
"isinstance",
"(",
"object_data",
",",
"Variable",
")",
":",
"return",
"object_data",
".",
"resolve",
"(",
"self",
".",
"parameters",
")",
"else",
":",
"return",
"object_data"
] | Instantiate object from the supplied data, additional args may come from the environment | [
"Instantiate",
"object",
"from",
"the",
"supplied",
"data",
"additional",
"args",
"may",
"come",
"from",
"the",
"environment"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L59-L77 |
251,299 | MillionIntegrals/vel | vel/internals/provider.py | Provider.render_configuration | def render_configuration(self, configuration=None):
""" Render variables in configuration object but don't instantiate anything """
if configuration is None:
configuration = self.environment
if isinstance(configuration, dict):
return {k: self.render_configuration(v) for k, v in configuration.items()}
elif isinstance(configuration, list):
return [self.render_configuration(x) for x in configuration]
elif isinstance(configuration, Variable):
return configuration.resolve(self.parameters)
else:
return configuration | python | def render_configuration(self, configuration=None):
if configuration is None:
configuration = self.environment
if isinstance(configuration, dict):
return {k: self.render_configuration(v) for k, v in configuration.items()}
elif isinstance(configuration, list):
return [self.render_configuration(x) for x in configuration]
elif isinstance(configuration, Variable):
return configuration.resolve(self.parameters)
else:
return configuration | [
"def",
"render_configuration",
"(",
"self",
",",
"configuration",
"=",
"None",
")",
":",
"if",
"configuration",
"is",
"None",
":",
"configuration",
"=",
"self",
".",
"environment",
"if",
"isinstance",
"(",
"configuration",
",",
"dict",
")",
":",
"return",
"{",
"k",
":",
"self",
".",
"render_configuration",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"configuration",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"configuration",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"render_configuration",
"(",
"x",
")",
"for",
"x",
"in",
"configuration",
"]",
"elif",
"isinstance",
"(",
"configuration",
",",
"Variable",
")",
":",
"return",
"configuration",
".",
"resolve",
"(",
"self",
".",
"parameters",
")",
"else",
":",
"return",
"configuration"
] | Render variables in configuration object but don't instantiate anything | [
"Render",
"variables",
"in",
"configuration",
"object",
"but",
"don",
"t",
"instantiate",
"anything"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/provider.py#L79-L91 |
Subsets and Splits