partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
Zotero.delete_tags
Delete a group of tags pass in up to 50 tags, or use *[tags]
pyzotero/zotero.py
def delete_tags(self, *payload): """ Delete a group of tags pass in up to 50 tags, or use *[tags] """ if len(payload) > 50: raise ze.TooManyItems("Only 50 tags or fewer may be deleted") modified_tags = " || ".join([tag for tag in payload]) # first, get version data by getting one tag self.tags(limit=1) headers = { "If-Unmodified-Since-Version": self.request.headers["last-modified-version"] } headers.update(self.default_headers()) req = requests.delete( url=self.endpoint + "/{t}/{u}/tags".format(t=self.library_type, u=self.library_id), params={"tag": modified_tags}, headers=headers, ) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) return True
def delete_tags(self, *payload): """ Delete a group of tags pass in up to 50 tags, or use *[tags] """ if len(payload) > 50: raise ze.TooManyItems("Only 50 tags or fewer may be deleted") modified_tags = " || ".join([tag for tag in payload]) # first, get version data by getting one tag self.tags(limit=1) headers = { "If-Unmodified-Since-Version": self.request.headers["last-modified-version"] } headers.update(self.default_headers()) req = requests.delete( url=self.endpoint + "/{t}/{u}/tags".format(t=self.library_type, u=self.library_id), params={"tag": modified_tags}, headers=headers, ) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) return True
[ "Delete", "a", "group", "of", "tags", "pass", "in", "up", "to", "50", "tags", "or", "use", "*", "[", "tags", "]" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1420-L1446
[ "def", "delete_tags", "(", "self", ",", "*", "payload", ")", ":", "if", "len", "(", "payload", ")", ">", "50", ":", "raise", "ze", ".", "TooManyItems", "(", "\"Only 50 tags or fewer may be deleted\"", ")", "modified_tags", "=", "\" || \"", ".", "join", "(", "[", "tag", "for", "tag", "in", "payload", "]", ")", "# first, get version data by getting one tag", "self", ".", "tags", "(", "limit", "=", "1", ")", "headers", "=", "{", "\"If-Unmodified-Since-Version\"", ":", "self", ".", "request", ".", "headers", "[", "\"last-modified-version\"", "]", "}", "headers", ".", "update", "(", "self", ".", "default_headers", "(", ")", ")", "req", "=", "requests", ".", "delete", "(", "url", "=", "self", ".", "endpoint", "+", "\"/{t}/{u}/tags\"", ".", "format", "(", "t", "=", "self", ".", "library_type", ",", "u", "=", "self", ".", "library_id", ")", ",", "params", "=", "{", "\"tag\"", ":", "modified_tags", "}", ",", "headers", "=", "headers", ",", ")", "self", ".", "request", "=", "req", "try", ":", "req", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "req", ")", "return", "True" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
Zotero.delete_item
Delete Items from a Zotero library Accepts a single argument: a dict containing item data OR a list of dicts containing item data
pyzotero/zotero.py
def delete_item(self, payload, last_modified=None): """ Delete Items from a Zotero library Accepts a single argument: a dict containing item data OR a list of dicts containing item data """ params = None if isinstance(payload, list): params = {"itemKey": ",".join([p["key"] for p in payload])} if last_modified is not None: modified = last_modified else: modified = payload[0]["version"] url = self.endpoint + "/{t}/{u}/items".format( t=self.library_type, u=self.library_id ) else: ident = payload["key"] if last_modified is not None: modified = last_modified else: modified = payload["version"] url = self.endpoint + "/{t}/{u}/items/{c}".format( t=self.library_type, u=self.library_id, c=ident ) headers = {"If-Unmodified-Since-Version": str(modified)} headers.update(self.default_headers()) req = requests.delete(url=url, params=params, headers=headers) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) return True
def delete_item(self, payload, last_modified=None): """ Delete Items from a Zotero library Accepts a single argument: a dict containing item data OR a list of dicts containing item data """ params = None if isinstance(payload, list): params = {"itemKey": ",".join([p["key"] for p in payload])} if last_modified is not None: modified = last_modified else: modified = payload[0]["version"] url = self.endpoint + "/{t}/{u}/items".format( t=self.library_type, u=self.library_id ) else: ident = payload["key"] if last_modified is not None: modified = last_modified else: modified = payload["version"] url = self.endpoint + "/{t}/{u}/items/{c}".format( t=self.library_type, u=self.library_id, c=ident ) headers = {"If-Unmodified-Since-Version": str(modified)} headers.update(self.default_headers()) req = requests.delete(url=url, params=params, headers=headers) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) return True
[ "Delete", "Items", "from", "a", "Zotero", "library", "Accepts", "a", "single", "argument", ":", "a", "dict", "containing", "item", "data", "OR", "a", "list", "of", "dicts", "containing", "item", "data" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1448-L1482
[ "def", "delete_item", "(", "self", ",", "payload", ",", "last_modified", "=", "None", ")", ":", "params", "=", "None", "if", "isinstance", "(", "payload", ",", "list", ")", ":", "params", "=", "{", "\"itemKey\"", ":", "\",\"", ".", "join", "(", "[", "p", "[", "\"key\"", "]", "for", "p", "in", "payload", "]", ")", "}", "if", "last_modified", "is", "not", "None", ":", "modified", "=", "last_modified", "else", ":", "modified", "=", "payload", "[", "0", "]", "[", "\"version\"", "]", "url", "=", "self", ".", "endpoint", "+", "\"/{t}/{u}/items\"", ".", "format", "(", "t", "=", "self", ".", "library_type", ",", "u", "=", "self", ".", "library_id", ")", "else", ":", "ident", "=", "payload", "[", "\"key\"", "]", "if", "last_modified", "is", "not", "None", ":", "modified", "=", "last_modified", "else", ":", "modified", "=", "payload", "[", "\"version\"", "]", "url", "=", "self", ".", "endpoint", "+", "\"/{t}/{u}/items/{c}\"", ".", "format", "(", "t", "=", "self", ".", "library_type", ",", "u", "=", "self", ".", "library_id", ",", "c", "=", "ident", ")", "headers", "=", "{", "\"If-Unmodified-Since-Version\"", ":", "str", "(", "modified", ")", "}", "headers", ".", "update", "(", "self", ".", "default_headers", "(", ")", ")", "req", "=", "requests", ".", "delete", "(", "url", "=", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ")", "self", ".", "request", "=", "req", "try", ":", "req", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "req", ")", "return", "True" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
SavedSearch._validate
Validate saved search conditions, raising an error if any contain invalid operators
pyzotero/zotero.py
def _validate(self, conditions): """ Validate saved search conditions, raising an error if any contain invalid operators """ allowed_keys = set(self.searchkeys) operators_set = set(self.operators.keys()) for condition in conditions: if set(condition.keys()) != allowed_keys: raise ze.ParamNotPassed( "Keys must be all of: %s" % ", ".join(self.searchkeys) ) if condition.get("operator") not in operators_set: raise ze.ParamNotPassed( "You have specified an unknown operator: %s" % condition.get("operator") ) # dict keys of allowed operators for the current condition permitted_operators = self.conditions_operators.get( condition.get("condition") ) # transform these into values permitted_operators_list = set( [self.operators.get(op) for op in permitted_operators] ) if condition.get("operator") not in permitted_operators_list: raise ze.ParamNotPassed( "You may not use the '%s' operator when selecting the '%s' condition. \nAllowed operators: %s" % ( condition.get("operator"), condition.get("condition"), ", ".join(list(permitted_operators_list)), ) )
def _validate(self, conditions): """ Validate saved search conditions, raising an error if any contain invalid operators """ allowed_keys = set(self.searchkeys) operators_set = set(self.operators.keys()) for condition in conditions: if set(condition.keys()) != allowed_keys: raise ze.ParamNotPassed( "Keys must be all of: %s" % ", ".join(self.searchkeys) ) if condition.get("operator") not in operators_set: raise ze.ParamNotPassed( "You have specified an unknown operator: %s" % condition.get("operator") ) # dict keys of allowed operators for the current condition permitted_operators = self.conditions_operators.get( condition.get("condition") ) # transform these into values permitted_operators_list = set( [self.operators.get(op) for op in permitted_operators] ) if condition.get("operator") not in permitted_operators_list: raise ze.ParamNotPassed( "You may not use the '%s' operator when selecting the '%s' condition. \nAllowed operators: %s" % ( condition.get("operator"), condition.get("condition"), ", ".join(list(permitted_operators_list)), ) )
[ "Validate", "saved", "search", "conditions", "raising", "an", "error", "if", "any", "contain", "invalid", "operators" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1725-L1755
[ "def", "_validate", "(", "self", ",", "conditions", ")", ":", "allowed_keys", "=", "set", "(", "self", ".", "searchkeys", ")", "operators_set", "=", "set", "(", "self", ".", "operators", ".", "keys", "(", ")", ")", "for", "condition", "in", "conditions", ":", "if", "set", "(", "condition", ".", "keys", "(", ")", ")", "!=", "allowed_keys", ":", "raise", "ze", ".", "ParamNotPassed", "(", "\"Keys must be all of: %s\"", "%", "\", \"", ".", "join", "(", "self", ".", "searchkeys", ")", ")", "if", "condition", ".", "get", "(", "\"operator\"", ")", "not", "in", "operators_set", ":", "raise", "ze", ".", "ParamNotPassed", "(", "\"You have specified an unknown operator: %s\"", "%", "condition", ".", "get", "(", "\"operator\"", ")", ")", "# dict keys of allowed operators for the current condition", "permitted_operators", "=", "self", ".", "conditions_operators", ".", "get", "(", "condition", ".", "get", "(", "\"condition\"", ")", ")", "# transform these into values", "permitted_operators_list", "=", "set", "(", "[", "self", ".", "operators", ".", "get", "(", "op", ")", "for", "op", "in", "permitted_operators", "]", ")", "if", "condition", ".", "get", "(", "\"operator\"", ")", "not", "in", "permitted_operators_list", ":", "raise", "ze", ".", "ParamNotPassed", "(", "\"You may not use the '%s' operator when selecting the '%s' condition. \\nAllowed operators: %s\"", "%", "(", "condition", ".", "get", "(", "\"operator\"", ")", ",", "condition", ".", "get", "(", "\"condition\"", ")", ",", "\", \"", ".", "join", "(", "list", "(", "permitted_operators_list", ")", ")", ",", ")", ")" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
Zupload._verify
ensure that all files to be attached exist open()'s better than exists(), cos it avoids a race condition
pyzotero/zotero.py
def _verify(self, payload): """ ensure that all files to be attached exist open()'s better than exists(), cos it avoids a race condition """ if not payload: # Check payload has nonzero length raise ze.ParamNotPassed for templt in payload: if os.path.isfile(str(self.basedir.joinpath(templt["filename"]))): try: # if it is a file, try to open it, and catch the error with open(str(self.basedir.joinpath(templt["filename"]))): pass except IOError: raise ze.FileDoesNotExist( "The file at %s couldn't be opened or found." % str(self.basedir.joinpath(templt["filename"])) ) # no point in continuing if the file isn't a file else: raise ze.FileDoesNotExist( "The file at %s couldn't be opened or found." % str(self.basedir.joinpath(templt["filename"])) )
def _verify(self, payload): """ ensure that all files to be attached exist open()'s better than exists(), cos it avoids a race condition """ if not payload: # Check payload has nonzero length raise ze.ParamNotPassed for templt in payload: if os.path.isfile(str(self.basedir.joinpath(templt["filename"]))): try: # if it is a file, try to open it, and catch the error with open(str(self.basedir.joinpath(templt["filename"]))): pass except IOError: raise ze.FileDoesNotExist( "The file at %s couldn't be opened or found." % str(self.basedir.joinpath(templt["filename"])) ) # no point in continuing if the file isn't a file else: raise ze.FileDoesNotExist( "The file at %s couldn't be opened or found." % str(self.basedir.joinpath(templt["filename"])) )
[ "ensure", "that", "all", "files", "to", "be", "attached", "exist", "open", "()", "s", "better", "than", "exists", "()", "cos", "it", "avoids", "a", "race", "condition" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1777-L1800
[ "def", "_verify", "(", "self", ",", "payload", ")", ":", "if", "not", "payload", ":", "# Check payload has nonzero length", "raise", "ze", ".", "ParamNotPassed", "for", "templt", "in", "payload", ":", "if", "os", ".", "path", ".", "isfile", "(", "str", "(", "self", ".", "basedir", ".", "joinpath", "(", "templt", "[", "\"filename\"", "]", ")", ")", ")", ":", "try", ":", "# if it is a file, try to open it, and catch the error", "with", "open", "(", "str", "(", "self", ".", "basedir", ".", "joinpath", "(", "templt", "[", "\"filename\"", "]", ")", ")", ")", ":", "pass", "except", "IOError", ":", "raise", "ze", ".", "FileDoesNotExist", "(", "\"The file at %s couldn't be opened or found.\"", "%", "str", "(", "self", ".", "basedir", ".", "joinpath", "(", "templt", "[", "\"filename\"", "]", ")", ")", ")", "# no point in continuing if the file isn't a file", "else", ":", "raise", "ze", ".", "FileDoesNotExist", "(", "\"The file at %s couldn't be opened or found.\"", "%", "str", "(", "self", ".", "basedir", ".", "joinpath", "(", "templt", "[", "\"filename\"", "]", ")", ")", ")" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
Zupload._create_prelim
Step 0: Register intent to upload files
pyzotero/zotero.py
def _create_prelim(self): """ Step 0: Register intent to upload files """ self._verify(self.payload) if "key" in self.payload[0] and self.payload[0]["key"]: if next((i for i in self.payload if "key" not in i), False): raise ze.UnsupportedParams( "Can't pass payload entries with and without keys to Zupload" ) return None # Don't do anything if payload comes with keys liblevel = "/{t}/{u}/items" # Create one or more new attachments headers = {"Zotero-Write-Token": token(), "Content-Type": "application/json"} headers.update(self.zinstance.default_headers()) # If we have a Parent ID, add it as a parentItem if self.parentid: for child in self.payload: child["parentItem"] = self.parentid to_send = json.dumps(self.payload) req = requests.post( url=self.zinstance.endpoint + liblevel.format( t=self.zinstance.library_type, u=self.zinstance.library_id ), data=to_send, headers=headers, ) try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) data = req.json() for k in data["success"]: self.payload[int(k)]["key"] = data["success"][k] return data
def _create_prelim(self): """ Step 0: Register intent to upload files """ self._verify(self.payload) if "key" in self.payload[0] and self.payload[0]["key"]: if next((i for i in self.payload if "key" not in i), False): raise ze.UnsupportedParams( "Can't pass payload entries with and without keys to Zupload" ) return None # Don't do anything if payload comes with keys liblevel = "/{t}/{u}/items" # Create one or more new attachments headers = {"Zotero-Write-Token": token(), "Content-Type": "application/json"} headers.update(self.zinstance.default_headers()) # If we have a Parent ID, add it as a parentItem if self.parentid: for child in self.payload: child["parentItem"] = self.parentid to_send = json.dumps(self.payload) req = requests.post( url=self.zinstance.endpoint + liblevel.format( t=self.zinstance.library_type, u=self.zinstance.library_id ), data=to_send, headers=headers, ) try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) data = req.json() for k in data["success"]: self.payload[int(k)]["key"] = data["success"][k] return data
[ "Step", "0", ":", "Register", "intent", "to", "upload", "files" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1802-L1837
[ "def", "_create_prelim", "(", "self", ")", ":", "self", ".", "_verify", "(", "self", ".", "payload", ")", "if", "\"key\"", "in", "self", ".", "payload", "[", "0", "]", "and", "self", ".", "payload", "[", "0", "]", "[", "\"key\"", "]", ":", "if", "next", "(", "(", "i", "for", "i", "in", "self", ".", "payload", "if", "\"key\"", "not", "in", "i", ")", ",", "False", ")", ":", "raise", "ze", ".", "UnsupportedParams", "(", "\"Can't pass payload entries with and without keys to Zupload\"", ")", "return", "None", "# Don't do anything if payload comes with keys", "liblevel", "=", "\"/{t}/{u}/items\"", "# Create one or more new attachments", "headers", "=", "{", "\"Zotero-Write-Token\"", ":", "token", "(", ")", ",", "\"Content-Type\"", ":", "\"application/json\"", "}", "headers", ".", "update", "(", "self", ".", "zinstance", ".", "default_headers", "(", ")", ")", "# If we have a Parent ID, add it as a parentItem", "if", "self", ".", "parentid", ":", "for", "child", "in", "self", ".", "payload", ":", "child", "[", "\"parentItem\"", "]", "=", "self", ".", "parentid", "to_send", "=", "json", ".", "dumps", "(", "self", ".", "payload", ")", "req", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "zinstance", ".", "endpoint", "+", "liblevel", ".", "format", "(", "t", "=", "self", ".", "zinstance", ".", "library_type", ",", "u", "=", "self", ".", "zinstance", ".", "library_id", ")", ",", "data", "=", "to_send", ",", "headers", "=", "headers", ",", ")", "try", ":", "req", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "req", ")", "data", "=", "req", ".", "json", "(", ")", "for", "k", "in", "data", "[", "\"success\"", "]", ":", "self", ".", "payload", "[", "int", "(", "k", ")", "]", "[", "\"key\"", "]", "=", "data", "[", "\"success\"", "]", "[", "k", "]", "return", "data" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
Zupload._get_auth
Step 1: get upload authorisation for a file
pyzotero/zotero.py
def _get_auth(self, attachment, reg_key, md5=None): """ Step 1: get upload authorisation for a file """ mtypes = mimetypes.guess_type(attachment) digest = hashlib.md5() with open(attachment, "rb") as att: for chunk in iter(lambda: att.read(8192), b""): digest.update(chunk) auth_headers = {"Content-Type": "application/x-www-form-urlencoded"} if not md5: auth_headers["If-None-Match"] = "*" else: # docs specify that for existing file we use this auth_headers["If-Match"] = md5 auth_headers.update(self.zinstance.default_headers()) data = { "md5": digest.hexdigest(), "filename": os.path.basename(attachment), "filesize": os.path.getsize(attachment), "mtime": str(int(os.path.getmtime(attachment) * 1000)), "contentType": mtypes[0] or "application/octet-stream", "charset": mtypes[1], "params": 1, } auth_req = requests.post( url=self.zinstance.endpoint + "/{t}/{u}/items/{i}/file".format( t=self.zinstance.library_type, u=self.zinstance.library_id, i=reg_key ), data=data, headers=auth_headers, ) try: auth_req.raise_for_status() except requests.exceptions.HTTPError: error_handler(auth_req) return auth_req.json()
def _get_auth(self, attachment, reg_key, md5=None): """ Step 1: get upload authorisation for a file """ mtypes = mimetypes.guess_type(attachment) digest = hashlib.md5() with open(attachment, "rb") as att: for chunk in iter(lambda: att.read(8192), b""): digest.update(chunk) auth_headers = {"Content-Type": "application/x-www-form-urlencoded"} if not md5: auth_headers["If-None-Match"] = "*" else: # docs specify that for existing file we use this auth_headers["If-Match"] = md5 auth_headers.update(self.zinstance.default_headers()) data = { "md5": digest.hexdigest(), "filename": os.path.basename(attachment), "filesize": os.path.getsize(attachment), "mtime": str(int(os.path.getmtime(attachment) * 1000)), "contentType": mtypes[0] or "application/octet-stream", "charset": mtypes[1], "params": 1, } auth_req = requests.post( url=self.zinstance.endpoint + "/{t}/{u}/items/{i}/file".format( t=self.zinstance.library_type, u=self.zinstance.library_id, i=reg_key ), data=data, headers=auth_headers, ) try: auth_req.raise_for_status() except requests.exceptions.HTTPError: error_handler(auth_req) return auth_req.json()
[ "Step", "1", ":", "get", "upload", "authorisation", "for", "a", "file" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1839-L1876
[ "def", "_get_auth", "(", "self", ",", "attachment", ",", "reg_key", ",", "md5", "=", "None", ")", ":", "mtypes", "=", "mimetypes", ".", "guess_type", "(", "attachment", ")", "digest", "=", "hashlib", ".", "md5", "(", ")", "with", "open", "(", "attachment", ",", "\"rb\"", ")", "as", "att", ":", "for", "chunk", "in", "iter", "(", "lambda", ":", "att", ".", "read", "(", "8192", ")", ",", "b\"\"", ")", ":", "digest", ".", "update", "(", "chunk", ")", "auth_headers", "=", "{", "\"Content-Type\"", ":", "\"application/x-www-form-urlencoded\"", "}", "if", "not", "md5", ":", "auth_headers", "[", "\"If-None-Match\"", "]", "=", "\"*\"", "else", ":", "# docs specify that for existing file we use this", "auth_headers", "[", "\"If-Match\"", "]", "=", "md5", "auth_headers", ".", "update", "(", "self", ".", "zinstance", ".", "default_headers", "(", ")", ")", "data", "=", "{", "\"md5\"", ":", "digest", ".", "hexdigest", "(", ")", ",", "\"filename\"", ":", "os", ".", "path", ".", "basename", "(", "attachment", ")", ",", "\"filesize\"", ":", "os", ".", "path", ".", "getsize", "(", "attachment", ")", ",", "\"mtime\"", ":", "str", "(", "int", "(", "os", ".", "path", ".", "getmtime", "(", "attachment", ")", "*", "1000", ")", ")", ",", "\"contentType\"", ":", "mtypes", "[", "0", "]", "or", "\"application/octet-stream\"", ",", "\"charset\"", ":", "mtypes", "[", "1", "]", ",", "\"params\"", ":", "1", ",", "}", "auth_req", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "zinstance", ".", "endpoint", "+", "\"/{t}/{u}/items/{i}/file\"", ".", "format", "(", "t", "=", "self", ".", "zinstance", ".", "library_type", ",", "u", "=", "self", ".", "zinstance", ".", "library_id", ",", "i", "=", "reg_key", ")", ",", "data", "=", "data", ",", "headers", "=", "auth_headers", ",", ")", "try", ":", "auth_req", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "auth_req", ")", "return", "auth_req", ".", "json", "(", ")" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
Zupload._upload_file
Step 2: auth successful, and file not on server zotero.org/support/dev/server_api/file_upload#a_full_upload reg_key isn't used, but we need to pass it through to Step 3
pyzotero/zotero.py
def _upload_file(self, authdata, attachment, reg_key): """ Step 2: auth successful, and file not on server zotero.org/support/dev/server_api/file_upload#a_full_upload reg_key isn't used, but we need to pass it through to Step 3 """ upload_dict = authdata[ "params" ] # using params now since prefix/suffix concat was giving ConnectionError # must pass tuple of tuples not dict to ensure key comes first upload_list = [("key", upload_dict["key"])] for k in upload_dict: if k != "key": upload_list.append((k, upload_dict[k])) # The prior code for attaching file gave me content not match md5 # errors upload_list.append(("file", open(attachment, "rb").read())) upload_pairs = tuple(upload_list) try: upload = requests.post( url=authdata["url"], files=upload_pairs, headers={ # "Content-Type": authdata['contentType'], "User-Agent": "Pyzotero/%s" % __version__ }, ) except (requests.exceptions.ConnectionError): raise ze.UploadError("ConnectionError") try: upload.raise_for_status() except requests.exceptions.HTTPError: error_handler(upload) # now check the responses return self._register_upload(authdata, reg_key)
def _upload_file(self, authdata, attachment, reg_key): """ Step 2: auth successful, and file not on server zotero.org/support/dev/server_api/file_upload#a_full_upload reg_key isn't used, but we need to pass it through to Step 3 """ upload_dict = authdata[ "params" ] # using params now since prefix/suffix concat was giving ConnectionError # must pass tuple of tuples not dict to ensure key comes first upload_list = [("key", upload_dict["key"])] for k in upload_dict: if k != "key": upload_list.append((k, upload_dict[k])) # The prior code for attaching file gave me content not match md5 # errors upload_list.append(("file", open(attachment, "rb").read())) upload_pairs = tuple(upload_list) try: upload = requests.post( url=authdata["url"], files=upload_pairs, headers={ # "Content-Type": authdata['contentType'], "User-Agent": "Pyzotero/%s" % __version__ }, ) except (requests.exceptions.ConnectionError): raise ze.UploadError("ConnectionError") try: upload.raise_for_status() except requests.exceptions.HTTPError: error_handler(upload) # now check the responses return self._register_upload(authdata, reg_key)
[ "Step", "2", ":", "auth", "successful", "and", "file", "not", "on", "server", "zotero", ".", "org", "/", "support", "/", "dev", "/", "server_api", "/", "file_upload#a_full_upload" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1878-L1914
[ "def", "_upload_file", "(", "self", ",", "authdata", ",", "attachment", ",", "reg_key", ")", ":", "upload_dict", "=", "authdata", "[", "\"params\"", "]", "# using params now since prefix/suffix concat was giving ConnectionError", "# must pass tuple of tuples not dict to ensure key comes first", "upload_list", "=", "[", "(", "\"key\"", ",", "upload_dict", "[", "\"key\"", "]", ")", "]", "for", "k", "in", "upload_dict", ":", "if", "k", "!=", "\"key\"", ":", "upload_list", ".", "append", "(", "(", "k", ",", "upload_dict", "[", "k", "]", ")", ")", "# The prior code for attaching file gave me content not match md5", "# errors", "upload_list", ".", "append", "(", "(", "\"file\"", ",", "open", "(", "attachment", ",", "\"rb\"", ")", ".", "read", "(", ")", ")", ")", "upload_pairs", "=", "tuple", "(", "upload_list", ")", "try", ":", "upload", "=", "requests", ".", "post", "(", "url", "=", "authdata", "[", "\"url\"", "]", ",", "files", "=", "upload_pairs", ",", "headers", "=", "{", "# \"Content-Type\": authdata['contentType'],", "\"User-Agent\"", ":", "\"Pyzotero/%s\"", "%", "__version__", "}", ",", ")", "except", "(", "requests", ".", "exceptions", ".", "ConnectionError", ")", ":", "raise", "ze", ".", "UploadError", "(", "\"ConnectionError\"", ")", "try", ":", "upload", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "upload", ")", "# now check the responses", "return", "self", ".", "_register_upload", "(", "authdata", ",", "reg_key", ")" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
Zupload._register_upload
Step 3: upload successful, so register it
pyzotero/zotero.py
def _register_upload(self, authdata, reg_key): """ Step 3: upload successful, so register it """ reg_headers = { "Content-Type": "application/x-www-form-urlencoded", "If-None-Match": "*", } reg_headers.update(self.zinstance.default_headers()) reg_data = {"upload": authdata.get("uploadKey")} upload_reg = requests.post( url=self.zinstance.endpoint + "/{t}/{u}/items/{i}/file".format( t=self.zinstance.library_type, u=self.zinstance.library_id, i=reg_key ), data=reg_data, headers=dict(reg_headers), ) try: upload_reg.raise_for_status() except requests.exceptions.HTTPError: error_handler(upload_reg)
def _register_upload(self, authdata, reg_key): """ Step 3: upload successful, so register it """ reg_headers = { "Content-Type": "application/x-www-form-urlencoded", "If-None-Match": "*", } reg_headers.update(self.zinstance.default_headers()) reg_data = {"upload": authdata.get("uploadKey")} upload_reg = requests.post( url=self.zinstance.endpoint + "/{t}/{u}/items/{i}/file".format( t=self.zinstance.library_type, u=self.zinstance.library_id, i=reg_key ), data=reg_data, headers=dict(reg_headers), ) try: upload_reg.raise_for_status() except requests.exceptions.HTTPError: error_handler(upload_reg)
[ "Step", "3", ":", "upload", "successful", "so", "register", "it" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1916-L1937
[ "def", "_register_upload", "(", "self", ",", "authdata", ",", "reg_key", ")", ":", "reg_headers", "=", "{", "\"Content-Type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"If-None-Match\"", ":", "\"*\"", ",", "}", "reg_headers", ".", "update", "(", "self", ".", "zinstance", ".", "default_headers", "(", ")", ")", "reg_data", "=", "{", "\"upload\"", ":", "authdata", ".", "get", "(", "\"uploadKey\"", ")", "}", "upload_reg", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "zinstance", ".", "endpoint", "+", "\"/{t}/{u}/items/{i}/file\"", ".", "format", "(", "t", "=", "self", ".", "zinstance", ".", "library_type", ",", "u", "=", "self", ".", "zinstance", ".", "library_id", ",", "i", "=", "reg_key", ")", ",", "data", "=", "reg_data", ",", "headers", "=", "dict", "(", "reg_headers", ")", ",", ")", "try", ":", "upload_reg", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", ":", "error_handler", "(", "upload_reg", ")" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
Zupload.upload
File upload functionality Goes through upload steps 0 - 3 (private class methods), and returns a dict noting success, failure, or unchanged (returning the payload entries with that property as a list for each status)
pyzotero/zotero.py
def upload(self): """ File upload functionality Goes through upload steps 0 - 3 (private class methods), and returns a dict noting success, failure, or unchanged (returning the payload entries with that property as a list for each status) """ result = {"success": [], "failure": [], "unchanged": []} self._create_prelim() for item in self.payload: if "key" not in item: result["failure"].append(item) continue attach = str(self.basedir.joinpath(item["filename"])) authdata = self._get_auth(attach, item["key"], md5=item.get("md5", None)) # no need to keep going if the file exists if authdata.get("exists"): result["unchanged"].append(item) continue self._upload_file(authdata, attach, item["key"]) result["success"].append(item) return result
def upload(self): """ File upload functionality Goes through upload steps 0 - 3 (private class methods), and returns a dict noting success, failure, or unchanged (returning the payload entries with that property as a list for each status) """ result = {"success": [], "failure": [], "unchanged": []} self._create_prelim() for item in self.payload: if "key" not in item: result["failure"].append(item) continue attach = str(self.basedir.joinpath(item["filename"])) authdata = self._get_auth(attach, item["key"], md5=item.get("md5", None)) # no need to keep going if the file exists if authdata.get("exists"): result["unchanged"].append(item) continue self._upload_file(authdata, attach, item["key"]) result["success"].append(item) return result
[ "File", "upload", "functionality" ]
urschrei/pyzotero
python
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1939-L1961
[ "def", "upload", "(", "self", ")", ":", "result", "=", "{", "\"success\"", ":", "[", "]", ",", "\"failure\"", ":", "[", "]", ",", "\"unchanged\"", ":", "[", "]", "}", "self", ".", "_create_prelim", "(", ")", "for", "item", "in", "self", ".", "payload", ":", "if", "\"key\"", "not", "in", "item", ":", "result", "[", "\"failure\"", "]", ".", "append", "(", "item", ")", "continue", "attach", "=", "str", "(", "self", ".", "basedir", ".", "joinpath", "(", "item", "[", "\"filename\"", "]", ")", ")", "authdata", "=", "self", ".", "_get_auth", "(", "attach", ",", "item", "[", "\"key\"", "]", ",", "md5", "=", "item", ".", "get", "(", "\"md5\"", ",", "None", ")", ")", "# no need to keep going if the file exists", "if", "authdata", ".", "get", "(", "\"exists\"", ")", ":", "result", "[", "\"unchanged\"", "]", ".", "append", "(", "item", ")", "continue", "self", ".", "_upload_file", "(", "authdata", ",", "attach", ",", "item", "[", "\"key\"", "]", ")", "result", "[", "\"success\"", "]", ".", "append", "(", "item", ")", "return", "result" ]
b378966b30146a952f7953c23202fb5a1ddf81d9
valid
which
Identify the location of an executable file.
setup.py
def which(program, win_allow_cross_arch=True): """Identify the location of an executable file.""" def is_exe(path): return os.path.isfile(path) and os.access(path, os.X_OK) def _get_path_list(): return os.environ['PATH'].split(os.pathsep) if os.name == 'nt': def find_exe(program): root, ext = os.path.splitext(program) if ext: if is_exe(program): return program else: for ext in os.environ['PATHEXT'].split(os.pathsep): program_path = root + ext.lower() if is_exe(program_path): return program_path return None def get_path_list(): paths = _get_path_list() if win_allow_cross_arch: alt_sys_path = os.path.expandvars(r"$WINDIR\Sysnative") if os.path.isdir(alt_sys_path): paths.insert(0, alt_sys_path) else: alt_sys_path = os.path.expandvars(r"$WINDIR\SysWOW64") if os.path.isdir(alt_sys_path): paths.append(alt_sys_path) return paths else: def find_exe(program): return program if is_exe(program) else None get_path_list = _get_path_list if os.path.split(program)[0]: program_path = find_exe(program) if program_path: return program_path else: for path in get_path_list(): program_path = find_exe(os.path.join(path, program)) if program_path: return program_path return None
def which(program, win_allow_cross_arch=True): """Identify the location of an executable file.""" def is_exe(path): return os.path.isfile(path) and os.access(path, os.X_OK) def _get_path_list(): return os.environ['PATH'].split(os.pathsep) if os.name == 'nt': def find_exe(program): root, ext = os.path.splitext(program) if ext: if is_exe(program): return program else: for ext in os.environ['PATHEXT'].split(os.pathsep): program_path = root + ext.lower() if is_exe(program_path): return program_path return None def get_path_list(): paths = _get_path_list() if win_allow_cross_arch: alt_sys_path = os.path.expandvars(r"$WINDIR\Sysnative") if os.path.isdir(alt_sys_path): paths.insert(0, alt_sys_path) else: alt_sys_path = os.path.expandvars(r"$WINDIR\SysWOW64") if os.path.isdir(alt_sys_path): paths.append(alt_sys_path) return paths else: def find_exe(program): return program if is_exe(program) else None get_path_list = _get_path_list if os.path.split(program)[0]: program_path = find_exe(program) if program_path: return program_path else: for path in get_path_list(): program_path = find_exe(os.path.join(path, program)) if program_path: return program_path return None
[ "Identify", "the", "location", "of", "an", "executable", "file", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L136-L184
[ "def", "which", "(", "program", ",", "win_allow_cross_arch", "=", "True", ")", ":", "def", "is_exe", "(", "path", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "path", ")", "and", "os", ".", "access", "(", "path", ",", "os", ".", "X_OK", ")", "def", "_get_path_list", "(", ")", ":", "return", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "pathsep", ")", "if", "os", ".", "name", "==", "'nt'", ":", "def", "find_exe", "(", "program", ")", ":", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "program", ")", "if", "ext", ":", "if", "is_exe", "(", "program", ")", ":", "return", "program", "else", ":", "for", "ext", "in", "os", ".", "environ", "[", "'PATHEXT'", "]", ".", "split", "(", "os", ".", "pathsep", ")", ":", "program_path", "=", "root", "+", "ext", ".", "lower", "(", ")", "if", "is_exe", "(", "program_path", ")", ":", "return", "program_path", "return", "None", "def", "get_path_list", "(", ")", ":", "paths", "=", "_get_path_list", "(", ")", "if", "win_allow_cross_arch", ":", "alt_sys_path", "=", "os", ".", "path", ".", "expandvars", "(", "r\"$WINDIR\\Sysnative\"", ")", "if", "os", ".", "path", ".", "isdir", "(", "alt_sys_path", ")", ":", "paths", ".", "insert", "(", "0", ",", "alt_sys_path", ")", "else", ":", "alt_sys_path", "=", "os", ".", "path", ".", "expandvars", "(", "r\"$WINDIR\\SysWOW64\"", ")", "if", "os", ".", "path", ".", "isdir", "(", "alt_sys_path", ")", ":", "paths", ".", "append", "(", "alt_sys_path", ")", "return", "paths", "else", ":", "def", "find_exe", "(", "program", ")", ":", "return", "program", "if", "is_exe", "(", "program", ")", "else", "None", "get_path_list", "=", "_get_path_list", "if", "os", ".", "path", ".", "split", "(", "program", ")", "[", "0", "]", ":", "program_path", "=", "find_exe", "(", "program", ")", "if", "program_path", ":", "return", "program_path", "else", ":", "for", "path", "in", "get_path_list", "(", ")", ":", "program_path", "=", "find_exe", "(", "os", ".", "path", ".", "join", "(", "path", ",", "program", ")", ")", "if", "program_path", ":", "return", "program_path", "return", "None" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
split_multiline
Split a multiline string into a list, excluding blank lines.
setup.py
def split_multiline(value): """Split a multiline string into a list, excluding blank lines.""" return [element for element in (line.strip() for line in value.split('\n')) if element]
def split_multiline(value): """Split a multiline string into a list, excluding blank lines.""" return [element for element in (line.strip() for line in value.split('\n')) if element]
[ "Split", "a", "multiline", "string", "into", "a", "list", "excluding", "blank", "lines", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L187-L190
[ "def", "split_multiline", "(", "value", ")", ":", "return", "[", "element", "for", "element", "in", "(", "line", ".", "strip", "(", ")", "for", "line", "in", "value", ".", "split", "(", "'\\n'", ")", ")", "if", "element", "]" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
split_elements
Split a string with comma or space-separated elements into a list.
setup.py
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" items = [v.strip() for v in value.split(',')] if len(items) == 1: items = value.split() return items
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" items = [v.strip() for v in value.split(',')] if len(items) == 1: items = value.split() return items
[ "Split", "a", "string", "with", "comma", "or", "space", "-", "separated", "elements", "into", "a", "list", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L193-L198
[ "def", "split_elements", "(", "value", ")", ":", "items", "=", "[", "v", ".", "strip", "(", ")", "for", "v", "in", "value", ".", "split", "(", "','", ")", "]", "if", "len", "(", "items", ")", "==", "1", ":", "items", "=", "value", ".", "split", "(", ")", "return", "items" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
eval_environ
Evaluate environment markers.
setup.py
def eval_environ(value): """Evaluate environment markers.""" def eval_environ_str(value): parts = value.split(';') if len(parts) < 2: return value expr = parts[1].lstrip() if not re.match("^((\\w+(\\.\\w+)?|'.*?'|\".*?\")\\s+" '(in|==|!=|not in)\\s+' "(\\w+(\\.\\w+)?|'.*?'|\".*?\")" '(\\s+(or|and)\\s+)?)+$', expr): raise ValueError('bad environment marker: %r' % expr) expr = re.sub(r"(platform\.\w+)", r"\1()", expr) return parts[0] if eval(expr) else '' if isinstance(value, list): new_value = [] for element in value: element = eval_environ_str(element) if element: new_value.append(element) elif isinstance(value, str): new_value = eval_environ_str(value) else: new_value = value return new_value
def eval_environ(value): """Evaluate environment markers.""" def eval_environ_str(value): parts = value.split(';') if len(parts) < 2: return value expr = parts[1].lstrip() if not re.match("^((\\w+(\\.\\w+)?|'.*?'|\".*?\")\\s+" '(in|==|!=|not in)\\s+' "(\\w+(\\.\\w+)?|'.*?'|\".*?\")" '(\\s+(or|and)\\s+)?)+$', expr): raise ValueError('bad environment marker: %r' % expr) expr = re.sub(r"(platform\.\w+)", r"\1()", expr) return parts[0] if eval(expr) else '' if isinstance(value, list): new_value = [] for element in value: element = eval_environ_str(element) if element: new_value.append(element) elif isinstance(value, str): new_value = eval_environ_str(value) else: new_value = value return new_value
[ "Evaluate", "environment", "markers", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L201-L227
[ "def", "eval_environ", "(", "value", ")", ":", "def", "eval_environ_str", "(", "value", ")", ":", "parts", "=", "value", ".", "split", "(", "';'", ")", "if", "len", "(", "parts", ")", "<", "2", ":", "return", "value", "expr", "=", "parts", "[", "1", "]", ".", "lstrip", "(", ")", "if", "not", "re", ".", "match", "(", "\"^((\\\\w+(\\\\.\\\\w+)?|'.*?'|\\\".*?\\\")\\\\s+\"", "'(in|==|!=|not in)\\\\s+'", "\"(\\\\w+(\\\\.\\\\w+)?|'.*?'|\\\".*?\\\")\"", "'(\\\\s+(or|and)\\\\s+)?)+$'", ",", "expr", ")", ":", "raise", "ValueError", "(", "'bad environment marker: %r'", "%", "expr", ")", "expr", "=", "re", ".", "sub", "(", "r\"(platform\\.\\w+)\"", ",", "r\"\\1()\"", ",", "expr", ")", "return", "parts", "[", "0", "]", "if", "eval", "(", "expr", ")", "else", "''", "if", "isinstance", "(", "value", ",", "list", ")", ":", "new_value", "=", "[", "]", "for", "element", "in", "value", ":", "element", "=", "eval_environ_str", "(", "element", ")", "if", "element", ":", "new_value", ".", "append", "(", "element", ")", "elif", "isinstance", "(", "value", ",", "str", ")", ":", "new_value", "=", "eval_environ_str", "(", "value", ")", "else", ":", "new_value", "=", "value", "return", "new_value" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
get_cfg_value
Get configuration value.
setup.py
def get_cfg_value(config, section, option): """Get configuration value.""" try: value = config[section][option] except KeyError: if (section, option) in MULTI_OPTIONS: return [] else: return '' if (section, option) in MULTI_OPTIONS: value = split_multiline(value) if (section, option) in ENVIRON_OPTIONS: value = eval_environ(value) return value
def get_cfg_value(config, section, option): """Get configuration value.""" try: value = config[section][option] except KeyError: if (section, option) in MULTI_OPTIONS: return [] else: return '' if (section, option) in MULTI_OPTIONS: value = split_multiline(value) if (section, option) in ENVIRON_OPTIONS: value = eval_environ(value) return value
[ "Get", "configuration", "value", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L230-L243
[ "def", "get_cfg_value", "(", "config", ",", "section", ",", "option", ")", ":", "try", ":", "value", "=", "config", "[", "section", "]", "[", "option", "]", "except", "KeyError", ":", "if", "(", "section", ",", "option", ")", "in", "MULTI_OPTIONS", ":", "return", "[", "]", "else", ":", "return", "''", "if", "(", "section", ",", "option", ")", "in", "MULTI_OPTIONS", ":", "value", "=", "split_multiline", "(", "value", ")", "if", "(", "section", ",", "option", ")", "in", "ENVIRON_OPTIONS", ":", "value", "=", "eval_environ", "(", "value", ")", "return", "value" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
set_cfg_value
Set configuration value.
setup.py
def set_cfg_value(config, section, option, value): """Set configuration value.""" if isinstance(value, list): value = '\n'.join(value) config[section][option] = value
def set_cfg_value(config, section, option, value): """Set configuration value.""" if isinstance(value, list): value = '\n'.join(value) config[section][option] = value
[ "Set", "configuration", "value", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L246-L250
[ "def", "set_cfg_value", "(", "config", ",", "section", ",", "option", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "'\\n'", ".", "join", "(", "value", ")", "config", "[", "section", "]", "[", "option", "]", "=", "value" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
cfg_to_args
Compatibility helper to use setup.cfg in setup.py.
setup.py
def cfg_to_args(config): """Compatibility helper to use setup.cfg in setup.py.""" kwargs = {} opts_to_args = { 'metadata': [ ('name', 'name'), ('author', 'author'), ('author-email', 'author_email'), ('maintainer', 'maintainer'), ('maintainer-email', 'maintainer_email'), ('home-page', 'url'), ('summary', 'description'), ('description', 'long_description'), ('download-url', 'download_url'), ('classifier', 'classifiers'), ('platform', 'platforms'), ('license', 'license'), ('keywords', 'keywords'), ], 'files': [ ('packages_root', 'package_dir'), ('packages', 'packages'), ('modules', 'py_modules'), ('scripts', 'scripts'), ('package_data', 'package_data'), ('data_files', 'data_files'), ], } opts_to_args['metadata'].append(('requires-dist', 'install_requires')) if IS_PY2K and not which('3to2'): kwargs['setup_requires'] = ['3to2'] kwargs['zip_safe'] = False for section in opts_to_args: for option, argname in opts_to_args[section]: value = get_cfg_value(config, section, option) if value: kwargs[argname] = value if 'long_description' not in kwargs: kwargs['long_description'] = read_description_file(config) if 'package_dir' in kwargs: kwargs['package_dir'] = {'': kwargs['package_dir']} if 'keywords' in kwargs: kwargs['keywords'] = split_elements(kwargs['keywords']) if 'package_data' in kwargs: kwargs['package_data'] = get_package_data(kwargs['package_data']) if 'data_files' in kwargs: kwargs['data_files'] = get_data_files(kwargs['data_files']) kwargs['version'] = get_version() if not IS_PY2K: kwargs['test_suite'] = 'test' return kwargs
def cfg_to_args(config): """Compatibility helper to use setup.cfg in setup.py.""" kwargs = {} opts_to_args = { 'metadata': [ ('name', 'name'), ('author', 'author'), ('author-email', 'author_email'), ('maintainer', 'maintainer'), ('maintainer-email', 'maintainer_email'), ('home-page', 'url'), ('summary', 'description'), ('description', 'long_description'), ('download-url', 'download_url'), ('classifier', 'classifiers'), ('platform', 'platforms'), ('license', 'license'), ('keywords', 'keywords'), ], 'files': [ ('packages_root', 'package_dir'), ('packages', 'packages'), ('modules', 'py_modules'), ('scripts', 'scripts'), ('package_data', 'package_data'), ('data_files', 'data_files'), ], } opts_to_args['metadata'].append(('requires-dist', 'install_requires')) if IS_PY2K and not which('3to2'): kwargs['setup_requires'] = ['3to2'] kwargs['zip_safe'] = False for section in opts_to_args: for option, argname in opts_to_args[section]: value = get_cfg_value(config, section, option) if value: kwargs[argname] = value if 'long_description' not in kwargs: kwargs['long_description'] = read_description_file(config) if 'package_dir' in kwargs: kwargs['package_dir'] = {'': kwargs['package_dir']} if 'keywords' in kwargs: kwargs['keywords'] = split_elements(kwargs['keywords']) if 'package_data' in kwargs: kwargs['package_data'] = get_package_data(kwargs['package_data']) if 'data_files' in kwargs: kwargs['data_files'] = get_data_files(kwargs['data_files']) kwargs['version'] = get_version() if not IS_PY2K: kwargs['test_suite'] = 'test' return kwargs
[ "Compatibility", "helper", "to", "use", "setup", ".", "cfg", "in", "setup", ".", "py", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L300-L360
[ "def", "cfg_to_args", "(", "config", ")", ":", "kwargs", "=", "{", "}", "opts_to_args", "=", "{", "'metadata'", ":", "[", "(", "'name'", ",", "'name'", ")", ",", "(", "'author'", ",", "'author'", ")", ",", "(", "'author-email'", ",", "'author_email'", ")", ",", "(", "'maintainer'", ",", "'maintainer'", ")", ",", "(", "'maintainer-email'", ",", "'maintainer_email'", ")", ",", "(", "'home-page'", ",", "'url'", ")", ",", "(", "'summary'", ",", "'description'", ")", ",", "(", "'description'", ",", "'long_description'", ")", ",", "(", "'download-url'", ",", "'download_url'", ")", ",", "(", "'classifier'", ",", "'classifiers'", ")", ",", "(", "'platform'", ",", "'platforms'", ")", ",", "(", "'license'", ",", "'license'", ")", ",", "(", "'keywords'", ",", "'keywords'", ")", ",", "]", ",", "'files'", ":", "[", "(", "'packages_root'", ",", "'package_dir'", ")", ",", "(", "'packages'", ",", "'packages'", ")", ",", "(", "'modules'", ",", "'py_modules'", ")", ",", "(", "'scripts'", ",", "'scripts'", ")", ",", "(", "'package_data'", ",", "'package_data'", ")", ",", "(", "'data_files'", ",", "'data_files'", ")", ",", "]", ",", "}", "opts_to_args", "[", "'metadata'", "]", ".", "append", "(", "(", "'requires-dist'", ",", "'install_requires'", ")", ")", "if", "IS_PY2K", "and", "not", "which", "(", "'3to2'", ")", ":", "kwargs", "[", "'setup_requires'", "]", "=", "[", "'3to2'", "]", "kwargs", "[", "'zip_safe'", "]", "=", "False", "for", "section", "in", "opts_to_args", ":", "for", "option", ",", "argname", "in", "opts_to_args", "[", "section", "]", ":", "value", "=", "get_cfg_value", "(", "config", ",", "section", ",", "option", ")", "if", "value", ":", "kwargs", "[", "argname", "]", "=", "value", "if", "'long_description'", "not", "in", "kwargs", ":", "kwargs", "[", "'long_description'", "]", "=", "read_description_file", "(", "config", ")", "if", "'package_dir'", "in", "kwargs", ":", "kwargs", "[", "'package_dir'", "]", "=", "{", "''", ":", "kwargs", "[", "'package_dir'", "]", "}", "if", "'keywords'", "in", "kwargs", ":", "kwargs", "[", "'keywords'", "]", "=", "split_elements", "(", "kwargs", "[", "'keywords'", "]", ")", "if", "'package_data'", "in", "kwargs", ":", "kwargs", "[", "'package_data'", "]", "=", "get_package_data", "(", "kwargs", "[", "'package_data'", "]", ")", "if", "'data_files'", "in", "kwargs", ":", "kwargs", "[", "'data_files'", "]", "=", "get_data_files", "(", "kwargs", "[", "'data_files'", "]", ")", "kwargs", "[", "'version'", "]", "=", "get_version", "(", ")", "if", "not", "IS_PY2K", ":", "kwargs", "[", "'test_suite'", "]", "=", "'test'", "return", "kwargs" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
run_3to2
Convert Python files using lib3to2.
setup.py
def run_3to2(args=None): """Convert Python files using lib3to2.""" args = BASE_ARGS_3TO2 if args is None else BASE_ARGS_3TO2 + args try: proc = subprocess.Popen(['3to2'] + args, stderr=subprocess.PIPE) except OSError: for path in glob.glob('*.egg'): if os.path.isdir(path) and path not in sys.path: sys.path.append(path) try: from lib3to2.main import main as lib3to2_main except ImportError: raise OSError('3to2 script is unavailable.') else: if lib3to2_main('lib3to2.fixes', args): raise Exception('lib3to2 parsing error') else: # HACK: workaround for 3to2 never returning non-zero # when using the -j option. num_errors = 0 while proc.poll() is None: line = proc.stderr.readline() sys.stderr.write(line) num_errors += line.count(': ParseError: ') if proc.returncode or num_errors: raise Exception('lib3to2 parsing error')
def run_3to2(args=None): """Convert Python files using lib3to2.""" args = BASE_ARGS_3TO2 if args is None else BASE_ARGS_3TO2 + args try: proc = subprocess.Popen(['3to2'] + args, stderr=subprocess.PIPE) except OSError: for path in glob.glob('*.egg'): if os.path.isdir(path) and path not in sys.path: sys.path.append(path) try: from lib3to2.main import main as lib3to2_main except ImportError: raise OSError('3to2 script is unavailable.') else: if lib3to2_main('lib3to2.fixes', args): raise Exception('lib3to2 parsing error') else: # HACK: workaround for 3to2 never returning non-zero # when using the -j option. num_errors = 0 while proc.poll() is None: line = proc.stderr.readline() sys.stderr.write(line) num_errors += line.count(': ParseError: ') if proc.returncode or num_errors: raise Exception('lib3to2 parsing error')
[ "Convert", "Python", "files", "using", "lib3to2", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L363-L388
[ "def", "run_3to2", "(", "args", "=", "None", ")", ":", "args", "=", "BASE_ARGS_3TO2", "if", "args", "is", "None", "else", "BASE_ARGS_3TO2", "+", "args", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'3to2'", "]", "+", "args", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "except", "OSError", ":", "for", "path", "in", "glob", ".", "glob", "(", "'*.egg'", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "path", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "append", "(", "path", ")", "try", ":", "from", "lib3to2", ".", "main", "import", "main", "as", "lib3to2_main", "except", "ImportError", ":", "raise", "OSError", "(", "'3to2 script is unavailable.'", ")", "else", ":", "if", "lib3to2_main", "(", "'lib3to2.fixes'", ",", "args", ")", ":", "raise", "Exception", "(", "'lib3to2 parsing error'", ")", "else", ":", "# HACK: workaround for 3to2 never returning non-zero", "# when using the -j option.", "num_errors", "=", "0", "while", "proc", ".", "poll", "(", ")", "is", "None", ":", "line", "=", "proc", ".", "stderr", ".", "readline", "(", ")", "sys", ".", "stderr", ".", "write", "(", "line", ")", "num_errors", "+=", "line", ".", "count", "(", "': ParseError: '", ")", "if", "proc", ".", "returncode", "or", "num_errors", ":", "raise", "Exception", "(", "'lib3to2 parsing error'", ")" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
write_py2k_header
Write Python 2 shebang and add encoding cookie if needed.
setup.py
def write_py2k_header(file_list): """Write Python 2 shebang and add encoding cookie if needed.""" if not isinstance(file_list, list): file_list = [file_list] python_re = re.compile(br"^(#!.*\bpython)(.*)([\r\n]+)$") coding_re = re.compile(br"coding[:=]\s*([-\w.]+)") new_line_re = re.compile(br"([\r\n]+)$") version_3 = LooseVersion('3') for file in file_list: if not os.path.getsize(file): continue rewrite_needed = False python_found = False coding_found = False lines = [] f = open(file, 'rb') try: while len(lines) < 2: line = f.readline() match = python_re.match(line) if match: python_found = True version = LooseVersion(match.group(2).decode() or '2') try: version_test = version >= version_3 except TypeError: version_test = True if version_test: line = python_re.sub(br"\g<1>2\g<3>", line) rewrite_needed = True elif coding_re.search(line): coding_found = True lines.append(line) if not coding_found: match = new_line_re.search(lines[0]) newline = match.group(1) if match else b"\n" line = b"# -*- coding: utf-8 -*-" + newline lines.insert(1 if python_found else 0, line) rewrite_needed = True if rewrite_needed: lines += f.readlines() finally: f.close() if rewrite_needed: f = open(file, 'wb') try: f.writelines(lines) finally: f.close()
def write_py2k_header(file_list): """Write Python 2 shebang and add encoding cookie if needed.""" if not isinstance(file_list, list): file_list = [file_list] python_re = re.compile(br"^(#!.*\bpython)(.*)([\r\n]+)$") coding_re = re.compile(br"coding[:=]\s*([-\w.]+)") new_line_re = re.compile(br"([\r\n]+)$") version_3 = LooseVersion('3') for file in file_list: if not os.path.getsize(file): continue rewrite_needed = False python_found = False coding_found = False lines = [] f = open(file, 'rb') try: while len(lines) < 2: line = f.readline() match = python_re.match(line) if match: python_found = True version = LooseVersion(match.group(2).decode() or '2') try: version_test = version >= version_3 except TypeError: version_test = True if version_test: line = python_re.sub(br"\g<1>2\g<3>", line) rewrite_needed = True elif coding_re.search(line): coding_found = True lines.append(line) if not coding_found: match = new_line_re.search(lines[0]) newline = match.group(1) if match else b"\n" line = b"# -*- coding: utf-8 -*-" + newline lines.insert(1 if python_found else 0, line) rewrite_needed = True if rewrite_needed: lines += f.readlines() finally: f.close() if rewrite_needed: f = open(file, 'wb') try: f.writelines(lines) finally: f.close()
[ "Write", "Python", "2", "shebang", "and", "add", "encoding", "cookie", "if", "needed", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/setup.py#L391-L444
[ "def", "write_py2k_header", "(", "file_list", ")", ":", "if", "not", "isinstance", "(", "file_list", ",", "list", ")", ":", "file_list", "=", "[", "file_list", "]", "python_re", "=", "re", ".", "compile", "(", "br\"^(#!.*\\bpython)(.*)([\\r\\n]+)$\"", ")", "coding_re", "=", "re", ".", "compile", "(", "br\"coding[:=]\\s*([-\\w.]+)\"", ")", "new_line_re", "=", "re", ".", "compile", "(", "br\"([\\r\\n]+)$\"", ")", "version_3", "=", "LooseVersion", "(", "'3'", ")", "for", "file", "in", "file_list", ":", "if", "not", "os", ".", "path", ".", "getsize", "(", "file", ")", ":", "continue", "rewrite_needed", "=", "False", "python_found", "=", "False", "coding_found", "=", "False", "lines", "=", "[", "]", "f", "=", "open", "(", "file", ",", "'rb'", ")", "try", ":", "while", "len", "(", "lines", ")", "<", "2", ":", "line", "=", "f", ".", "readline", "(", ")", "match", "=", "python_re", ".", "match", "(", "line", ")", "if", "match", ":", "python_found", "=", "True", "version", "=", "LooseVersion", "(", "match", ".", "group", "(", "2", ")", ".", "decode", "(", ")", "or", "'2'", ")", "try", ":", "version_test", "=", "version", ">=", "version_3", "except", "TypeError", ":", "version_test", "=", "True", "if", "version_test", ":", "line", "=", "python_re", ".", "sub", "(", "br\"\\g<1>2\\g<3>\"", ",", "line", ")", "rewrite_needed", "=", "True", "elif", "coding_re", ".", "search", "(", "line", ")", ":", "coding_found", "=", "True", "lines", ".", "append", "(", "line", ")", "if", "not", "coding_found", ":", "match", "=", "new_line_re", ".", "search", "(", "lines", "[", "0", "]", ")", "newline", "=", "match", ".", "group", "(", "1", ")", "if", "match", "else", "b\"\\n\"", "line", "=", "b\"# -*- coding: utf-8 -*-\"", "+", "newline", "lines", ".", "insert", "(", "1", "if", "python_found", "else", "0", ",", "line", ")", "rewrite_needed", "=", "True", "if", "rewrite_needed", ":", "lines", "+=", "f", ".", "readlines", "(", ")", "finally", ":", "f", ".", "close", "(", ")", "if", "rewrite_needed", ":", "f", "=", "open", "(", "file", ",", "'wb'", ")", "try", ":", "f", ".", "writelines", "(", "lines", ")", "finally", ":", "f", ".", "close", "(", ")" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
which
Identify the location of an executable file.
language_check/which.py
def which(program): """Identify the location of an executable file.""" if os.path.split(program)[0]: program_path = find_exe(program) if program_path: return program_path else: for path in get_path_list(): program_path = find_exe(os.path.join(path, program)) if program_path: return program_path return None
def which(program): """Identify the location of an executable file.""" if os.path.split(program)[0]: program_path = find_exe(program) if program_path: return program_path else: for path in get_path_list(): program_path = find_exe(os.path.join(path, program)) if program_path: return program_path return None
[ "Identify", "the", "location", "of", "an", "executable", "file", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/which.py#L14-L25
[ "def", "which", "(", "program", ")", ":", "if", "os", ".", "path", ".", "split", "(", "program", ")", "[", "0", "]", ":", "program_path", "=", "find_exe", "(", "program", ")", "if", "program_path", ":", "return", "program_path", "else", ":", "for", "path", "in", "get_path_list", "(", ")", ":", "program_path", "=", "find_exe", "(", "os", ".", "path", ".", "join", "(", "path", ",", "program", ")", ")", "if", "program_path", ":", "return", "program_path", "return", "None" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
correct
Automatically apply suggestions to the text.
language_check/__init__.py
def correct(text: str, matches: [Match]) -> str: """Automatically apply suggestions to the text.""" ltext = list(text) matches = [match for match in matches if match.replacements] errors = [ltext[match.offset:match.offset + match.errorlength] for match in matches] correct_offset = 0 for n, match in enumerate(matches): frompos, topos = (correct_offset + match.offset, correct_offset + match.offset + match.errorlength) if ltext[frompos:topos] != errors[n]: continue repl = match.replacements[0] ltext[frompos:topos] = list(repl) correct_offset += len(repl) - len(errors[n]) return ''.join(ltext)
def correct(text: str, matches: [Match]) -> str: """Automatically apply suggestions to the text.""" ltext = list(text) matches = [match for match in matches if match.replacements] errors = [ltext[match.offset:match.offset + match.errorlength] for match in matches] correct_offset = 0 for n, match in enumerate(matches): frompos, topos = (correct_offset + match.offset, correct_offset + match.offset + match.errorlength) if ltext[frompos:topos] != errors[n]: continue repl = match.replacements[0] ltext[frompos:topos] = list(repl) correct_offset += len(repl) - len(errors[n]) return ''.join(ltext)
[ "Automatically", "apply", "suggestions", "to", "the", "text", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L493-L508
[ "def", "correct", "(", "text", ":", "str", ",", "matches", ":", "[", "Match", "]", ")", "->", "str", ":", "ltext", "=", "list", "(", "text", ")", "matches", "=", "[", "match", "for", "match", "in", "matches", "if", "match", ".", "replacements", "]", "errors", "=", "[", "ltext", "[", "match", ".", "offset", ":", "match", ".", "offset", "+", "match", ".", "errorlength", "]", "for", "match", "in", "matches", "]", "correct_offset", "=", "0", "for", "n", ",", "match", "in", "enumerate", "(", "matches", ")", ":", "frompos", ",", "topos", "=", "(", "correct_offset", "+", "match", ".", "offset", ",", "correct_offset", "+", "match", ".", "offset", "+", "match", ".", "errorlength", ")", "if", "ltext", "[", "frompos", ":", "topos", "]", "!=", "errors", "[", "n", "]", ":", "continue", "repl", "=", "match", ".", "replacements", "[", "0", "]", "ltext", "[", "frompos", ":", "topos", "]", "=", "list", "(", "repl", ")", "correct_offset", "+=", "len", "(", "repl", ")", "-", "len", "(", "errors", "[", "n", "]", ")", "return", "''", ".", "join", "(", "ltext", ")" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
get_version
Get LanguageTool version.
language_check/__init__.py
def get_version(): """Get LanguageTool version.""" version = _get_attrib().get('version') if not version: match = re.search(r"LanguageTool-?.*?(\S+)$", get_directory()) if match: version = match.group(1) return version
def get_version(): """Get LanguageTool version.""" version = _get_attrib().get('version') if not version: match = re.search(r"LanguageTool-?.*?(\S+)$", get_directory()) if match: version = match.group(1) return version
[ "Get", "LanguageTool", "version", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L520-L527
[ "def", "get_version", "(", ")", ":", "version", "=", "_get_attrib", "(", ")", ".", "get", "(", "'version'", ")", "if", "not", "version", ":", "match", "=", "re", ".", "search", "(", "r\"LanguageTool-?.*?(\\S+)$\"", ",", "get_directory", "(", ")", ")", "if", "match", ":", "version", "=", "match", ".", "group", "(", "1", ")", "return", "version" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
get_languages
Get supported languages.
language_check/__init__.py
def get_languages() -> set: """Get supported languages.""" try: languages = cache['languages'] except KeyError: languages = LanguageTool._get_languages() cache['languages'] = languages return languages
def get_languages() -> set: """Get supported languages.""" try: languages = cache['languages'] except KeyError: languages = LanguageTool._get_languages() cache['languages'] = languages return languages
[ "Get", "supported", "languages", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L535-L542
[ "def", "get_languages", "(", ")", "->", "set", ":", "try", ":", "languages", "=", "cache", "[", "'languages'", "]", "except", "KeyError", ":", "languages", "=", "LanguageTool", ".", "_get_languages", "(", ")", "cache", "[", "'languages'", "]", "=", "languages", "return", "languages" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
get_directory
Get LanguageTool directory.
language_check/__init__.py
def get_directory(): """Get LanguageTool directory.""" try: language_check_dir = cache['language_check_dir'] except KeyError: def version_key(string): return [int(e) if e.isdigit() else e for e in re.split(r"(\d+)", string)] def get_lt_dir(base_dir): paths = [ path for path in glob.glob(os.path.join(base_dir, 'LanguageTool*')) if os.path.isdir(path) ] return max(paths, key=version_key) if paths else None base_dir = os.path.dirname(sys.argv[0]) language_check_dir = get_lt_dir(base_dir) if not language_check_dir: try: base_dir = os.path.dirname(os.path.abspath(__file__)) except NameError: pass else: language_check_dir = get_lt_dir(base_dir) if not language_check_dir: raise PathError("can't find LanguageTool directory in {!r}" .format(base_dir)) cache['language_check_dir'] = language_check_dir return language_check_dir
def get_directory(): """Get LanguageTool directory.""" try: language_check_dir = cache['language_check_dir'] except KeyError: def version_key(string): return [int(e) if e.isdigit() else e for e in re.split(r"(\d+)", string)] def get_lt_dir(base_dir): paths = [ path for path in glob.glob(os.path.join(base_dir, 'LanguageTool*')) if os.path.isdir(path) ] return max(paths, key=version_key) if paths else None base_dir = os.path.dirname(sys.argv[0]) language_check_dir = get_lt_dir(base_dir) if not language_check_dir: try: base_dir = os.path.dirname(os.path.abspath(__file__)) except NameError: pass else: language_check_dir = get_lt_dir(base_dir) if not language_check_dir: raise PathError("can't find LanguageTool directory in {!r}" .format(base_dir)) cache['language_check_dir'] = language_check_dir return language_check_dir
[ "Get", "LanguageTool", "directory", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L545-L575
[ "def", "get_directory", "(", ")", ":", "try", ":", "language_check_dir", "=", "cache", "[", "'language_check_dir'", "]", "except", "KeyError", ":", "def", "version_key", "(", "string", ")", ":", "return", "[", "int", "(", "e", ")", "if", "e", ".", "isdigit", "(", ")", "else", "e", "for", "e", "in", "re", ".", "split", "(", "r\"(\\d+)\"", ",", "string", ")", "]", "def", "get_lt_dir", "(", "base_dir", ")", ":", "paths", "=", "[", "path", "for", "path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "base_dir", ",", "'LanguageTool*'", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "]", "return", "max", "(", "paths", ",", "key", "=", "version_key", ")", "if", "paths", "else", "None", "base_dir", "=", "os", ".", "path", ".", "dirname", "(", "sys", ".", "argv", "[", "0", "]", ")", "language_check_dir", "=", "get_lt_dir", "(", "base_dir", ")", "if", "not", "language_check_dir", ":", "try", ":", "base_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "except", "NameError", ":", "pass", "else", ":", "language_check_dir", "=", "get_lt_dir", "(", "base_dir", ")", "if", "not", "language_check_dir", ":", "raise", "PathError", "(", "\"can't find LanguageTool directory in {!r}\"", ".", "format", "(", "base_dir", ")", ")", "cache", "[", "'language_check_dir'", "]", "=", "language_check_dir", "return", "language_check_dir" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
set_directory
Set LanguageTool directory.
language_check/__init__.py
def set_directory(path=None): """Set LanguageTool directory.""" old_path = get_directory() terminate_server() cache.clear() if path: cache['language_check_dir'] = path try: get_jar_info() except Error: cache['language_check_dir'] = old_path raise
def set_directory(path=None): """Set LanguageTool directory.""" old_path = get_directory() terminate_server() cache.clear() if path: cache['language_check_dir'] = path try: get_jar_info() except Error: cache['language_check_dir'] = old_path raise
[ "Set", "LanguageTool", "directory", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L578-L589
[ "def", "set_directory", "(", "path", "=", "None", ")", ":", "old_path", "=", "get_directory", "(", ")", "terminate_server", "(", ")", "cache", ".", "clear", "(", ")", "if", "path", ":", "cache", "[", "'language_check_dir'", "]", "=", "path", "try", ":", "get_jar_info", "(", ")", "except", "Error", ":", "cache", "[", "'language_check_dir'", "]", "=", "old_path", "raise" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
LanguageTool.check
Match text against enabled rules.
language_check/__init__.py
def check(self, text: str, srctext=None) -> [Match]: """Match text against enabled rules.""" root = self._get_root(self._url, self._encode(text, srctext)) return [Match(e.attrib) for e in root if e.tag == 'error']
def check(self, text: str, srctext=None) -> [Match]: """Match text against enabled rules.""" root = self._get_root(self._url, self._encode(text, srctext)) return [Match(e.attrib) for e in root if e.tag == 'error']
[ "Match", "text", "against", "enabled", "rules", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L248-L251
[ "def", "check", "(", "self", ",", "text", ":", "str", ",", "srctext", "=", "None", ")", "->", "[", "Match", "]", ":", "root", "=", "self", ".", "_get_root", "(", "self", ".", "_url", ",", "self", ".", "_encode", "(", "text", ",", "srctext", ")", ")", "return", "[", "Match", "(", "e", ".", "attrib", ")", "for", "e", "in", "root", "if", "e", ".", "tag", "==", "'error'", "]" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
LanguageTool._check_api
Match text against enabled rules (result in XML format).
language_check/__init__.py
def _check_api(self, text: str, srctext=None) -> bytes: """Match text against enabled rules (result in XML format).""" root = self._get_root(self._url, self._encode(text, srctext)) return (b'<?xml version="1.0" encoding="UTF-8"?>\n' + ElementTree.tostring(root) + b"\n")
def _check_api(self, text: str, srctext=None) -> bytes: """Match text against enabled rules (result in XML format).""" root = self._get_root(self._url, self._encode(text, srctext)) return (b'<?xml version="1.0" encoding="UTF-8"?>\n' + ElementTree.tostring(root) + b"\n")
[ "Match", "text", "against", "enabled", "rules", "(", "result", "in", "XML", "format", ")", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L253-L257
[ "def", "_check_api", "(", "self", ",", "text", ":", "str", ",", "srctext", "=", "None", ")", "->", "bytes", ":", "root", "=", "self", ".", "_get_root", "(", "self", ".", "_url", ",", "self", ".", "_encode", "(", "text", ",", "srctext", ")", ")", "return", "(", "b'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n'", "+", "ElementTree", ".", "tostring", "(", "root", ")", "+", "b\"\\n\"", ")" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
LanguageTool.correct
Automatically apply suggestions to the text.
language_check/__init__.py
def correct(self, text: str, srctext=None) -> str: """Automatically apply suggestions to the text.""" return correct(text, self.check(text, srctext))
def correct(self, text: str, srctext=None) -> str: """Automatically apply suggestions to the text.""" return correct(text, self.check(text, srctext))
[ "Automatically", "apply", "suggestions", "to", "the", "text", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L273-L275
[ "def", "correct", "(", "self", ",", "text", ":", "str", ",", "srctext", "=", "None", ")", "->", "str", ":", "return", "correct", "(", "text", ",", "self", ".", "check", "(", "text", ",", "srctext", ")", ")" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
parse_java_version
Return Java version (major1, major2). >>> parse_java_version('''java version "1.6.0_65" ... Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609) ... Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)) ... ''') (1, 6) >>> parse_java_version(''' ... openjdk version "1.8.0_60" ... OpenJDK Runtime Environment (build 1.8.0_60-b27) ... OpenJDK 64-Bit Server VM (build 25.60-b23, mixed mode)) ... ''') (1, 8)
download_lt.py
def parse_java_version(version_text): """Return Java version (major1, major2). >>> parse_java_version('''java version "1.6.0_65" ... Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609) ... Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)) ... ''') (1, 6) >>> parse_java_version(''' ... openjdk version "1.8.0_60" ... OpenJDK Runtime Environment (build 1.8.0_60-b27) ... OpenJDK 64-Bit Server VM (build 25.60-b23, mixed mode)) ... ''') (1, 8) """ match = re.search(JAVA_VERSION_REGEX, version_text) if not match: raise SystemExit( 'Could not parse Java version from """{}""".'.format(version_text)) return (int(match.group('major1')), int(match.group('major2')))
def parse_java_version(version_text): """Return Java version (major1, major2). >>> parse_java_version('''java version "1.6.0_65" ... Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609) ... Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)) ... ''') (1, 6) >>> parse_java_version(''' ... openjdk version "1.8.0_60" ... OpenJDK Runtime Environment (build 1.8.0_60-b27) ... OpenJDK 64-Bit Server VM (build 25.60-b23, mixed mode)) ... ''') (1, 8) """ match = re.search(JAVA_VERSION_REGEX, version_text) if not match: raise SystemExit( 'Could not parse Java version from """{}""".'.format(version_text)) return (int(match.group('major1')), int(match.group('major2')))
[ "Return", "Java", "version", "(", "major1", "major2", ")", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/download_lt.py#L40-L62
[ "def", "parse_java_version", "(", "version_text", ")", ":", "match", "=", "re", ".", "search", "(", "JAVA_VERSION_REGEX", ",", "version_text", ")", "if", "not", "match", ":", "raise", "SystemExit", "(", "'Could not parse Java version from \"\"\"{}\"\"\".'", ".", "format", "(", "version_text", ")", ")", "return", "(", "int", "(", "match", ".", "group", "(", "'major1'", ")", ")", ",", "int", "(", "match", ".", "group", "(", "'major2'", ")", ")", ")" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
get_newest_possible_languagetool_version
Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, ... JAVA_7_COMPATIBLE_VERSION, ... LATEST_VERSION] True
download_lt.py
def get_newest_possible_languagetool_version(): """Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, ... JAVA_7_COMPATIBLE_VERSION, ... LATEST_VERSION] True """ java_path = find_executable('java') if not java_path: # Just ignore this and assume an old version of Java. It might not be # found because of a PATHEXT-related issue # (https://bugs.python.org/issue2200). return JAVA_6_COMPATIBLE_VERSION output = subprocess.check_output([java_path, '-version'], stderr=subprocess.STDOUT, universal_newlines=True) java_version = parse_java_version(output) if java_version >= (1, 8): return LATEST_VERSION elif java_version >= (1, 7): return JAVA_7_COMPATIBLE_VERSION elif java_version >= (1, 6): warn('language-check would be able to use a newer version of ' 'LanguageTool if you had Java 7 or newer installed') return JAVA_6_COMPATIBLE_VERSION else: raise SystemExit( 'You need at least Java 6 to use language-check')
def get_newest_possible_languagetool_version(): """Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, ... JAVA_7_COMPATIBLE_VERSION, ... LATEST_VERSION] True """ java_path = find_executable('java') if not java_path: # Just ignore this and assume an old version of Java. It might not be # found because of a PATHEXT-related issue # (https://bugs.python.org/issue2200). return JAVA_6_COMPATIBLE_VERSION output = subprocess.check_output([java_path, '-version'], stderr=subprocess.STDOUT, universal_newlines=True) java_version = parse_java_version(output) if java_version >= (1, 8): return LATEST_VERSION elif java_version >= (1, 7): return JAVA_7_COMPATIBLE_VERSION elif java_version >= (1, 6): warn('language-check would be able to use a newer version of ' 'LanguageTool if you had Java 7 or newer installed') return JAVA_6_COMPATIBLE_VERSION else: raise SystemExit( 'You need at least Java 6 to use language-check')
[ "Return", "newest", "compatible", "version", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/download_lt.py#L65-L98
[ "def", "get_newest_possible_languagetool_version", "(", ")", ":", "java_path", "=", "find_executable", "(", "'java'", ")", "if", "not", "java_path", ":", "# Just ignore this and assume an old version of Java. It might not be", "# found because of a PATHEXT-related issue", "# (https://bugs.python.org/issue2200).", "return", "JAVA_6_COMPATIBLE_VERSION", "output", "=", "subprocess", ".", "check_output", "(", "[", "java_path", ",", "'-version'", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "universal_newlines", "=", "True", ")", "java_version", "=", "parse_java_version", "(", "output", ")", "if", "java_version", ">=", "(", "1", ",", "8", ")", ":", "return", "LATEST_VERSION", "elif", "java_version", ">=", "(", "1", ",", "7", ")", ":", "return", "JAVA_7_COMPATIBLE_VERSION", "elif", "java_version", ">=", "(", "1", ",", "6", ")", ":", "warn", "(", "'language-check would be able to use a newer version of '", "'LanguageTool if you had Java 7 or newer installed'", ")", "return", "JAVA_6_COMPATIBLE_VERSION", "else", ":", "raise", "SystemExit", "(", "'You need at least Java 6 to use language-check'", ")" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
get_common_prefix
Get common directory in a zip file if any.
download_lt.py
def get_common_prefix(z): """Get common directory in a zip file if any.""" name_list = z.namelist() if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]): return name_list[0] return None
def get_common_prefix(z): """Get common directory in a zip file if any.""" name_list = z.namelist() if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]): return name_list[0] return None
[ "Get", "common", "directory", "in", "a", "zip", "file", "if", "any", "." ]
myint/language-check
python
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/download_lt.py#L101-L106
[ "def", "get_common_prefix", "(", "z", ")", ":", "name_list", "=", "z", ".", "namelist", "(", ")", "if", "name_list", "and", "all", "(", "n", ".", "startswith", "(", "name_list", "[", "0", "]", ")", "for", "n", "in", "name_list", "[", "1", ":", "]", ")", ":", "return", "name_list", "[", "0", "]", "return", "None" ]
58e419833ef28a9193fcaa21193616a8a14504a9
valid
_ProactorEventLoop._process_events
Process events from proactor.
asyncqt/_windows.py
def _process_events(self, events): """Process events from proactor.""" for f, callback, transferred, key, ov in events: try: self._logger.debug('Invoking event callback {}'.format(callback)) value = callback(transferred, key, ov) except OSError: self._logger.warning('Event callback failed', exc_info=sys.exc_info()) else: f.set_result(value)
def _process_events(self, events): """Process events from proactor.""" for f, callback, transferred, key, ov in events: try: self._logger.debug('Invoking event callback {}'.format(callback)) value = callback(transferred, key, ov) except OSError: self._logger.warning('Event callback failed', exc_info=sys.exc_info()) else: f.set_result(value)
[ "Process", "events", "from", "proactor", "." ]
gmarull/asyncqt
python
https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/_windows.py#L38-L47
[ "def", "_process_events", "(", "self", ",", "events", ")", ":", "for", "f", ",", "callback", ",", "transferred", ",", "key", ",", "ov", "in", "events", ":", "try", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking event callback {}'", ".", "format", "(", "callback", ")", ")", "value", "=", "callback", "(", "transferred", ",", "key", ",", "ov", ")", "except", "OSError", ":", "self", ".", "_logger", ".", "warning", "(", "'Event callback failed'", ",", "exc_info", "=", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "f", ".", "set_result", "(", "value", ")" ]
292e42c0bf799e5aeee099ee2cec27a810b01870
valid
asyncClose
Allow to run async code before application is closed.
asyncqt/__init__.py
def asyncClose(fn): """Allow to run async code before application is closed.""" @functools.wraps(fn) def wrapper(*args, **kwargs): f = asyncio.ensure_future(fn(*args, **kwargs)) while not f.done(): QApplication.instance().processEvents() return wrapper
def asyncClose(fn): """Allow to run async code before application is closed.""" @functools.wraps(fn) def wrapper(*args, **kwargs): f = asyncio.ensure_future(fn(*args, **kwargs)) while not f.done(): QApplication.instance().processEvents() return wrapper
[ "Allow", "to", "run", "async", "code", "before", "application", "is", "closed", "." ]
gmarull/asyncqt
python
https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/__init__.py#L627-L635
[ "def", "asyncClose", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "asyncio", ".", "ensure_future", "(", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "while", "not", "f", ".", "done", "(", ")", ":", "QApplication", ".", "instance", "(", ")", ".", "processEvents", "(", ")", "return", "wrapper" ]
292e42c0bf799e5aeee099ee2cec27a810b01870
valid
asyncSlot
Make a Qt async slot run on asyncio loop.
asyncqt/__init__.py
def asyncSlot(*args): """Make a Qt async slot run on asyncio loop.""" def outer_decorator(fn): @Slot(*args) @functools.wraps(fn) def wrapper(*args, **kwargs): asyncio.ensure_future(fn(*args, **kwargs)) return wrapper return outer_decorator
def asyncSlot(*args): """Make a Qt async slot run on asyncio loop.""" def outer_decorator(fn): @Slot(*args) @functools.wraps(fn) def wrapper(*args, **kwargs): asyncio.ensure_future(fn(*args, **kwargs)) return wrapper return outer_decorator
[ "Make", "a", "Qt", "async", "slot", "run", "on", "asyncio", "loop", "." ]
gmarull/asyncqt
python
https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/__init__.py#L638-L646
[ "def", "asyncSlot", "(", "*", "args", ")", ":", "def", "outer_decorator", "(", "fn", ")", ":", "@", "Slot", "(", "*", "args", ")", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "asyncio", ".", "ensure_future", "(", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "return", "wrapper", "return", "outer_decorator" ]
292e42c0bf799e5aeee099ee2cec27a810b01870
valid
with_logger
Class decorator to add a logger to a class.
asyncqt/_common.py
def with_logger(cls): """Class decorator to add a logger to a class.""" attr_name = '_logger' cls_name = cls.__qualname__ module = cls.__module__ if module is not None: cls_name = module + '.' + cls_name else: raise AssertionError setattr(cls, attr_name, logging.getLogger(cls_name)) return cls
def with_logger(cls): """Class decorator to add a logger to a class.""" attr_name = '_logger' cls_name = cls.__qualname__ module = cls.__module__ if module is not None: cls_name = module + '.' + cls_name else: raise AssertionError setattr(cls, attr_name, logging.getLogger(cls_name)) return cls
[ "Class", "decorator", "to", "add", "a", "logger", "to", "a", "class", "." ]
gmarull/asyncqt
python
https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/_common.py#L10-L20
[ "def", "with_logger", "(", "cls", ")", ":", "attr_name", "=", "'_logger'", "cls_name", "=", "cls", ".", "__qualname__", "module", "=", "cls", ".", "__module__", "if", "module", "is", "not", "None", ":", "cls_name", "=", "module", "+", "'.'", "+", "cls_name", "else", ":", "raise", "AssertionError", "setattr", "(", "cls", ",", "attr_name", ",", "logging", ".", "getLogger", "(", "cls_name", ")", ")", "return", "cls" ]
292e42c0bf799e5aeee099ee2cec27a810b01870
valid
_SelectorEventLoop._process_event
Selector has delivered us an event.
asyncqt/_unix.py
def _process_event(self, key, mask): """Selector has delivered us an event.""" self._logger.debug('Processing event with key {} and mask {}'.format(key, mask)) fileobj, (reader, writer) = key.fileobj, key.data if mask & selectors.EVENT_READ and reader is not None: if reader._cancelled: self.remove_reader(fileobj) else: self._logger.debug('Invoking reader callback: {}'.format(reader)) reader._run() if mask & selectors.EVENT_WRITE and writer is not None: if writer._cancelled: self.remove_writer(fileobj) else: self._logger.debug('Invoking writer callback: {}'.format(writer)) writer._run()
def _process_event(self, key, mask): """Selector has delivered us an event.""" self._logger.debug('Processing event with key {} and mask {}'.format(key, mask)) fileobj, (reader, writer) = key.fileobj, key.data if mask & selectors.EVENT_READ and reader is not None: if reader._cancelled: self.remove_reader(fileobj) else: self._logger.debug('Invoking reader callback: {}'.format(reader)) reader._run() if mask & selectors.EVENT_WRITE and writer is not None: if writer._cancelled: self.remove_writer(fileobj) else: self._logger.debug('Invoking writer callback: {}'.format(writer)) writer._run()
[ "Selector", "has", "delivered", "us", "an", "event", "." ]
gmarull/asyncqt
python
https://github.com/gmarull/asyncqt/blob/292e42c0bf799e5aeee099ee2cec27a810b01870/asyncqt/_unix.py#L206-L221
[ "def", "_process_event", "(", "self", ",", "key", ",", "mask", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Processing event with key {} and mask {}'", ".", "format", "(", "key", ",", "mask", ")", ")", "fileobj", ",", "(", "reader", ",", "writer", ")", "=", "key", ".", "fileobj", ",", "key", ".", "data", "if", "mask", "&", "selectors", ".", "EVENT_READ", "and", "reader", "is", "not", "None", ":", "if", "reader", ".", "_cancelled", ":", "self", ".", "remove_reader", "(", "fileobj", ")", "else", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking reader callback: {}'", ".", "format", "(", "reader", ")", ")", "reader", ".", "_run", "(", ")", "if", "mask", "&", "selectors", ".", "EVENT_WRITE", "and", "writer", "is", "not", "None", ":", "if", "writer", ".", "_cancelled", ":", "self", ".", "remove_writer", "(", "fileobj", ")", "else", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking writer callback: {}'", ".", "format", "(", "writer", ")", ")", "writer", ".", "_run", "(", ")" ]
292e42c0bf799e5aeee099ee2cec27a810b01870
valid
MibCompiler.addSources
Add more ASN.1 MIB source repositories. MibCompiler.compile will invoke each of configured source objects in order of their addition asking each to fetch MIB module specified by name. Args: sources: reader object(s) Returns: reference to itself (can be used for call chaining)
pysmi/compiler.py
def addSources(self, *sources): """Add more ASN.1 MIB source repositories. MibCompiler.compile will invoke each of configured source objects in order of their addition asking each to fetch MIB module specified by name. Args: sources: reader object(s) Returns: reference to itself (can be used for call chaining) """ self._sources.extend(sources) debug.logger & debug.flagCompiler and debug.logger( 'current MIB source(s): %s' % ', '.join([str(x) for x in self._sources])) return self
def addSources(self, *sources): """Add more ASN.1 MIB source repositories. MibCompiler.compile will invoke each of configured source objects in order of their addition asking each to fetch MIB module specified by name. Args: sources: reader object(s) Returns: reference to itself (can be used for call chaining) """ self._sources.extend(sources) debug.logger & debug.flagCompiler and debug.logger( 'current MIB source(s): %s' % ', '.join([str(x) for x in self._sources])) return self
[ "Add", "more", "ASN", ".", "1", "MIB", "source", "repositories", "." ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/compiler.py#L94-L113
[ "def", "addSources", "(", "self", ",", "*", "sources", ")", ":", "self", ".", "_sources", ".", "extend", "(", "sources", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'current MIB source(s): %s'", "%", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "_sources", "]", ")", ")", "return", "self" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
MibCompiler.addSearchers
Add more transformed MIBs repositories. MibCompiler.compile will invoke each of configured searcher objects in order of their addition asking each if already transformed MIB module already exists and is more recent than specified. Args: searchers: searcher object(s) Returns: reference to itself (can be used for call chaining)
pysmi/compiler.py
def addSearchers(self, *searchers): """Add more transformed MIBs repositories. MibCompiler.compile will invoke each of configured searcher objects in order of their addition asking each if already transformed MIB module already exists and is more recent than specified. Args: searchers: searcher object(s) Returns: reference to itself (can be used for call chaining) """ self._searchers.extend(searchers) debug.logger & debug.flagCompiler and debug.logger( 'current compiled MIBs location(s): %s' % ', '.join([str(x) for x in self._searchers])) return self
def addSearchers(self, *searchers): """Add more transformed MIBs repositories. MibCompiler.compile will invoke each of configured searcher objects in order of their addition asking each if already transformed MIB module already exists and is more recent than specified. Args: searchers: searcher object(s) Returns: reference to itself (can be used for call chaining) """ self._searchers.extend(searchers) debug.logger & debug.flagCompiler and debug.logger( 'current compiled MIBs location(s): %s' % ', '.join([str(x) for x in self._searchers])) return self
[ "Add", "more", "transformed", "MIBs", "repositories", "." ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/compiler.py#L115-L134
[ "def", "addSearchers", "(", "self", ",", "*", "searchers", ")", ":", "self", ".", "_searchers", ".", "extend", "(", "searchers", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'current compiled MIBs location(s): %s'", "%", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "_searchers", "]", ")", ")", "return", "self" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
MibCompiler.addBorrowers
Add more transformed MIBs repositories to borrow MIBs from. Whenever MibCompiler.compile encounters MIB module which neither of the *searchers* can find or fetched ASN.1 MIB module can not be parsed (due to syntax errors), these *borrowers* objects will be invoked in order of their addition asking each if already transformed MIB can be fetched (borrowed). Args: borrowers: borrower object(s) Returns: reference to itself (can be used for call chaining)
pysmi/compiler.py
def addBorrowers(self, *borrowers): """Add more transformed MIBs repositories to borrow MIBs from. Whenever MibCompiler.compile encounters MIB module which neither of the *searchers* can find or fetched ASN.1 MIB module can not be parsed (due to syntax errors), these *borrowers* objects will be invoked in order of their addition asking each if already transformed MIB can be fetched (borrowed). Args: borrowers: borrower object(s) Returns: reference to itself (can be used for call chaining) """ self._borrowers.extend(borrowers) debug.logger & debug.flagCompiler and debug.logger( 'current MIB borrower(s): %s' % ', '.join([str(x) for x in self._borrowers])) return self
def addBorrowers(self, *borrowers): """Add more transformed MIBs repositories to borrow MIBs from. Whenever MibCompiler.compile encounters MIB module which neither of the *searchers* can find or fetched ASN.1 MIB module can not be parsed (due to syntax errors), these *borrowers* objects will be invoked in order of their addition asking each if already transformed MIB can be fetched (borrowed). Args: borrowers: borrower object(s) Returns: reference to itself (can be used for call chaining) """ self._borrowers.extend(borrowers) debug.logger & debug.flagCompiler and debug.logger( 'current MIB borrower(s): %s' % ', '.join([str(x) for x in self._borrowers])) return self
[ "Add", "more", "transformed", "MIBs", "repositories", "to", "borrow", "MIBs", "from", "." ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/compiler.py#L136-L157
[ "def", "addBorrowers", "(", "self", ",", "*", "borrowers", ")", ":", "self", ".", "_borrowers", ".", "extend", "(", "borrowers", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'current MIB borrower(s): %s'", "%", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "_borrowers", "]", ")", ")", "return", "self" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
MibCompiler.compile
Transform requested and possibly referred MIBs. The *compile* method should be invoked when *MibCompiler* object is operational meaning at least *sources* are specified. Once called with a MIB module name, *compile* will: * fetch ASN.1 MIB module with given name by calling *sources* * make sure no such transformed MIB already exists (with *searchers*) * parse ASN.1 MIB text with *parser* * perform actual MIB transformation into target format with *code generator* * may attempt to borrow pre-transformed MIB through *borrowers* * write transformed MIB through *writer* The above sequence will be performed for each MIB name given in *mibnames* and may be performed for all MIBs referred to from MIBs being processed. Args: mibnames: list of ASN.1 MIBs names options: options that affect the way PySMI components work Returns: A dictionary of MIB module names processed (keys) and *MibStatus* class instances (values)
pysmi/compiler.py
def compile(self, *mibnames, **options): """Transform requested and possibly referred MIBs. The *compile* method should be invoked when *MibCompiler* object is operational meaning at least *sources* are specified. Once called with a MIB module name, *compile* will: * fetch ASN.1 MIB module with given name by calling *sources* * make sure no such transformed MIB already exists (with *searchers*) * parse ASN.1 MIB text with *parser* * perform actual MIB transformation into target format with *code generator* * may attempt to borrow pre-transformed MIB through *borrowers* * write transformed MIB through *writer* The above sequence will be performed for each MIB name given in *mibnames* and may be performed for all MIBs referred to from MIBs being processed. Args: mibnames: list of ASN.1 MIBs names options: options that affect the way PySMI components work Returns: A dictionary of MIB module names processed (keys) and *MibStatus* class instances (values) """ processed = {} parsedMibs = {} failedMibs = {} borrowedMibs = {} builtMibs = {} symbolTableMap = {} mibsToParse = [x for x in mibnames] canonicalMibNames = {} while mibsToParse: mibname = mibsToParse.pop(0) if mibname in parsedMibs: debug.logger & debug.flagCompiler and debug.logger('MIB %s already parsed' % mibname) continue if mibname in failedMibs: debug.logger & debug.flagCompiler and debug.logger('MIB %s already failed' % mibname) continue for source in self._sources: debug.logger & debug.flagCompiler and debug.logger('trying source %s' % source) try: fileInfo, fileData = source.getData(mibname) for mibTree in self._parser.parse(fileData): mibInfo, symbolTable = self._symbolgen.genCode( mibTree, symbolTableMap ) symbolTableMap[mibInfo.name] = symbolTable parsedMibs[mibInfo.name] = fileInfo, mibInfo, mibTree if mibname in failedMibs: del failedMibs[mibname] mibsToParse.extend(mibInfo.imported) if fileInfo.name in mibnames: if mibInfo.name not in canonicalMibNames: canonicalMibNames[mibInfo.name] = [] canonicalMibNames[mibInfo.name].append(fileInfo.name) debug.logger & debug.flagCompiler and debug.logger( '%s (%s) read from %s, immediate dependencies: %s' % ( mibInfo.name, mibname, fileInfo.path, ', '.join(mibInfo.imported) or '<none>')) break except error.PySmiReaderFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger('no %s found at %s' % (mibname, source)) continue except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.source = source exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('%serror %s from %s' % ( options.get('ignoreErrors') and 'ignoring ' or 'failing on ', exc, source)) failedMibs[mibname] = exc processed[mibname] = statusFailed.setOptions(error=exc) else: exc = error.PySmiError('MIB source %s not found' % mibname) exc.mibname = mibname debug.logger & debug.flagCompiler and debug.logger('no %s found everywhere' % mibname) if mibname not in failedMibs: failedMibs[mibname] = exc if mibname not in processed: processed[mibname] = statusMissing debug.logger & debug.flagCompiler and debug.logger( 'MIBs analyzed %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # See what MIBs need generating # for mibname in tuple(parsedMibs): fileInfo, mibInfo, mibTree = parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('checking if %s requires updating' % mibname) for searcher in self._searchers: try: searcher.fileExists(mibname, fileInfo.mtime, rebuild=options.get('rebuild')) except error.PySmiFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger( 'no compiled MIB %s available through %s' % (mibname, searcher)) continue except error.PySmiFileNotModifiedError: debug.logger & debug.flagCompiler and debug.logger( 'will be using existing compiled MIB %s found by %s' % (mibname, searcher)) del parsedMibs[mibname] processed[mibname] = statusUntouched break except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.searcher = searcher exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (searcher, exc)) continue else: debug.logger & debug.flagCompiler and debug.logger( 'no suitable compiled MIB %s found anywhere' % mibname) if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( 'excluding imported MIB %s from code generation' % mibname) del parsedMibs[mibname] processed[mibname] = statusUntouched continue debug.logger & debug.flagCompiler and debug.logger( 'MIBs parsed %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # Generate code for parsed MIBs # for mibname in parsedMibs.copy(): fileInfo, mibInfo, mibTree = parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('compiling %s read from %s' % (mibname, fileInfo.path)) platform_info, user_info = self._get_system_info() comments = [ 'ASN.1 source %s' % fileInfo.path, 'Produced by %s-%s at %s' % (packageName, packageVersion, time.asctime()), 'On host %s platform %s version %s by user %s' % (platform_info[1], platform_info[0], platform_info[2], user_info[0]), 'Using Python version %s' % sys.version.split('\n')[0] ] try: mibInfo, mibData = self._codegen.genCode( mibTree, symbolTableMap, comments=comments, dstTemplate=options.get('dstTemplate'), genTexts=options.get('genTexts'), textFilter=options.get('textFilter') ) builtMibs[mibname] = fileInfo, mibInfo, mibData del parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( '%s read from %s and compiled by %s' % (mibname, fileInfo.path, self._writer)) except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.handler = self._codegen exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (self._codegen, exc)) processed[mibname] = statusFailed.setOptions(error=exc) failedMibs[mibname] = exc del parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs built %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # Try to borrow pre-compiled MIBs for failed ones # for mibname in failedMibs.copy(): if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger('excluding imported MIB %s from borrowing' % mibname) continue for borrower in self._borrowers: debug.logger & debug.flagCompiler and debug.logger('trying to borrow %s from %s' % (mibname, borrower)) try: fileInfo, fileData = borrower.getData( mibname, genTexts=options.get('genTexts') ) borrowedMibs[mibname] = fileInfo, MibInfo(name=mibname, imported=[]), fileData del failedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('%s borrowed with %s' % (mibname, borrower)) break except error.PySmiError: debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (borrower, sys.exc_info()[1])) debug.logger & debug.flagCompiler and debug.logger( 'MIBs available for borrowing %s, MIBs failed %s' % (len(borrowedMibs), len(failedMibs))) # # See what MIBs need borrowing # for mibname in borrowedMibs.copy(): debug.logger & debug.flagCompiler and debug.logger('checking if failed MIB %s requires borrowing' % mibname) fileInfo, mibInfo, mibData = borrowedMibs[mibname] for searcher in self._searchers: try: searcher.fileExists(mibname, fileInfo.mtime, rebuild=options.get('rebuild')) except error.PySmiFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger( 'no compiled MIB %s available through %s' % (mibname, searcher)) continue except error.PySmiFileNotModifiedError: debug.logger & debug.flagCompiler and debug.logger( 'will be using existing compiled MIB %s found by %s' % (mibname, searcher)) del borrowedMibs[mibname] processed[mibname] = statusUntouched break except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.searcher = searcher exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (searcher, exc)) continue else: debug.logger & debug.flagCompiler and debug.logger( 'no suitable compiled MIB %s found anywhere' % mibname) if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( 'excluding imported MIB %s from borrowing' % mibname) processed[mibname] = statusUntouched else: debug.logger & debug.flagCompiler and debug.logger('will borrow MIB %s' % mibname) builtMibs[mibname] = borrowedMibs[mibname] processed[mibname] = statusBorrowed.setOptions( path=fileInfo.path, file=fileInfo.file, alias=fileInfo.name ) del borrowedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs built %s, MIBs failed %s' % (len(builtMibs), len(failedMibs))) # # We could attempt to ignore missing/failed MIBs # if failedMibs and not options.get('ignoreErrors'): debug.logger & debug.flagCompiler and debug.logger('failing with problem MIBs %s' % ', '.join(failedMibs)) for mibname in builtMibs: processed[mibname] = statusUnprocessed return processed debug.logger & debug.flagCompiler and debug.logger( 'proceeding with built MIBs %s, failed MIBs %s' % (', '.join(builtMibs), ', '.join(failedMibs))) # # Store compiled MIBs # for mibname in builtMibs.copy(): fileInfo, mibInfo, mibData = builtMibs[mibname] try: if options.get('writeMibs', True): self._writer.putData( mibname, mibData, dryRun=options.get('dryRun') ) debug.logger & debug.flagCompiler and debug.logger('%s stored by %s' % (mibname, self._writer)) del builtMibs[mibname] if mibname not in processed: processed[mibname] = statusCompiled.setOptions( path=fileInfo.path, file=fileInfo.file, alias=fileInfo.name, oid=mibInfo.oid, oids=mibInfo.oids, identity=mibInfo.identity, revision=mibInfo.revision, enterprise=mibInfo.enterprise, compliance=mibInfo.compliance, ) except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.handler = self._codegen exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error %s from %s' % (exc, self._writer)) processed[mibname] = statusFailed.setOptions(error=exc) failedMibs[mibname] = exc del builtMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs modified: %s' % ', '.join([x for x in processed if processed[x] in ('compiled', 'borrowed')])) return processed
def compile(self, *mibnames, **options): """Transform requested and possibly referred MIBs. The *compile* method should be invoked when *MibCompiler* object is operational meaning at least *sources* are specified. Once called with a MIB module name, *compile* will: * fetch ASN.1 MIB module with given name by calling *sources* * make sure no such transformed MIB already exists (with *searchers*) * parse ASN.1 MIB text with *parser* * perform actual MIB transformation into target format with *code generator* * may attempt to borrow pre-transformed MIB through *borrowers* * write transformed MIB through *writer* The above sequence will be performed for each MIB name given in *mibnames* and may be performed for all MIBs referred to from MIBs being processed. Args: mibnames: list of ASN.1 MIBs names options: options that affect the way PySMI components work Returns: A dictionary of MIB module names processed (keys) and *MibStatus* class instances (values) """ processed = {} parsedMibs = {} failedMibs = {} borrowedMibs = {} builtMibs = {} symbolTableMap = {} mibsToParse = [x for x in mibnames] canonicalMibNames = {} while mibsToParse: mibname = mibsToParse.pop(0) if mibname in parsedMibs: debug.logger & debug.flagCompiler and debug.logger('MIB %s already parsed' % mibname) continue if mibname in failedMibs: debug.logger & debug.flagCompiler and debug.logger('MIB %s already failed' % mibname) continue for source in self._sources: debug.logger & debug.flagCompiler and debug.logger('trying source %s' % source) try: fileInfo, fileData = source.getData(mibname) for mibTree in self._parser.parse(fileData): mibInfo, symbolTable = self._symbolgen.genCode( mibTree, symbolTableMap ) symbolTableMap[mibInfo.name] = symbolTable parsedMibs[mibInfo.name] = fileInfo, mibInfo, mibTree if mibname in failedMibs: del failedMibs[mibname] mibsToParse.extend(mibInfo.imported) if fileInfo.name in mibnames: if mibInfo.name not in canonicalMibNames: canonicalMibNames[mibInfo.name] = [] canonicalMibNames[mibInfo.name].append(fileInfo.name) debug.logger & debug.flagCompiler and debug.logger( '%s (%s) read from %s, immediate dependencies: %s' % ( mibInfo.name, mibname, fileInfo.path, ', '.join(mibInfo.imported) or '<none>')) break except error.PySmiReaderFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger('no %s found at %s' % (mibname, source)) continue except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.source = source exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('%serror %s from %s' % ( options.get('ignoreErrors') and 'ignoring ' or 'failing on ', exc, source)) failedMibs[mibname] = exc processed[mibname] = statusFailed.setOptions(error=exc) else: exc = error.PySmiError('MIB source %s not found' % mibname) exc.mibname = mibname debug.logger & debug.flagCompiler and debug.logger('no %s found everywhere' % mibname) if mibname not in failedMibs: failedMibs[mibname] = exc if mibname not in processed: processed[mibname] = statusMissing debug.logger & debug.flagCompiler and debug.logger( 'MIBs analyzed %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # See what MIBs need generating # for mibname in tuple(parsedMibs): fileInfo, mibInfo, mibTree = parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('checking if %s requires updating' % mibname) for searcher in self._searchers: try: searcher.fileExists(mibname, fileInfo.mtime, rebuild=options.get('rebuild')) except error.PySmiFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger( 'no compiled MIB %s available through %s' % (mibname, searcher)) continue except error.PySmiFileNotModifiedError: debug.logger & debug.flagCompiler and debug.logger( 'will be using existing compiled MIB %s found by %s' % (mibname, searcher)) del parsedMibs[mibname] processed[mibname] = statusUntouched break except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.searcher = searcher exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (searcher, exc)) continue else: debug.logger & debug.flagCompiler and debug.logger( 'no suitable compiled MIB %s found anywhere' % mibname) if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( 'excluding imported MIB %s from code generation' % mibname) del parsedMibs[mibname] processed[mibname] = statusUntouched continue debug.logger & debug.flagCompiler and debug.logger( 'MIBs parsed %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # Generate code for parsed MIBs # for mibname in parsedMibs.copy(): fileInfo, mibInfo, mibTree = parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('compiling %s read from %s' % (mibname, fileInfo.path)) platform_info, user_info = self._get_system_info() comments = [ 'ASN.1 source %s' % fileInfo.path, 'Produced by %s-%s at %s' % (packageName, packageVersion, time.asctime()), 'On host %s platform %s version %s by user %s' % (platform_info[1], platform_info[0], platform_info[2], user_info[0]), 'Using Python version %s' % sys.version.split('\n')[0] ] try: mibInfo, mibData = self._codegen.genCode( mibTree, symbolTableMap, comments=comments, dstTemplate=options.get('dstTemplate'), genTexts=options.get('genTexts'), textFilter=options.get('textFilter') ) builtMibs[mibname] = fileInfo, mibInfo, mibData del parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( '%s read from %s and compiled by %s' % (mibname, fileInfo.path, self._writer)) except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.handler = self._codegen exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (self._codegen, exc)) processed[mibname] = statusFailed.setOptions(error=exc) failedMibs[mibname] = exc del parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs built %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # Try to borrow pre-compiled MIBs for failed ones # for mibname in failedMibs.copy(): if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger('excluding imported MIB %s from borrowing' % mibname) continue for borrower in self._borrowers: debug.logger & debug.flagCompiler and debug.logger('trying to borrow %s from %s' % (mibname, borrower)) try: fileInfo, fileData = borrower.getData( mibname, genTexts=options.get('genTexts') ) borrowedMibs[mibname] = fileInfo, MibInfo(name=mibname, imported=[]), fileData del failedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('%s borrowed with %s' % (mibname, borrower)) break except error.PySmiError: debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (borrower, sys.exc_info()[1])) debug.logger & debug.flagCompiler and debug.logger( 'MIBs available for borrowing %s, MIBs failed %s' % (len(borrowedMibs), len(failedMibs))) # # See what MIBs need borrowing # for mibname in borrowedMibs.copy(): debug.logger & debug.flagCompiler and debug.logger('checking if failed MIB %s requires borrowing' % mibname) fileInfo, mibInfo, mibData = borrowedMibs[mibname] for searcher in self._searchers: try: searcher.fileExists(mibname, fileInfo.mtime, rebuild=options.get('rebuild')) except error.PySmiFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger( 'no compiled MIB %s available through %s' % (mibname, searcher)) continue except error.PySmiFileNotModifiedError: debug.logger & debug.flagCompiler and debug.logger( 'will be using existing compiled MIB %s found by %s' % (mibname, searcher)) del borrowedMibs[mibname] processed[mibname] = statusUntouched break except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.searcher = searcher exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (searcher, exc)) continue else: debug.logger & debug.flagCompiler and debug.logger( 'no suitable compiled MIB %s found anywhere' % mibname) if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( 'excluding imported MIB %s from borrowing' % mibname) processed[mibname] = statusUntouched else: debug.logger & debug.flagCompiler and debug.logger('will borrow MIB %s' % mibname) builtMibs[mibname] = borrowedMibs[mibname] processed[mibname] = statusBorrowed.setOptions( path=fileInfo.path, file=fileInfo.file, alias=fileInfo.name ) del borrowedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs built %s, MIBs failed %s' % (len(builtMibs), len(failedMibs))) # # We could attempt to ignore missing/failed MIBs # if failedMibs and not options.get('ignoreErrors'): debug.logger & debug.flagCompiler and debug.logger('failing with problem MIBs %s' % ', '.join(failedMibs)) for mibname in builtMibs: processed[mibname] = statusUnprocessed return processed debug.logger & debug.flagCompiler and debug.logger( 'proceeding with built MIBs %s, failed MIBs %s' % (', '.join(builtMibs), ', '.join(failedMibs))) # # Store compiled MIBs # for mibname in builtMibs.copy(): fileInfo, mibInfo, mibData = builtMibs[mibname] try: if options.get('writeMibs', True): self._writer.putData( mibname, mibData, dryRun=options.get('dryRun') ) debug.logger & debug.flagCompiler and debug.logger('%s stored by %s' % (mibname, self._writer)) del builtMibs[mibname] if mibname not in processed: processed[mibname] = statusCompiled.setOptions( path=fileInfo.path, file=fileInfo.file, alias=fileInfo.name, oid=mibInfo.oid, oids=mibInfo.oids, identity=mibInfo.identity, revision=mibInfo.revision, enterprise=mibInfo.enterprise, compliance=mibInfo.compliance, ) except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.handler = self._codegen exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error %s from %s' % (exc, self._writer)) processed[mibname] = statusFailed.setOptions(error=exc) failedMibs[mibname] = exc del builtMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs modified: %s' % ', '.join([x for x in processed if processed[x] in ('compiled', 'borrowed')])) return processed
[ "Transform", "requested", "and", "possibly", "referred", "MIBs", "." ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/compiler.py#L175-L530
[ "def", "compile", "(", "self", ",", "*", "mibnames", ",", "*", "*", "options", ")", ":", "processed", "=", "{", "}", "parsedMibs", "=", "{", "}", "failedMibs", "=", "{", "}", "borrowedMibs", "=", "{", "}", "builtMibs", "=", "{", "}", "symbolTableMap", "=", "{", "}", "mibsToParse", "=", "[", "x", "for", "x", "in", "mibnames", "]", "canonicalMibNames", "=", "{", "}", "while", "mibsToParse", ":", "mibname", "=", "mibsToParse", ".", "pop", "(", "0", ")", "if", "mibname", "in", "parsedMibs", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'MIB %s already parsed'", "%", "mibname", ")", "continue", "if", "mibname", "in", "failedMibs", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'MIB %s already failed'", "%", "mibname", ")", "continue", "for", "source", "in", "self", ".", "_sources", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'trying source %s'", "%", "source", ")", "try", ":", "fileInfo", ",", "fileData", "=", "source", ".", "getData", "(", "mibname", ")", "for", "mibTree", "in", "self", ".", "_parser", ".", "parse", "(", "fileData", ")", ":", "mibInfo", ",", "symbolTable", "=", "self", ".", "_symbolgen", ".", "genCode", "(", "mibTree", ",", "symbolTableMap", ")", "symbolTableMap", "[", "mibInfo", ".", "name", "]", "=", "symbolTable", "parsedMibs", "[", "mibInfo", ".", "name", "]", "=", "fileInfo", ",", "mibInfo", ",", "mibTree", "if", "mibname", "in", "failedMibs", ":", "del", "failedMibs", "[", "mibname", "]", "mibsToParse", ".", "extend", "(", "mibInfo", ".", "imported", ")", "if", "fileInfo", ".", "name", "in", "mibnames", ":", "if", "mibInfo", ".", "name", "not", "in", "canonicalMibNames", ":", "canonicalMibNames", "[", "mibInfo", ".", "name", "]", "=", "[", "]", "canonicalMibNames", "[", "mibInfo", ".", "name", "]", ".", "append", "(", "fileInfo", ".", "name", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'%s (%s) read from %s, immediate dependencies: %s'", "%", "(", "mibInfo", ".", "name", ",", "mibname", ",", "fileInfo", ".", "path", ",", "', '", ".", "join", "(", "mibInfo", ".", "imported", ")", "or", "'<none>'", ")", ")", "break", "except", "error", ".", "PySmiReaderFileNotFoundError", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'no %s found at %s'", "%", "(", "mibname", ",", "source", ")", ")", "continue", "except", "error", ".", "PySmiError", ":", "exc_class", ",", "exc", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "exc", ".", "source", "=", "source", "exc", ".", "mibname", "=", "mibname", "exc", ".", "msg", "+=", "' at MIB %s'", "%", "mibname", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'%serror %s from %s'", "%", "(", "options", ".", "get", "(", "'ignoreErrors'", ")", "and", "'ignoring '", "or", "'failing on '", ",", "exc", ",", "source", ")", ")", "failedMibs", "[", "mibname", "]", "=", "exc", "processed", "[", "mibname", "]", "=", "statusFailed", ".", "setOptions", "(", "error", "=", "exc", ")", "else", ":", "exc", "=", "error", ".", "PySmiError", "(", "'MIB source %s not found'", "%", "mibname", ")", "exc", ".", "mibname", "=", "mibname", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'no %s found everywhere'", "%", "mibname", ")", "if", "mibname", "not", "in", "failedMibs", ":", "failedMibs", "[", "mibname", "]", "=", "exc", "if", "mibname", "not", "in", "processed", ":", "processed", "[", "mibname", "]", "=", "statusMissing", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'MIBs analyzed %s, MIBs failed %s'", "%", "(", "len", "(", "parsedMibs", ")", ",", "len", "(", "failedMibs", ")", ")", ")", "#", "# See what MIBs need generating", "#", "for", "mibname", "in", "tuple", "(", "parsedMibs", ")", ":", "fileInfo", ",", "mibInfo", ",", "mibTree", "=", "parsedMibs", "[", "mibname", "]", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'checking if %s requires updating'", "%", "mibname", ")", "for", "searcher", "in", "self", ".", "_searchers", ":", "try", ":", "searcher", ".", "fileExists", "(", "mibname", ",", "fileInfo", ".", "mtime", ",", "rebuild", "=", "options", ".", "get", "(", "'rebuild'", ")", ")", "except", "error", ".", "PySmiFileNotFoundError", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'no compiled MIB %s available through %s'", "%", "(", "mibname", ",", "searcher", ")", ")", "continue", "except", "error", ".", "PySmiFileNotModifiedError", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'will be using existing compiled MIB %s found by %s'", "%", "(", "mibname", ",", "searcher", ")", ")", "del", "parsedMibs", "[", "mibname", "]", "processed", "[", "mibname", "]", "=", "statusUntouched", "break", "except", "error", ".", "PySmiError", ":", "exc_class", ",", "exc", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "exc", ".", "searcher", "=", "searcher", "exc", ".", "mibname", "=", "mibname", "exc", ".", "msg", "+=", "' at MIB %s'", "%", "mibname", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'error from %s: %s'", "%", "(", "searcher", ",", "exc", ")", ")", "continue", "else", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'no suitable compiled MIB %s found anywhere'", "%", "mibname", ")", "if", "options", ".", "get", "(", "'noDeps'", ")", "and", "mibname", "not", "in", "canonicalMibNames", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'excluding imported MIB %s from code generation'", "%", "mibname", ")", "del", "parsedMibs", "[", "mibname", "]", "processed", "[", "mibname", "]", "=", "statusUntouched", "continue", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'MIBs parsed %s, MIBs failed %s'", "%", "(", "len", "(", "parsedMibs", ")", ",", "len", "(", "failedMibs", ")", ")", ")", "#", "# Generate code for parsed MIBs", "#", "for", "mibname", "in", "parsedMibs", ".", "copy", "(", ")", ":", "fileInfo", ",", "mibInfo", ",", "mibTree", "=", "parsedMibs", "[", "mibname", "]", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'compiling %s read from %s'", "%", "(", "mibname", ",", "fileInfo", ".", "path", ")", ")", "platform_info", ",", "user_info", "=", "self", ".", "_get_system_info", "(", ")", "comments", "=", "[", "'ASN.1 source %s'", "%", "fileInfo", ".", "path", ",", "'Produced by %s-%s at %s'", "%", "(", "packageName", ",", "packageVersion", ",", "time", ".", "asctime", "(", ")", ")", ",", "'On host %s platform %s version %s by user %s'", "%", "(", "platform_info", "[", "1", "]", ",", "platform_info", "[", "0", "]", ",", "platform_info", "[", "2", "]", ",", "user_info", "[", "0", "]", ")", ",", "'Using Python version %s'", "%", "sys", ".", "version", ".", "split", "(", "'\\n'", ")", "[", "0", "]", "]", "try", ":", "mibInfo", ",", "mibData", "=", "self", ".", "_codegen", ".", "genCode", "(", "mibTree", ",", "symbolTableMap", ",", "comments", "=", "comments", ",", "dstTemplate", "=", "options", ".", "get", "(", "'dstTemplate'", ")", ",", "genTexts", "=", "options", ".", "get", "(", "'genTexts'", ")", ",", "textFilter", "=", "options", ".", "get", "(", "'textFilter'", ")", ")", "builtMibs", "[", "mibname", "]", "=", "fileInfo", ",", "mibInfo", ",", "mibData", "del", "parsedMibs", "[", "mibname", "]", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'%s read from %s and compiled by %s'", "%", "(", "mibname", ",", "fileInfo", ".", "path", ",", "self", ".", "_writer", ")", ")", "except", "error", ".", "PySmiError", ":", "exc_class", ",", "exc", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "exc", ".", "handler", "=", "self", ".", "_codegen", "exc", ".", "mibname", "=", "mibname", "exc", ".", "msg", "+=", "' at MIB %s'", "%", "mibname", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'error from %s: %s'", "%", "(", "self", ".", "_codegen", ",", "exc", ")", ")", "processed", "[", "mibname", "]", "=", "statusFailed", ".", "setOptions", "(", "error", "=", "exc", ")", "failedMibs", "[", "mibname", "]", "=", "exc", "del", "parsedMibs", "[", "mibname", "]", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'MIBs built %s, MIBs failed %s'", "%", "(", "len", "(", "parsedMibs", ")", ",", "len", "(", "failedMibs", ")", ")", ")", "#", "# Try to borrow pre-compiled MIBs for failed ones", "#", "for", "mibname", "in", "failedMibs", ".", "copy", "(", ")", ":", "if", "options", ".", "get", "(", "'noDeps'", ")", "and", "mibname", "not", "in", "canonicalMibNames", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'excluding imported MIB %s from borrowing'", "%", "mibname", ")", "continue", "for", "borrower", "in", "self", ".", "_borrowers", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'trying to borrow %s from %s'", "%", "(", "mibname", ",", "borrower", ")", ")", "try", ":", "fileInfo", ",", "fileData", "=", "borrower", ".", "getData", "(", "mibname", ",", "genTexts", "=", "options", ".", "get", "(", "'genTexts'", ")", ")", "borrowedMibs", "[", "mibname", "]", "=", "fileInfo", ",", "MibInfo", "(", "name", "=", "mibname", ",", "imported", "=", "[", "]", ")", ",", "fileData", "del", "failedMibs", "[", "mibname", "]", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'%s borrowed with %s'", "%", "(", "mibname", ",", "borrower", ")", ")", "break", "except", "error", ".", "PySmiError", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'error from %s: %s'", "%", "(", "borrower", ",", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'MIBs available for borrowing %s, MIBs failed %s'", "%", "(", "len", "(", "borrowedMibs", ")", ",", "len", "(", "failedMibs", ")", ")", ")", "#", "# See what MIBs need borrowing", "#", "for", "mibname", "in", "borrowedMibs", ".", "copy", "(", ")", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'checking if failed MIB %s requires borrowing'", "%", "mibname", ")", "fileInfo", ",", "mibInfo", ",", "mibData", "=", "borrowedMibs", "[", "mibname", "]", "for", "searcher", "in", "self", ".", "_searchers", ":", "try", ":", "searcher", ".", "fileExists", "(", "mibname", ",", "fileInfo", ".", "mtime", ",", "rebuild", "=", "options", ".", "get", "(", "'rebuild'", ")", ")", "except", "error", ".", "PySmiFileNotFoundError", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'no compiled MIB %s available through %s'", "%", "(", "mibname", ",", "searcher", ")", ")", "continue", "except", "error", ".", "PySmiFileNotModifiedError", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'will be using existing compiled MIB %s found by %s'", "%", "(", "mibname", ",", "searcher", ")", ")", "del", "borrowedMibs", "[", "mibname", "]", "processed", "[", "mibname", "]", "=", "statusUntouched", "break", "except", "error", ".", "PySmiError", ":", "exc_class", ",", "exc", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "exc", ".", "searcher", "=", "searcher", "exc", ".", "mibname", "=", "mibname", "exc", ".", "msg", "+=", "' at MIB %s'", "%", "mibname", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'error from %s: %s'", "%", "(", "searcher", ",", "exc", ")", ")", "continue", "else", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'no suitable compiled MIB %s found anywhere'", "%", "mibname", ")", "if", "options", ".", "get", "(", "'noDeps'", ")", "and", "mibname", "not", "in", "canonicalMibNames", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'excluding imported MIB %s from borrowing'", "%", "mibname", ")", "processed", "[", "mibname", "]", "=", "statusUntouched", "else", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'will borrow MIB %s'", "%", "mibname", ")", "builtMibs", "[", "mibname", "]", "=", "borrowedMibs", "[", "mibname", "]", "processed", "[", "mibname", "]", "=", "statusBorrowed", ".", "setOptions", "(", "path", "=", "fileInfo", ".", "path", ",", "file", "=", "fileInfo", ".", "file", ",", "alias", "=", "fileInfo", ".", "name", ")", "del", "borrowedMibs", "[", "mibname", "]", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'MIBs built %s, MIBs failed %s'", "%", "(", "len", "(", "builtMibs", ")", ",", "len", "(", "failedMibs", ")", ")", ")", "#", "# We could attempt to ignore missing/failed MIBs", "#", "if", "failedMibs", "and", "not", "options", ".", "get", "(", "'ignoreErrors'", ")", ":", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'failing with problem MIBs %s'", "%", "', '", ".", "join", "(", "failedMibs", ")", ")", "for", "mibname", "in", "builtMibs", ":", "processed", "[", "mibname", "]", "=", "statusUnprocessed", "return", "processed", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'proceeding with built MIBs %s, failed MIBs %s'", "%", "(", "', '", ".", "join", "(", "builtMibs", ")", ",", "', '", ".", "join", "(", "failedMibs", ")", ")", ")", "#", "# Store compiled MIBs", "#", "for", "mibname", "in", "builtMibs", ".", "copy", "(", ")", ":", "fileInfo", ",", "mibInfo", ",", "mibData", "=", "builtMibs", "[", "mibname", "]", "try", ":", "if", "options", ".", "get", "(", "'writeMibs'", ",", "True", ")", ":", "self", ".", "_writer", ".", "putData", "(", "mibname", ",", "mibData", ",", "dryRun", "=", "options", ".", "get", "(", "'dryRun'", ")", ")", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'%s stored by %s'", "%", "(", "mibname", ",", "self", ".", "_writer", ")", ")", "del", "builtMibs", "[", "mibname", "]", "if", "mibname", "not", "in", "processed", ":", "processed", "[", "mibname", "]", "=", "statusCompiled", ".", "setOptions", "(", "path", "=", "fileInfo", ".", "path", ",", "file", "=", "fileInfo", ".", "file", ",", "alias", "=", "fileInfo", ".", "name", ",", "oid", "=", "mibInfo", ".", "oid", ",", "oids", "=", "mibInfo", ".", "oids", ",", "identity", "=", "mibInfo", ".", "identity", ",", "revision", "=", "mibInfo", ".", "revision", ",", "enterprise", "=", "mibInfo", ".", "enterprise", ",", "compliance", "=", "mibInfo", ".", "compliance", ",", ")", "except", "error", ".", "PySmiError", ":", "exc_class", ",", "exc", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "exc", ".", "handler", "=", "self", ".", "_codegen", "exc", ".", "mibname", "=", "mibname", "exc", ".", "msg", "+=", "' at MIB %s'", "%", "mibname", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'error %s from %s'", "%", "(", "exc", ",", "self", ".", "_writer", ")", ")", "processed", "[", "mibname", "]", "=", "statusFailed", ".", "setOptions", "(", "error", "=", "exc", ")", "failedMibs", "[", "mibname", "]", "=", "exc", "del", "builtMibs", "[", "mibname", "]", "debug", ".", "logger", "&", "debug", ".", "flagCompiler", "and", "debug", ".", "logger", "(", "'MIBs modified: %s'", "%", "', '", ".", "join", "(", "[", "x", "for", "x", "in", "processed", "if", "processed", "[", "x", "]", "in", "(", "'compiled'", ",", "'borrowed'", ")", "]", ")", ")", "return", "processed" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Lexer.t_UPPERCASE_IDENTIFIER
r'[A-Z][-a-zA-z0-9]*
pysmi/lexer/smi.py
def t_UPPERCASE_IDENTIFIER(self, t): r'[A-Z][-a-zA-z0-9]*' if t.value in self.forbidden_words: raise error.PySmiLexerError("%s is forbidden" % t.value, lineno=t.lineno) if t.value[-1] == '-': raise error.PySmiLexerError("Identifier should not end with '-': %s" % t.value, lineno=t.lineno) t.type = self.reserved.get(t.value, 'UPPERCASE_IDENTIFIER') return t
def t_UPPERCASE_IDENTIFIER(self, t): r'[A-Z][-a-zA-z0-9]*' if t.value in self.forbidden_words: raise error.PySmiLexerError("%s is forbidden" % t.value, lineno=t.lineno) if t.value[-1] == '-': raise error.PySmiLexerError("Identifier should not end with '-': %s" % t.value, lineno=t.lineno) t.type = self.reserved.get(t.value, 'UPPERCASE_IDENTIFIER') return t
[ "r", "[", "A", "-", "Z", "]", "[", "-", "a", "-", "zA", "-", "z0", "-", "9", "]", "*" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/lexer/smi.py#L194-L204
[ "def", "t_UPPERCASE_IDENTIFIER", "(", "self", ",", "t", ")", ":", "if", "t", ".", "value", "in", "self", ".", "forbidden_words", ":", "raise", "error", ".", "PySmiLexerError", "(", "\"%s is forbidden\"", "%", "t", ".", "value", ",", "lineno", "=", "t", ".", "lineno", ")", "if", "t", ".", "value", "[", "-", "1", "]", "==", "'-'", ":", "raise", "error", ".", "PySmiLexerError", "(", "\"Identifier should not end with '-': %s\"", "%", "t", ".", "value", ",", "lineno", "=", "t", ".", "lineno", ")", "t", ".", "type", "=", "self", ".", "reserved", ".", "get", "(", "t", ".", "value", ",", "'UPPERCASE_IDENTIFIER'", ")", "return", "t" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Lexer.t_LOWERCASE_IDENTIFIER
r'[0-9]*[a-z][-a-zA-z0-9]*
pysmi/lexer/smi.py
def t_LOWERCASE_IDENTIFIER(self, t): r'[0-9]*[a-z][-a-zA-z0-9]*' if t.value[-1] == '-': raise error.PySmiLexerError("Identifier should not end with '-': %s" % t.value, lineno=t.lineno) return t
def t_LOWERCASE_IDENTIFIER(self, t): r'[0-9]*[a-z][-a-zA-z0-9]*' if t.value[-1] == '-': raise error.PySmiLexerError("Identifier should not end with '-': %s" % t.value, lineno=t.lineno) return t
[ "r", "[", "0", "-", "9", "]", "*", "[", "a", "-", "z", "]", "[", "-", "a", "-", "zA", "-", "z0", "-", "9", "]", "*" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/lexer/smi.py#L206-L210
[ "def", "t_LOWERCASE_IDENTIFIER", "(", "self", ",", "t", ")", ":", "if", "t", ".", "value", "[", "-", "1", "]", "==", "'-'", ":", "raise", "error", ".", "PySmiLexerError", "(", "\"Identifier should not end with '-': %s\"", "%", "t", ".", "value", ",", "lineno", "=", "t", ".", "lineno", ")", "return", "t" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Lexer.t_NUMBER
r'-?[0-9]+
pysmi/lexer/smi.py
def t_NUMBER(self, t): r'-?[0-9]+' t.value = int(t.value) neg = 0 if t.value < 0: neg = 1 val = abs(t.value) if val <= UNSIGNED32_MAX: if neg: t.type = 'NEGATIVENUMBER' elif val <= UNSIGNED64_MAX: if neg: t.type = 'NEGATIVENUMBER64' else: t.type = 'NUMBER64' else: raise error.PySmiLexerError("Number %s is too big" % t.value, lineno=t.lineno) return t
def t_NUMBER(self, t): r'-?[0-9]+' t.value = int(t.value) neg = 0 if t.value < 0: neg = 1 val = abs(t.value) if val <= UNSIGNED32_MAX: if neg: t.type = 'NEGATIVENUMBER' elif val <= UNSIGNED64_MAX: if neg: t.type = 'NEGATIVENUMBER64' else: t.type = 'NUMBER64' else: raise error.PySmiLexerError("Number %s is too big" % t.value, lineno=t.lineno) return t
[ "r", "-", "?", "[", "0", "-", "9", "]", "+" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/lexer/smi.py#L212-L234
[ "def", "t_NUMBER", "(", "self", ",", "t", ")", ":", "t", ".", "value", "=", "int", "(", "t", ".", "value", ")", "neg", "=", "0", "if", "t", ".", "value", "<", "0", ":", "neg", "=", "1", "val", "=", "abs", "(", "t", ".", "value", ")", "if", "val", "<=", "UNSIGNED32_MAX", ":", "if", "neg", ":", "t", ".", "type", "=", "'NEGATIVENUMBER'", "elif", "val", "<=", "UNSIGNED64_MAX", ":", "if", "neg", ":", "t", ".", "type", "=", "'NEGATIVENUMBER64'", "else", ":", "t", ".", "type", "=", "'NUMBER64'", "else", ":", "raise", "error", ".", "PySmiLexerError", "(", "\"Number %s is too big\"", "%", "t", ".", "value", ",", "lineno", "=", "t", ".", "lineno", ")", "return", "t" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Lexer.t_BIN_STRING
r'\'[01]*\'[bB]
pysmi/lexer/smi.py
def t_BIN_STRING(self, t): r'\'[01]*\'[bB]' value = t.value[1:-2] while value and value[0] == '0' and len(value) % 8: value = value[1:] # XXX raise in strict mode # if len(value) % 8: # raise error.PySmiLexerError("Number of 0s and 1s have to divide by 8 in binary string %s" % t.value, lineno=t.lineno) return t
def t_BIN_STRING(self, t): r'\'[01]*\'[bB]' value = t.value[1:-2] while value and value[0] == '0' and len(value) % 8: value = value[1:] # XXX raise in strict mode # if len(value) % 8: # raise error.PySmiLexerError("Number of 0s and 1s have to divide by 8 in binary string %s" % t.value, lineno=t.lineno) return t
[ "r", "\\", "[", "01", "]", "*", "\\", "[", "bB", "]" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/lexer/smi.py#L236-L244
[ "def", "t_BIN_STRING", "(", "self", ",", "t", ")", ":", "value", "=", "t", ".", "value", "[", "1", ":", "-", "2", "]", "while", "value", "and", "value", "[", "0", "]", "==", "'0'", "and", "len", "(", "value", ")", "%", "8", ":", "value", "=", "value", "[", "1", ":", "]", "# XXX raise in strict mode", "# if len(value) % 8:", "# raise error.PySmiLexerError(\"Number of 0s and 1s have to divide by 8 in binary string %s\" % t.value, lineno=t.lineno)", "return", "t" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Lexer.t_HEX_STRING
r'\'[0-9a-fA-F]*\'[hH]
pysmi/lexer/smi.py
def t_HEX_STRING(self, t): r'\'[0-9a-fA-F]*\'[hH]' value = t.value[1:-2] while value and value[0] == '0' and len(value) % 2: value = value[1:] # XXX raise in strict mode # if len(value) % 2: # raise error.PySmiLexerError("Number of symbols have to be even in hex string %s" % t.value, lineno=t.lineno) return t
def t_HEX_STRING(self, t): r'\'[0-9a-fA-F]*\'[hH]' value = t.value[1:-2] while value and value[0] == '0' and len(value) % 2: value = value[1:] # XXX raise in strict mode # if len(value) % 2: # raise error.PySmiLexerError("Number of symbols have to be even in hex string %s" % t.value, lineno=t.lineno) return t
[ "r", "\\", "[", "0", "-", "9a", "-", "fA", "-", "F", "]", "*", "\\", "[", "hH", "]" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/lexer/smi.py#L246-L254
[ "def", "t_HEX_STRING", "(", "self", ",", "t", ")", ":", "value", "=", "t", ".", "value", "[", "1", ":", "-", "2", "]", "while", "value", "and", "value", "[", "0", "]", "==", "'0'", "and", "len", "(", "value", ")", "%", "2", ":", "value", "=", "value", "[", "1", ":", "]", "# XXX raise in strict mode", "# if len(value) % 2:", "# raise error.PySmiLexerError(\"Number of symbols have to be even in hex string %s\" % t.value, lineno=t.lineno)", "return", "t" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Lexer.t_QUOTED_STRING
r'\"[^\"]*\"
pysmi/lexer/smi.py
def t_QUOTED_STRING(self, t): r'\"[^\"]*\"' t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', t.value)) return t
def t_QUOTED_STRING(self, t): r'\"[^\"]*\"' t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', t.value)) return t
[ "r", "\\", "[", "^", "\\", "]", "*", "\\" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/lexer/smi.py#L256-L259
[ "def", "t_QUOTED_STRING", "(", "self", ",", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "len", "(", "re", ".", "findall", "(", "r'\\r\\n|\\n|\\r'", ",", "t", ".", "value", ")", ")", "return", "t" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_modules
modules : modules module | module
pysmi/parser/smi.py
def p_modules(self, p): """modules : modules module | module""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
def p_modules(self, p): """modules : modules module | module""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
[ "modules", ":", "modules", "module", "|", "module" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L87-L94
[ "def", "p_modules", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_importPart
importPart : imports | empty
pysmi/parser/smi.py
def p_importPart(self, p): """importPart : imports | empty""" # libsmi: TODO: ``IMPORTS ;'' allowed? refer ASN.1! if p[1]: importDict = {} for imp in p[1]: # don't do just dict() because moduleNames may be repeated fromModule, symbols = imp if fromModule in importDict: importDict[fromModule] += symbols else: importDict[fromModule] = symbols p[0] = importDict
def p_importPart(self, p): """importPart : imports | empty""" # libsmi: TODO: ``IMPORTS ;'' allowed? refer ASN.1! if p[1]: importDict = {} for imp in p[1]: # don't do just dict() because moduleNames may be repeated fromModule, symbols = imp if fromModule in importDict: importDict[fromModule] += symbols else: importDict[fromModule] = symbols p[0] = importDict
[ "importPart", ":", "imports", "|", "empty" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L124-L137
[ "def", "p_importPart", "(", "self", ",", "p", ")", ":", "# libsmi: TODO: ``IMPORTS ;'' allowed? refer ASN.1!", "if", "p", "[", "1", "]", ":", "importDict", "=", "{", "}", "for", "imp", "in", "p", "[", "1", "]", ":", "# don't do just dict() because moduleNames may be repeated", "fromModule", ",", "symbols", "=", "imp", "if", "fromModule", "in", "importDict", ":", "importDict", "[", "fromModule", "]", "+=", "symbols", "else", ":", "importDict", "[", "fromModule", "]", "=", "symbols", "p", "[", "0", "]", "=", "importDict" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_imports
imports : imports import | import
pysmi/parser/smi.py
def p_imports(self, p): """imports : imports import | import""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
def p_imports(self, p): """imports : imports import | import""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
[ "imports", ":", "imports", "import", "|", "import" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L139-L146
[ "def", "p_imports", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_importIdentifiers
importIdentifiers : importIdentifiers ',' importIdentifier | importIdentifier
pysmi/parser/smi.py
def p_importIdentifiers(self, p): """importIdentifiers : importIdentifiers ',' importIdentifier | importIdentifier""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_importIdentifiers(self, p): """importIdentifiers : importIdentifiers ',' importIdentifier | importIdentifier""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
[ "importIdentifiers", ":", "importIdentifiers", "importIdentifier", "|", "importIdentifier" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L155-L162
[ "def", "p_importIdentifiers", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_declarations
declarations : declarations declaration | declaration
pysmi/parser/smi.py
def p_declarations(self, p): """declarations : declarations declaration | declaration""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
def p_declarations(self, p): """declarations : declarations declaration | declaration""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
[ "declarations", ":", "declarations", "declaration", "|", "declaration" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L208-L215
[ "def", "p_declarations", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_typeDeclarationRHS
typeDeclarationRHS : Syntax | TEXTUAL_CONVENTION DisplayPart STATUS Status DESCRIPTION Text ReferPart SYNTAX Syntax | choiceClause
pysmi/parser/smi.py
def p_typeDeclarationRHS(self, p): """typeDeclarationRHS : Syntax | TEXTUAL_CONVENTION DisplayPart STATUS Status DESCRIPTION Text ReferPart SYNTAX Syntax | choiceClause""" if p[1]: if p[1] == 'TEXTUAL-CONVENTION': p[0] = ('typeDeclarationRHS', p[2], # display p[4], # status (p[5], p[6]), # description p[7], # reference p[9]) # syntax else: p[0] = ('typeDeclarationRHS', p[1])
def p_typeDeclarationRHS(self, p): """typeDeclarationRHS : Syntax | TEXTUAL_CONVENTION DisplayPart STATUS Status DESCRIPTION Text ReferPart SYNTAX Syntax | choiceClause""" if p[1]: if p[1] == 'TEXTUAL-CONVENTION': p[0] = ('typeDeclarationRHS', p[2], # display p[4], # status (p[5], p[6]), # description p[7], # reference p[9]) # syntax else: p[0] = ('typeDeclarationRHS', p[1])
[ "typeDeclarationRHS", ":", "Syntax", "|", "TEXTUAL_CONVENTION", "DisplayPart", "STATUS", "Status", "DESCRIPTION", "Text", "ReferPart", "SYNTAX", "Syntax", "|", "choiceClause" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L291-L303
[ "def", "p_typeDeclarationRHS", "(", "self", ",", "p", ")", ":", "if", "p", "[", "1", "]", ":", "if", "p", "[", "1", "]", "==", "'TEXTUAL-CONVENTION'", ":", "p", "[", "0", "]", "=", "(", "'typeDeclarationRHS'", ",", "p", "[", "2", "]", ",", "# display", "p", "[", "4", "]", ",", "# status", "(", "p", "[", "5", "]", ",", "p", "[", "6", "]", ")", ",", "# description", "p", "[", "7", "]", ",", "# reference", "p", "[", "9", "]", ")", "# syntax", "else", ":", "p", "[", "0", "]", "=", "(", "'typeDeclarationRHS'", ",", "p", "[", "1", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_sequenceItems
sequenceItems : sequenceItems ',' sequenceItem | sequenceItem
pysmi/parser/smi.py
def p_sequenceItems(self, p): """sequenceItems : sequenceItems ',' sequenceItem | sequenceItem""" # libsmi: TODO: might this list be emtpy? n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_sequenceItems(self, p): """sequenceItems : sequenceItems ',' sequenceItem | sequenceItem""" # libsmi: TODO: might this list be emtpy? n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
[ "sequenceItems", ":", "sequenceItems", "sequenceItem", "|", "sequenceItem" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L319-L327
[ "def", "p_sequenceItems", "(", "self", ",", "p", ")", ":", "# libsmi: TODO: might this list be emtpy?", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_Syntax
Syntax : ObjectSyntax | BITS '{' NamedBits '}
pysmi/parser/smi.py
def p_Syntax(self, p): """Syntax : ObjectSyntax | BITS '{' NamedBits '}'""" # libsmi: TODO: standalone `BITS' ok? seen in RMON2-MIB # libsmi: -> no, it's only allowed in a SEQUENCE {...} n = len(p) if n == 2: p[0] = p[1] elif n == 5: p[0] = (p[1], p[3])
def p_Syntax(self, p): """Syntax : ObjectSyntax | BITS '{' NamedBits '}'""" # libsmi: TODO: standalone `BITS' ok? seen in RMON2-MIB # libsmi: -> no, it's only allowed in a SEQUENCE {...} n = len(p) if n == 2: p[0] = p[1] elif n == 5: p[0] = (p[1], p[3])
[ "Syntax", ":", "ObjectSyntax", "|", "BITS", "{", "NamedBits", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L333-L342
[ "def", "p_Syntax", "(", "self", ",", "p", ")", ":", "# libsmi: TODO: standalone `BITS' ok? seen in RMON2-MIB", "# libsmi: -> no, it's only allowed in a SEQUENCE {...}", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "elif", "n", "==", "5", ":", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_NamedBits
NamedBits : NamedBits ',' NamedBit | NamedBit
pysmi/parser/smi.py
def p_NamedBits(self, p): """NamedBits : NamedBits ',' NamedBit | NamedBit""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_NamedBits(self, p): """NamedBits : NamedBits ',' NamedBit | NamedBit""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
[ "NamedBits", ":", "NamedBits", "NamedBit", "|", "NamedBit" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L350-L357
[ "def", "p_NamedBits", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_objectIdentityClause
objectIdentityClause : LOWERCASE_IDENTIFIER OBJECT_IDENTITY STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}
pysmi/parser/smi.py
def p_objectIdentityClause(self, p): """objectIdentityClause : LOWERCASE_IDENTIFIER OBJECT_IDENTITY STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('objectIdentityClause', p[1], # id # p[2], # OBJECT_IDENTITY p[4], # status (p[5], p[6]), # description p[7], # reference p[10])
def p_objectIdentityClause(self, p): """objectIdentityClause : LOWERCASE_IDENTIFIER OBJECT_IDENTITY STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('objectIdentityClause', p[1], # id # p[2], # OBJECT_IDENTITY p[4], # status (p[5], p[6]), # description p[7], # reference p[10])
[ "objectIdentityClause", ":", "LOWERCASE_IDENTIFIER", "OBJECT_IDENTITY", "STATUS", "Status", "DESCRIPTION", "Text", "ReferPart", "COLON_COLON_EQUAL", "{", "objectIdentifier", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L363-L370
[ "def", "p_objectIdentityClause", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'objectIdentityClause'", ",", "p", "[", "1", "]", ",", "# id", "# p[2], # OBJECT_IDENTITY", "p", "[", "4", "]", ",", "# status", "(", "p", "[", "5", "]", ",", "p", "[", "6", "]", ")", ",", "# description", "p", "[", "7", "]", ",", "# reference", "p", "[", "10", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_objectTypeClause
objectTypeClause : LOWERCASE_IDENTIFIER OBJECT_TYPE SYNTAX Syntax UnitsPart MaxOrPIBAccessPart STATUS Status descriptionClause ReferPart IndexPart MibIndex DefValPart COLON_COLON_EQUAL '{' ObjectName '}
pysmi/parser/smi.py
def p_objectTypeClause(self, p): """objectTypeClause : LOWERCASE_IDENTIFIER OBJECT_TYPE SYNTAX Syntax UnitsPart MaxOrPIBAccessPart STATUS Status descriptionClause ReferPart IndexPart MibIndex DefValPart COLON_COLON_EQUAL '{' ObjectName '}'""" p[0] = ('objectTypeClause', p[1], # id # p[2], # OBJECT_TYPE p[4], # syntax p[5], # UnitsPart p[6], # MaxOrPIBAccessPart p[8], # status p[9], # descriptionClause p[10], # reference p[11], # augmentions p[12], # index p[13], # DefValPart p[16])
def p_objectTypeClause(self, p): """objectTypeClause : LOWERCASE_IDENTIFIER OBJECT_TYPE SYNTAX Syntax UnitsPart MaxOrPIBAccessPart STATUS Status descriptionClause ReferPart IndexPart MibIndex DefValPart COLON_COLON_EQUAL '{' ObjectName '}'""" p[0] = ('objectTypeClause', p[1], # id # p[2], # OBJECT_TYPE p[4], # syntax p[5], # UnitsPart p[6], # MaxOrPIBAccessPart p[8], # status p[9], # descriptionClause p[10], # reference p[11], # augmentions p[12], # index p[13], # DefValPart p[16])
[ "objectTypeClause", ":", "LOWERCASE_IDENTIFIER", "OBJECT_TYPE", "SYNTAX", "Syntax", "UnitsPart", "MaxOrPIBAccessPart", "STATUS", "Status", "descriptionClause", "ReferPart", "IndexPart", "MibIndex", "DefValPart", "COLON_COLON_EQUAL", "{", "ObjectName", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L372-L385
[ "def", "p_objectTypeClause", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'objectTypeClause'", ",", "p", "[", "1", "]", ",", "# id", "# p[2], # OBJECT_TYPE", "p", "[", "4", "]", ",", "# syntax", "p", "[", "5", "]", ",", "# UnitsPart", "p", "[", "6", "]", ",", "# MaxOrPIBAccessPart", "p", "[", "8", "]", ",", "# status", "p", "[", "9", "]", ",", "# descriptionClause", "p", "[", "10", "]", ",", "# reference", "p", "[", "11", "]", ",", "# augmentions", "p", "[", "12", "]", ",", "# index", "p", "[", "13", "]", ",", "# DefValPart", "p", "[", "16", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_VarTypes
VarTypes : VarTypes ',' VarType | VarType
pysmi/parser/smi.py
def p_VarTypes(self, p): """VarTypes : VarTypes ',' VarType | VarType""" n = len(p) if n == 4: p[0] = ('VarTypes', p[1][1] + [p[3]]) elif n == 2: p[0] = ('VarTypes', [p[1]])
def p_VarTypes(self, p): """VarTypes : VarTypes ',' VarType | VarType""" n = len(p) if n == 4: p[0] = ('VarTypes', p[1][1] + [p[3]]) elif n == 2: p[0] = ('VarTypes', [p[1]])
[ "VarTypes", ":", "VarTypes", "VarType", "|", "VarType" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L409-L416
[ "def", "p_VarTypes", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "(", "'VarTypes'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'VarTypes'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_moduleIdentityClause
moduleIdentityClause : LOWERCASE_IDENTIFIER MODULE_IDENTITY SubjectCategoriesPart LAST_UPDATED ExtUTCTime ORGANIZATION Text CONTACT_INFO Text DESCRIPTION Text RevisionPart COLON_COLON_EQUAL '{' objectIdentifier '}
pysmi/parser/smi.py
def p_moduleIdentityClause(self, p): """moduleIdentityClause : LOWERCASE_IDENTIFIER MODULE_IDENTITY SubjectCategoriesPart LAST_UPDATED ExtUTCTime ORGANIZATION Text CONTACT_INFO Text DESCRIPTION Text RevisionPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('moduleIdentityClause', p[1], # id # p[2], # MODULE_IDENTITY # XXX p[3], # SubjectCategoriesPart (p[4], p[5]), # last updated (p[6], p[7]), # organization (p[8], p[9]), # contact info (p[10], p[11]), # description p[12], # RevisionPart p[15])
def p_moduleIdentityClause(self, p): """moduleIdentityClause : LOWERCASE_IDENTIFIER MODULE_IDENTITY SubjectCategoriesPart LAST_UPDATED ExtUTCTime ORGANIZATION Text CONTACT_INFO Text DESCRIPTION Text RevisionPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('moduleIdentityClause', p[1], # id # p[2], # MODULE_IDENTITY # XXX p[3], # SubjectCategoriesPart (p[4], p[5]), # last updated (p[6], p[7]), # organization (p[8], p[9]), # contact info (p[10], p[11]), # description p[12], # RevisionPart p[15])
[ "moduleIdentityClause", ":", "LOWERCASE_IDENTIFIER", "MODULE_IDENTITY", "SubjectCategoriesPart", "LAST_UPDATED", "ExtUTCTime", "ORGANIZATION", "Text", "CONTACT_INFO", "Text", "DESCRIPTION", "Text", "RevisionPart", "COLON_COLON_EQUAL", "{", "objectIdentifier", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L450-L460
[ "def", "p_moduleIdentityClause", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'moduleIdentityClause'", ",", "p", "[", "1", "]", ",", "# id", "# p[2], # MODULE_IDENTITY", "# XXX p[3], # SubjectCategoriesPart", "(", "p", "[", "4", "]", ",", "p", "[", "5", "]", ")", ",", "# last updated", "(", "p", "[", "6", "]", ",", "p", "[", "7", "]", ")", ",", "# organization", "(", "p", "[", "8", "]", ",", "p", "[", "9", "]", ")", ",", "# contact info", "(", "p", "[", "10", "]", ",", "p", "[", "11", "]", ")", ",", "# description", "p", "[", "12", "]", ",", "# RevisionPart", "p", "[", "15", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_ObjectSyntax
ObjectSyntax : SimpleSyntax | conceptualTable | row | entryType | ApplicationSyntax | typeTag SimpleSyntax
pysmi/parser/smi.py
def p_ObjectSyntax(self, p): """ObjectSyntax : SimpleSyntax | conceptualTable | row | entryType | ApplicationSyntax | typeTag SimpleSyntax""" n = len(p) if n == 2: p[0] = p[1] elif n == 3: p[0] = p[2]
def p_ObjectSyntax(self, p): """ObjectSyntax : SimpleSyntax | conceptualTable | row | entryType | ApplicationSyntax | typeTag SimpleSyntax""" n = len(p) if n == 2: p[0] = p[1] elif n == 3: p[0] = p[2]
[ "ObjectSyntax", ":", "SimpleSyntax", "|", "conceptualTable", "|", "row", "|", "entryType", "|", "ApplicationSyntax", "|", "typeTag", "SimpleSyntax" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L494-L505
[ "def", "p_ObjectSyntax", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "elif", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_SimpleSyntax
SimpleSyntax : INTEGER | INTEGER integerSubType | INTEGER enumSpec | INTEGER32 | INTEGER32 integerSubType | UPPERCASE_IDENTIFIER enumSpec | UPPERCASE_IDENTIFIER integerSubType | OCTET STRING | OCTET STRING octetStringSubType | UPPERCASE_IDENTIFIER octetStringSubType | OBJECT IDENTIFIER anySubType
pysmi/parser/smi.py
def p_SimpleSyntax(self, p): """SimpleSyntax : INTEGER | INTEGER integerSubType | INTEGER enumSpec | INTEGER32 | INTEGER32 integerSubType | UPPERCASE_IDENTIFIER enumSpec | UPPERCASE_IDENTIFIER integerSubType | OCTET STRING | OCTET STRING octetStringSubType | UPPERCASE_IDENTIFIER octetStringSubType | OBJECT IDENTIFIER anySubType""" n = len(p) if n == 2: p[0] = ('SimpleSyntax', p[1]) elif n == 3: if p[1] == 'OCTET': p[0] = ('SimpleSyntax', p[1] + ' ' + p[2]) else: p[0] = ('SimpleSyntax', p[1], p[2]) elif n == 4: p[0] = ('SimpleSyntax', p[1] + ' ' + p[2], p[3])
def p_SimpleSyntax(self, p): """SimpleSyntax : INTEGER | INTEGER integerSubType | INTEGER enumSpec | INTEGER32 | INTEGER32 integerSubType | UPPERCASE_IDENTIFIER enumSpec | UPPERCASE_IDENTIFIER integerSubType | OCTET STRING | OCTET STRING octetStringSubType | UPPERCASE_IDENTIFIER octetStringSubType | OBJECT IDENTIFIER anySubType""" n = len(p) if n == 2: p[0] = ('SimpleSyntax', p[1]) elif n == 3: if p[1] == 'OCTET': p[0] = ('SimpleSyntax', p[1] + ' ' + p[2]) else: p[0] = ('SimpleSyntax', p[1], p[2]) elif n == 4: p[0] = ('SimpleSyntax', p[1] + ' ' + p[2], p[3])
[ "SimpleSyntax", ":", "INTEGER", "|", "INTEGER", "integerSubType", "|", "INTEGER", "enumSpec", "|", "INTEGER32", "|", "INTEGER32", "integerSubType", "|", "UPPERCASE_IDENTIFIER", "enumSpec", "|", "UPPERCASE_IDENTIFIER", "integerSubType", "|", "OCTET", "STRING", "|", "OCTET", "STRING", "octetStringSubType", "|", "UPPERCASE_IDENTIFIER", "octetStringSubType", "|", "OBJECT", "IDENTIFIER", "anySubType" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L521-L544
[ "def", "p_SimpleSyntax", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'SimpleSyntax'", ",", "p", "[", "1", "]", ")", "elif", "n", "==", "3", ":", "if", "p", "[", "1", "]", "==", "'OCTET'", ":", "p", "[", "0", "]", "=", "(", "'SimpleSyntax'", ",", "p", "[", "1", "]", "+", "' '", "+", "p", "[", "2", "]", ")", "else", ":", "p", "[", "0", "]", "=", "(", "'SimpleSyntax'", ",", "p", "[", "1", "]", ",", "p", "[", "2", "]", ")", "elif", "n", "==", "4", ":", "p", "[", "0", "]", "=", "(", "'SimpleSyntax'", ",", "p", "[", "1", "]", "+", "' '", "+", "p", "[", "2", "]", ",", "p", "[", "3", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_valueofSimpleSyntax
valueofSimpleSyntax : NUMBER | NEGATIVENUMBER | NUMBER64 | NEGATIVENUMBER64 | HEX_STRING | BIN_STRING | LOWERCASE_IDENTIFIER | QUOTED_STRING | '{' objectIdentifier_defval '}
pysmi/parser/smi.py
def p_valueofSimpleSyntax(self, p): """valueofSimpleSyntax : NUMBER | NEGATIVENUMBER | NUMBER64 | NEGATIVENUMBER64 | HEX_STRING | BIN_STRING | LOWERCASE_IDENTIFIER | QUOTED_STRING | '{' objectIdentifier_defval '}'""" # libsmi for objectIdentifier_defval: # This is only for some MIBs with invalid numerical # OID notation for DEFVALs. We DO NOT parse them # correctly. We just don't want to produce a # parser error. n = len(p) if n == 2: p[0] = p[1] elif n == 4: # XXX pass
def p_valueofSimpleSyntax(self, p): """valueofSimpleSyntax : NUMBER | NEGATIVENUMBER | NUMBER64 | NEGATIVENUMBER64 | HEX_STRING | BIN_STRING | LOWERCASE_IDENTIFIER | QUOTED_STRING | '{' objectIdentifier_defval '}'""" # libsmi for objectIdentifier_defval: # This is only for some MIBs with invalid numerical # OID notation for DEFVALs. We DO NOT parse them # correctly. We just don't want to produce a # parser error. n = len(p) if n == 2: p[0] = p[1] elif n == 4: # XXX pass
[ "valueofSimpleSyntax", ":", "NUMBER", "|", "NEGATIVENUMBER", "|", "NUMBER64", "|", "NEGATIVENUMBER64", "|", "HEX_STRING", "|", "BIN_STRING", "|", "LOWERCASE_IDENTIFIER", "|", "QUOTED_STRING", "|", "{", "objectIdentifier_defval", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L546-L565
[ "def", "p_valueofSimpleSyntax", "(", "self", ",", "p", ")", ":", "# libsmi for objectIdentifier_defval:", "# This is only for some MIBs with invalid numerical", "# OID notation for DEFVALs. We DO NOT parse them", "# correctly. We just don't want to produce a", "# parser error.", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "elif", "n", "==", "4", ":", "# XXX", "pass" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_sequenceSimpleSyntax
sequenceSimpleSyntax : INTEGER anySubType | INTEGER32 anySubType | OCTET STRING anySubType | OBJECT IDENTIFIER anySubType
pysmi/parser/smi.py
def p_sequenceSimpleSyntax(self, p): """sequenceSimpleSyntax : INTEGER anySubType | INTEGER32 anySubType | OCTET STRING anySubType | OBJECT IDENTIFIER anySubType""" n = len(p) if n == 3: p[0] = p[1] # XXX not supporting subtypes here elif n == 4: p[0] = p[1] + ' ' + p[2]
def p_sequenceSimpleSyntax(self, p): """sequenceSimpleSyntax : INTEGER anySubType | INTEGER32 anySubType | OCTET STRING anySubType | OBJECT IDENTIFIER anySubType""" n = len(p) if n == 3: p[0] = p[1] # XXX not supporting subtypes here elif n == 4: p[0] = p[1] + ' ' + p[2]
[ "sequenceSimpleSyntax", ":", "INTEGER", "anySubType", "|", "INTEGER32", "anySubType", "|", "OCTET", "STRING", "anySubType", "|", "OBJECT", "IDENTIFIER", "anySubType" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L567-L576
[ "def", "p_sequenceSimpleSyntax", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "# XXX not supporting subtypes here", "elif", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "' '", "+", "p", "[", "2", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_ApplicationSyntax
ApplicationSyntax : IPADDRESS anySubType | COUNTER32 | COUNTER32 integerSubType | GAUGE32 | GAUGE32 integerSubType | UNSIGNED32 | UNSIGNED32 integerSubType | TIMETICKS anySubType | OPAQUE | OPAQUE octetStringSubType | COUNTER64 | COUNTER64 integerSubType
pysmi/parser/smi.py
def p_ApplicationSyntax(self, p): """ApplicationSyntax : IPADDRESS anySubType | COUNTER32 | COUNTER32 integerSubType | GAUGE32 | GAUGE32 integerSubType | UNSIGNED32 | UNSIGNED32 integerSubType | TIMETICKS anySubType | OPAQUE | OPAQUE octetStringSubType | COUNTER64 | COUNTER64 integerSubType""" # COUNTER32 and COUNTER64 was with anySubType in libsmi n = len(p) if n == 2: p[0] = ('ApplicationSyntax', p[1]) elif n == 3: p[0] = ('ApplicationSyntax', p[1], p[2])
def p_ApplicationSyntax(self, p): """ApplicationSyntax : IPADDRESS anySubType | COUNTER32 | COUNTER32 integerSubType | GAUGE32 | GAUGE32 integerSubType | UNSIGNED32 | UNSIGNED32 integerSubType | TIMETICKS anySubType | OPAQUE | OPAQUE octetStringSubType | COUNTER64 | COUNTER64 integerSubType""" # COUNTER32 and COUNTER64 was with anySubType in libsmi n = len(p) if n == 2: p[0] = ('ApplicationSyntax', p[1]) elif n == 3: p[0] = ('ApplicationSyntax', p[1], p[2])
[ "ApplicationSyntax", ":", "IPADDRESS", "anySubType", "|", "COUNTER32", "|", "COUNTER32", "integerSubType", "|", "GAUGE32", "|", "GAUGE32", "integerSubType", "|", "UNSIGNED32", "|", "UNSIGNED32", "integerSubType", "|", "TIMETICKS", "anySubType", "|", "OPAQUE", "|", "OPAQUE", "octetStringSubType", "|", "COUNTER64", "|", "COUNTER64", "integerSubType" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L578-L596
[ "def", "p_ApplicationSyntax", "(", "self", ",", "p", ")", ":", "# COUNTER32 and COUNTER64 was with anySubType in libsmi", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'ApplicationSyntax'", ",", "p", "[", "1", "]", ")", "elif", "n", "==", "3", ":", "p", "[", "0", "]", "=", "(", "'ApplicationSyntax'", ",", "p", "[", "1", "]", ",", "p", "[", "2", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_sequenceApplicationSyntax
sequenceApplicationSyntax : IPADDRESS anySubType | COUNTER32 anySubType | GAUGE32 anySubType | UNSIGNED32 anySubType | TIMETICKS anySubType | OPAQUE | COUNTER64 anySubType
pysmi/parser/smi.py
def p_sequenceApplicationSyntax(self, p): """sequenceApplicationSyntax : IPADDRESS anySubType | COUNTER32 anySubType | GAUGE32 anySubType | UNSIGNED32 anySubType | TIMETICKS anySubType | OPAQUE | COUNTER64 anySubType""" n = len(p) if n == 2: p[0] = p[1] elif n == 3: p[0] = p[1]
def p_sequenceApplicationSyntax(self, p): """sequenceApplicationSyntax : IPADDRESS anySubType | COUNTER32 anySubType | GAUGE32 anySubType | UNSIGNED32 anySubType | TIMETICKS anySubType | OPAQUE | COUNTER64 anySubType""" n = len(p) if n == 2: p[0] = p[1] elif n == 3: p[0] = p[1]
[ "sequenceApplicationSyntax", ":", "IPADDRESS", "anySubType", "|", "COUNTER32", "anySubType", "|", "GAUGE32", "anySubType", "|", "UNSIGNED32", "anySubType", "|", "TIMETICKS", "anySubType", "|", "OPAQUE", "|", "COUNTER64", "anySubType" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L598-L610
[ "def", "p_sequenceApplicationSyntax", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "elif", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_ranges
ranges : ranges '|' range | range
pysmi/parser/smi.py
def p_ranges(self, p): """ranges : ranges '|' range | range""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_ranges(self, p): """ranges : ranges '|' range | range""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
[ "ranges", ":", "ranges", "|", "range", "|", "range" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L628-L635
[ "def", "p_ranges", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_range
range : value DOT_DOT value | value
pysmi/parser/smi.py
def p_range(self, p): """range : value DOT_DOT value | value""" n = len(p) if n == 2: p[0] = (p[1],) elif n == 4: p[0] = (p[1], p[3])
def p_range(self, p): """range : value DOT_DOT value | value""" n = len(p) if n == 2: p[0] = (p[1],) elif n == 4: p[0] = (p[1], p[3])
[ "range", ":", "value", "DOT_DOT", "value", "|", "value" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L637-L644
[ "def", "p_range", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", ",", ")", "elif", "n", "==", "4", ":", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_enumItems
enumItems : enumItems ',' enumItem | enumItem
pysmi/parser/smi.py
def p_enumItems(self, p): """enumItems : enumItems ',' enumItem | enumItem""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_enumItems(self, p): """enumItems : enumItems ',' enumItem | enumItem""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
[ "enumItems", ":", "enumItems", "enumItem", "|", "enumItem" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L659-L666
[ "def", "p_enumItems", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_IndexTypes
IndexTypes : IndexTypes ',' IndexType | IndexType
pysmi/parser/smi.py
def p_IndexTypes(self, p): """IndexTypes : IndexTypes ',' IndexType | IndexType""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_IndexTypes(self, p): """IndexTypes : IndexTypes ',' IndexType | IndexType""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
[ "IndexTypes", ":", "IndexTypes", "IndexType", "|", "IndexType" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L710-L717
[ "def", "p_IndexTypes", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_IndexType
IndexType : IMPLIED Index | Index
pysmi/parser/smi.py
def p_IndexType(self, p): """IndexType : IMPLIED Index | Index""" n = len(p) if n == 2: p[0] = (0, p[1]) elif n == 3: p[0] = (1, p[2])
def p_IndexType(self, p): """IndexType : IMPLIED Index | Index""" n = len(p) if n == 2: p[0] = (0, p[1]) elif n == 3: p[0] = (1, p[2])
[ "IndexType", ":", "IMPLIED", "Index", "|", "Index" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L719-L726
[ "def", "p_IndexType", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "0", ",", "p", "[", "1", "]", ")", "elif", "n", "==", "3", ":", "p", "[", "0", "]", "=", "(", "1", ",", "p", "[", "2", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_Value
Value : valueofObjectSyntax | '{' BitsValue '}
pysmi/parser/smi.py
def p_Value(self, p): """Value : valueofObjectSyntax | '{' BitsValue '}'""" n = len(p) if n == 2: p[0] = p[1] elif n == 4: p[0] = p[2]
def p_Value(self, p): """Value : valueofObjectSyntax | '{' BitsValue '}'""" n = len(p) if n == 2: p[0] = p[1] elif n == 4: p[0] = p[2]
[ "Value", ":", "valueofObjectSyntax", "|", "{", "BitsValue", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L744-L751
[ "def", "p_Value", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "elif", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_BitNames
BitNames : BitNames ',' LOWERCASE_IDENTIFIER | LOWERCASE_IDENTIFIER
pysmi/parser/smi.py
def p_BitNames(self, p): """BitNames : BitNames ',' LOWERCASE_IDENTIFIER | LOWERCASE_IDENTIFIER""" n = len(p) if n == 4: p[0] = ('BitNames', p[1][1] + [p[3]]) elif n == 2: p[0] = ('BitNames', [p[1]])
def p_BitNames(self, p): """BitNames : BitNames ',' LOWERCASE_IDENTIFIER | LOWERCASE_IDENTIFIER""" n = len(p) if n == 4: p[0] = ('BitNames', p[1][1] + [p[3]]) elif n == 2: p[0] = ('BitNames', [p[1]])
[ "BitNames", ":", "BitNames", "LOWERCASE_IDENTIFIER", "|", "LOWERCASE_IDENTIFIER" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L759-L766
[ "def", "p_BitNames", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "(", "'BitNames'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'BitNames'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_Revisions
Revisions : Revisions Revision | Revision
pysmi/parser/smi.py
def p_Revisions(self, p): """Revisions : Revisions Revision | Revision""" n = len(p) if n == 3: p[0] = ('Revisions', p[1][1] + [p[2]]) elif n == 2: p[0] = ('Revisions', [p[1]])
def p_Revisions(self, p): """Revisions : Revisions Revision | Revision""" n = len(p) if n == 3: p[0] = ('Revisions', p[1][1] + [p[2]]) elif n == 2: p[0] = ('Revisions', [p[1]])
[ "Revisions", ":", "Revisions", "Revision", "|", "Revision" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L788-L795
[ "def", "p_Revisions", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "(", "'Revisions'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'Revisions'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_Objects
Objects : Objects ',' Object | Object
pysmi/parser/smi.py
def p_Objects(self, p): """Objects : Objects ',' Object | Object""" n = len(p) if n == 4: p[0] = ('Objects', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Objects', [p[1]])
def p_Objects(self, p): """Objects : Objects ',' Object | Object""" n = len(p) if n == 4: p[0] = ('Objects', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Objects', [p[1]])
[ "Objects", ":", "Objects", "Object", "|", "Object" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L811-L818
[ "def", "p_Objects", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "(", "'Objects'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'Objects'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_Notifications
Notifications : Notifications ',' Notification | Notification
pysmi/parser/smi.py
def p_Notifications(self, p): """Notifications : Notifications ',' Notification | Notification""" n = len(p) if n == 4: p[0] = ('Notifications', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Notifications', [p[1]])
def p_Notifications(self, p): """Notifications : Notifications ',' Notification | Notification""" n = len(p) if n == 4: p[0] = ('Notifications', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Notifications', [p[1]])
[ "Notifications", ":", "Notifications", "Notification", "|", "Notification" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L828-L835
[ "def", "p_Notifications", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "(", "'Notifications'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'Notifications'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_subidentifiers
subidentifiers : subidentifiers subidentifier | subidentifier
pysmi/parser/smi.py
def p_subidentifiers(self, p): """subidentifiers : subidentifiers subidentifier | subidentifier""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
def p_subidentifiers(self, p): """subidentifiers : subidentifiers subidentifier | subidentifier""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
[ "subidentifiers", ":", "subidentifiers", "subidentifier", "|", "subidentifier" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L853-L860
[ "def", "p_subidentifiers", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_subidentifier
subidentifier : fuzzy_lowercase_identifier | NUMBER | LOWERCASE_IDENTIFIER '(' NUMBER ')
pysmi/parser/smi.py
def p_subidentifier(self, p): """subidentifier : fuzzy_lowercase_identifier | NUMBER | LOWERCASE_IDENTIFIER '(' NUMBER ')'""" n = len(p) if n == 2: p[0] = p[1] elif n == 5: # NOTE: we are not creating new symbol p[1] because formally # it is not defined in *this* MIB p[0] = (p[1], p[3])
def p_subidentifier(self, p): """subidentifier : fuzzy_lowercase_identifier | NUMBER | LOWERCASE_IDENTIFIER '(' NUMBER ')'""" n = len(p) if n == 2: p[0] = p[1] elif n == 5: # NOTE: we are not creating new symbol p[1] because formally # it is not defined in *this* MIB p[0] = (p[1], p[3])
[ "subidentifier", ":", "fuzzy_lowercase_identifier", "|", "NUMBER", "|", "LOWERCASE_IDENTIFIER", "(", "NUMBER", ")" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L862-L872
[ "def", "p_subidentifier", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "elif", "n", "==", "5", ":", "# NOTE: we are not creating new symbol p[1] because formally", "# it is not defined in *this* MIB", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_subidentifiers_defval
subidentifiers_defval : subidentifiers_defval subidentifier_defval | subidentifier_defval
pysmi/parser/smi.py
def p_subidentifiers_defval(self, p): """subidentifiers_defval : subidentifiers_defval subidentifier_defval | subidentifier_defval""" n = len(p) if n == 3: p[0] = ('subidentifiers_defval', p[1][1] + [p[2]]) elif n == 2: p[0] = ('subidentifiers_defval', [p[1]])
def p_subidentifiers_defval(self, p): """subidentifiers_defval : subidentifiers_defval subidentifier_defval | subidentifier_defval""" n = len(p) if n == 3: p[0] = ('subidentifiers_defval', p[1][1] + [p[2]]) elif n == 2: p[0] = ('subidentifiers_defval', [p[1]])
[ "subidentifiers_defval", ":", "subidentifiers_defval", "subidentifier_defval", "|", "subidentifier_defval" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L878-L885
[ "def", "p_subidentifiers_defval", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "(", "'subidentifiers_defval'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'subidentifiers_defval'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_subidentifier_defval
subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')' | NUMBER
pysmi/parser/smi.py
def p_subidentifier_defval(self, p): """subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')' | NUMBER""" n = len(p) if n == 2: p[0] = ('subidentifier_defval', p[1]) elif n == 5: p[0] = ('subidentifier_defval', p[1], p[3])
def p_subidentifier_defval(self, p): """subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')' | NUMBER""" n = len(p) if n == 2: p[0] = ('subidentifier_defval', p[1]) elif n == 5: p[0] = ('subidentifier_defval', p[1], p[3])
[ "subidentifier_defval", ":", "LOWERCASE_IDENTIFIER", "(", "NUMBER", ")", "|", "NUMBER" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L887-L894
[ "def", "p_subidentifier_defval", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'subidentifier_defval'", ",", "p", "[", "1", "]", ")", "elif", "n", "==", "5", ":", "p", "[", "0", "]", "=", "(", "'subidentifier_defval'", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_objectGroupClause
objectGroupClause : LOWERCASE_IDENTIFIER OBJECT_GROUP ObjectGroupObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}
pysmi/parser/smi.py
def p_objectGroupClause(self, p): """objectGroupClause : LOWERCASE_IDENTIFIER OBJECT_GROUP ObjectGroupObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('objectGroupClause', p[1], # id p[3], # objects p[5], # status (p[6], p[7]), # description p[8], # reference p[11])
def p_objectGroupClause(self, p): """objectGroupClause : LOWERCASE_IDENTIFIER OBJECT_GROUP ObjectGroupObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('objectGroupClause', p[1], # id p[3], # objects p[5], # status (p[6], p[7]), # description p[8], # reference p[11])
[ "objectGroupClause", ":", "LOWERCASE_IDENTIFIER", "OBJECT_GROUP", "ObjectGroupObjectsPart", "STATUS", "Status", "DESCRIPTION", "Text", "ReferPart", "COLON_COLON_EQUAL", "{", "objectIdentifier", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L896-L904
[ "def", "p_objectGroupClause", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'objectGroupClause'", ",", "p", "[", "1", "]", ",", "# id", "p", "[", "3", "]", ",", "# objects", "p", "[", "5", "]", ",", "# status", "(", "p", "[", "6", "]", ",", "p", "[", "7", "]", ")", ",", "# description", "p", "[", "8", "]", ",", "# reference", "p", "[", "11", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_notificationGroupClause
notificationGroupClause : LOWERCASE_IDENTIFIER NOTIFICATION_GROUP NotificationsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}
pysmi/parser/smi.py
def p_notificationGroupClause(self, p): """notificationGroupClause : LOWERCASE_IDENTIFIER NOTIFICATION_GROUP NotificationsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('notificationGroupClause', p[1], # id p[3], # notifications p[5], # status (p[6], p[7]), # description p[8], # reference p[11])
def p_notificationGroupClause(self, p): """notificationGroupClause : LOWERCASE_IDENTIFIER NOTIFICATION_GROUP NotificationsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('notificationGroupClause', p[1], # id p[3], # notifications p[5], # status (p[6], p[7]), # description p[8], # reference p[11])
[ "notificationGroupClause", ":", "LOWERCASE_IDENTIFIER", "NOTIFICATION_GROUP", "NotificationsPart", "STATUS", "Status", "DESCRIPTION", "Text", "ReferPart", "COLON_COLON_EQUAL", "{", "objectIdentifier", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L906-L914
[ "def", "p_notificationGroupClause", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'notificationGroupClause'", ",", "p", "[", "1", "]", ",", "# id", "p", "[", "3", "]", ",", "# notifications", "p", "[", "5", "]", ",", "# status", "(", "p", "[", "6", "]", ",", "p", "[", "7", "]", ")", ",", "# description", "p", "[", "8", "]", ",", "# reference", "p", "[", "11", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_moduleComplianceClause
moduleComplianceClause : LOWERCASE_IDENTIFIER MODULE_COMPLIANCE STATUS Status DESCRIPTION Text ReferPart ComplianceModulePart COLON_COLON_EQUAL '{' objectIdentifier '}
pysmi/parser/smi.py
def p_moduleComplianceClause(self, p): """moduleComplianceClause : LOWERCASE_IDENTIFIER MODULE_COMPLIANCE STATUS Status DESCRIPTION Text ReferPart ComplianceModulePart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('moduleComplianceClause', p[1], # id # p[2], # MODULE_COMPLIANCE p[4], # status (p[5], p[6]), # description p[7], # reference p[8], # ComplianceModules p[11])
def p_moduleComplianceClause(self, p): """moduleComplianceClause : LOWERCASE_IDENTIFIER MODULE_COMPLIANCE STATUS Status DESCRIPTION Text ReferPart ComplianceModulePart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('moduleComplianceClause', p[1], # id # p[2], # MODULE_COMPLIANCE p[4], # status (p[5], p[6]), # description p[7], # reference p[8], # ComplianceModules p[11])
[ "moduleComplianceClause", ":", "LOWERCASE_IDENTIFIER", "MODULE_COMPLIANCE", "STATUS", "Status", "DESCRIPTION", "Text", "ReferPart", "ComplianceModulePart", "COLON_COLON_EQUAL", "{", "objectIdentifier", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L916-L925
[ "def", "p_moduleComplianceClause", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'moduleComplianceClause'", ",", "p", "[", "1", "]", ",", "# id", "# p[2], # MODULE_COMPLIANCE", "p", "[", "4", "]", ",", "# status", "(", "p", "[", "5", "]", ",", "p", "[", "6", "]", ")", ",", "# description", "p", "[", "7", "]", ",", "# reference", "p", "[", "8", "]", ",", "# ComplianceModules", "p", "[", "11", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_ComplianceModules
ComplianceModules : ComplianceModules ComplianceModule | ComplianceModule
pysmi/parser/smi.py
def p_ComplianceModules(self, p): """ComplianceModules : ComplianceModules ComplianceModule | ComplianceModule""" n = len(p) if n == 3: p[0] = ('ComplianceModules', p[1][1] + [p[2]]) elif n == 2: p[0] = ('ComplianceModules', [p[1]])
def p_ComplianceModules(self, p): """ComplianceModules : ComplianceModules ComplianceModule | ComplianceModule""" n = len(p) if n == 3: p[0] = ('ComplianceModules', p[1][1] + [p[2]]) elif n == 2: p[0] = ('ComplianceModules', [p[1]])
[ "ComplianceModules", ":", "ComplianceModules", "ComplianceModule", "|", "ComplianceModule" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L931-L938
[ "def", "p_ComplianceModules", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "(", "'ComplianceModules'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'ComplianceModules'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_ComplianceModule
ComplianceModule : MODULE ComplianceModuleName MandatoryPart CompliancePart
pysmi/parser/smi.py
def p_ComplianceModule(self, p): """ComplianceModule : MODULE ComplianceModuleName MandatoryPart CompliancePart""" objects = p[3] and p[3][1] or [] objects += p[4] and p[4][1] or [] p[0] = (p[2], # ModuleName objects)
def p_ComplianceModule(self, p): """ComplianceModule : MODULE ComplianceModuleName MandatoryPart CompliancePart""" objects = p[3] and p[3][1] or [] objects += p[4] and p[4][1] or [] p[0] = (p[2], # ModuleName objects)
[ "ComplianceModule", ":", "MODULE", "ComplianceModuleName", "MandatoryPart", "CompliancePart" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L940-L945
[ "def", "p_ComplianceModule", "(", "self", ",", "p", ")", ":", "objects", "=", "p", "[", "3", "]", "and", "p", "[", "3", "]", "[", "1", "]", "or", "[", "]", "objects", "+=", "p", "[", "4", "]", "and", "p", "[", "4", "]", "[", "1", "]", "or", "[", "]", "p", "[", "0", "]", "=", "(", "p", "[", "2", "]", ",", "# ModuleName", "objects", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_MandatoryGroups
MandatoryGroups : MandatoryGroups ',' MandatoryGroup | MandatoryGroup
pysmi/parser/smi.py
def p_MandatoryGroups(self, p): """MandatoryGroups : MandatoryGroups ',' MandatoryGroup | MandatoryGroup""" n = len(p) if n == 4: p[0] = ('MandatoryGroups', p[1][1] + [p[3]]) elif n == 2: p[0] = ('MandatoryGroups', [p[1]])
def p_MandatoryGroups(self, p): """MandatoryGroups : MandatoryGroups ',' MandatoryGroup | MandatoryGroup""" n = len(p) if n == 4: p[0] = ('MandatoryGroups', p[1][1] + [p[3]]) elif n == 2: p[0] = ('MandatoryGroups', [p[1]])
[ "MandatoryGroups", ":", "MandatoryGroups", "MandatoryGroup", "|", "MandatoryGroup" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L959-L966
[ "def", "p_MandatoryGroups", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "(", "'MandatoryGroups'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'MandatoryGroups'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_Compliances
Compliances : Compliances Compliance | Compliance
pysmi/parser/smi.py
def p_Compliances(self, p): """Compliances : Compliances Compliance | Compliance""" n = len(p) if n == 3: p[0] = p[1] and p[2] and ('Compliances', p[1][1] + [p[2]]) or p[1] elif n == 2: p[0] = p[1] and ('Compliances', [p[1]]) or None
def p_Compliances(self, p): """Compliances : Compliances Compliance | Compliance""" n = len(p) if n == 3: p[0] = p[1] and p[2] and ('Compliances', p[1][1] + [p[2]]) or p[1] elif n == 2: p[0] = p[1] and ('Compliances', [p[1]]) or None
[ "Compliances", ":", "Compliances", "Compliance", "|", "Compliance" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L978-L985
[ "def", "p_Compliances", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "and", "p", "[", "2", "]", "and", "(", "'Compliances'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]", ")", "or", "p", "[", "1", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "and", "(", "'Compliances'", ",", "[", "p", "[", "1", "]", "]", ")", "or", "None" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_agentCapabilitiesClause
agentCapabilitiesClause : LOWERCASE_IDENTIFIER AGENT_CAPABILITIES PRODUCT_RELEASE Text STATUS Status DESCRIPTION Text ReferPart ModulePart_Capabilities COLON_COLON_EQUAL '{' objectIdentifier '}
pysmi/parser/smi.py
def p_agentCapabilitiesClause(self, p): """agentCapabilitiesClause : LOWERCASE_IDENTIFIER AGENT_CAPABILITIES PRODUCT_RELEASE Text STATUS Status DESCRIPTION Text ReferPart ModulePart_Capabilities COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('agentCapabilitiesClause', p[1], # id # p[2], # AGENT_CAPABILITIES (p[3], p[4]), # product release p[6], # status (p[7], p[8]), # description p[9], # reference # p[10], # module capabilities p[13])
def p_agentCapabilitiesClause(self, p): """agentCapabilitiesClause : LOWERCASE_IDENTIFIER AGENT_CAPABILITIES PRODUCT_RELEASE Text STATUS Status DESCRIPTION Text ReferPart ModulePart_Capabilities COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('agentCapabilitiesClause', p[1], # id # p[2], # AGENT_CAPABILITIES (p[3], p[4]), # product release p[6], # status (p[7], p[8]), # description p[9], # reference # p[10], # module capabilities p[13])
[ "agentCapabilitiesClause", ":", "LOWERCASE_IDENTIFIER", "AGENT_CAPABILITIES", "PRODUCT_RELEASE", "Text", "STATUS", "Status", "DESCRIPTION", "Text", "ReferPart", "ModulePart_Capabilities", "COLON_COLON_EQUAL", "{", "objectIdentifier", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L1030-L1039
[ "def", "p_agentCapabilitiesClause", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'agentCapabilitiesClause'", ",", "p", "[", "1", "]", ",", "# id", "# p[2], # AGENT_CAPABILITIES", "(", "p", "[", "3", "]", ",", "p", "[", "4", "]", ")", ",", "# product release", "p", "[", "6", "]", ",", "# status", "(", "p", "[", "7", "]", ",", "p", "[", "8", "]", ")", ",", "# description", "p", "[", "9", "]", ",", "# reference", "# p[10], # module capabilities", "p", "[", "13", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SmiV2Parser.p_Cells
Cells : Cells ',' Cell | Cell
pysmi/parser/smi.py
def p_Cells(self, p): """Cells : Cells ',' Cell | Cell""" n = len(p) if n == 4: p[0] = ('Cells', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Cells', [p[1]])
def p_Cells(self, p): """Cells : Cells ',' Cell | Cell""" n = len(p) if n == 4: p[0] = ('Cells', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Cells', [p[1]])
[ "Cells", ":", "Cells", "Cell", "|", "Cell" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L1126-L1133
[ "def", "p_Cells", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "(", "'Cells'", ",", "p", "[", "1", "]", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", ")", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "(", "'Cells'", ",", "[", "p", "[", "1", "]", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
SupportIndex.p_typeSMIv1
typeSMIv1 : INTEGER | OCTET STRING | IPADDRESS | NETWORKADDRESS
pysmi/parser/smi.py
def p_typeSMIv1(self, p): """typeSMIv1 : INTEGER | OCTET STRING | IPADDRESS | NETWORKADDRESS""" n = len(p) indextype = n == 3 and p[1] + ' ' + p[2] or p[1] p[0] = indextype
def p_typeSMIv1(self, p): """typeSMIv1 : INTEGER | OCTET STRING | IPADDRESS | NETWORKADDRESS""" n = len(p) indextype = n == 3 and p[1] + ' ' + p[2] or p[1] p[0] = indextype
[ "typeSMIv1", ":", "INTEGER", "|", "OCTET", "STRING", "|", "IPADDRESS", "|", "NETWORKADDRESS" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L1249-L1256
[ "def", "p_typeSMIv1", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "indextype", "=", "n", "==", "3", "and", "p", "[", "1", "]", "+", "' '", "+", "p", "[", "2", "]", "or", "p", "[", "1", "]", "p", "[", "0", "]", "=", "indextype" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
CommaAndSpaces.p_enumItems
enumItems : enumItems ',' enumItem | enumItem | enumItems enumItem | enumItems ',
pysmi/parser/smi.py
def p_enumItems(self, p): """enumItems : enumItems ',' enumItem | enumItem | enumItems enumItem | enumItems ','""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]] elif n == 3: # typo case if p[2] == ',': p[0] = p[1] else: p[0] = p[1] + [p[2]]
def p_enumItems(self, p): """enumItems : enumItems ',' enumItem | enumItem | enumItems enumItem | enumItems ','""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]] elif n == 3: # typo case if p[2] == ',': p[0] = p[1] else: p[0] = p[1] + [p[2]]
[ "enumItems", ":", "enumItems", "enumItem", "|", "enumItem", "|", "enumItems", "enumItem", "|", "enumItems" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L1302-L1316
[ "def", "p_enumItems", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", "elif", "n", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]", "elif", "n", "==", "3", ":", "# typo case", "if", "p", "[", "2", "]", "==", "','", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "else", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "2", "]", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
LowcaseIdentifier.p_notificationTypeClause
notificationTypeClause : fuzzy_lowercase_identifier NOTIFICATION_TYPE NotificationObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' NotificationName '}
pysmi/parser/smi.py
def p_notificationTypeClause(self, p): """notificationTypeClause : fuzzy_lowercase_identifier NOTIFICATION_TYPE NotificationObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' NotificationName '}'""" # some MIBs have uppercase and/or lowercase id p[0] = ('notificationTypeClause', p[1], # id # p[2], # NOTIFICATION_TYPE p[3], # NotificationObjectsPart p[5], # status (p[6], p[7]), # description p[8], # Reference p[11])
def p_notificationTypeClause(self, p): """notificationTypeClause : fuzzy_lowercase_identifier NOTIFICATION_TYPE NotificationObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' NotificationName '}'""" # some MIBs have uppercase and/or lowercase id p[0] = ('notificationTypeClause', p[1], # id # p[2], # NOTIFICATION_TYPE p[3], # NotificationObjectsPart p[5], # status (p[6], p[7]), # description p[8], # Reference p[11])
[ "notificationTypeClause", ":", "fuzzy_lowercase_identifier", "NOTIFICATION_TYPE", "NotificationObjectsPart", "STATUS", "Status", "DESCRIPTION", "Text", "ReferPart", "COLON_COLON_EQUAL", "{", "NotificationName", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L1333-L1341
[ "def", "p_notificationTypeClause", "(", "self", ",", "p", ")", ":", "# some MIBs have uppercase and/or lowercase id", "p", "[", "0", "]", "=", "(", "'notificationTypeClause'", ",", "p", "[", "1", "]", ",", "# id", "# p[2], # NOTIFICATION_TYPE", "p", "[", "3", "]", ",", "# NotificationObjectsPart", "p", "[", "5", "]", ",", "# status", "(", "p", "[", "6", "]", ",", "p", "[", "7", "]", ")", ",", "# description", "p", "[", "8", "]", ",", "# Reference", "p", "[", "11", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
CurlyBracesInEnterprises.p_trapTypeClause
trapTypeClause : fuzzy_lowercase_identifier TRAP_TYPE EnterprisePart VarPart DescrPart ReferPart COLON_COLON_EQUAL NUMBER
pysmi/parser/smi.py
def p_trapTypeClause(self, p): """trapTypeClause : fuzzy_lowercase_identifier TRAP_TYPE EnterprisePart VarPart DescrPart ReferPart COLON_COLON_EQUAL NUMBER""" # libsmi: TODO: range of number? p[0] = ('trapTypeClause', p[1], # fuzzy_lowercase_identifier # p[2], # TRAP_TYPE p[3], # EnterprisePart (objectIdentifier) p[4], # VarPart p[5], # description p[6], # reference p[8])
def p_trapTypeClause(self, p): """trapTypeClause : fuzzy_lowercase_identifier TRAP_TYPE EnterprisePart VarPart DescrPart ReferPart COLON_COLON_EQUAL NUMBER""" # libsmi: TODO: range of number? p[0] = ('trapTypeClause', p[1], # fuzzy_lowercase_identifier # p[2], # TRAP_TYPE p[3], # EnterprisePart (objectIdentifier) p[4], # VarPart p[5], # description p[6], # reference p[8])
[ "trapTypeClause", ":", "fuzzy_lowercase_identifier", "TRAP_TYPE", "EnterprisePart", "VarPart", "DescrPart", "ReferPart", "COLON_COLON_EQUAL", "NUMBER" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L1348-L1357
[ "def", "p_trapTypeClause", "(", "self", ",", "p", ")", ":", "# libsmi: TODO: range of number?", "p", "[", "0", "]", "=", "(", "'trapTypeClause'", ",", "p", "[", "1", "]", ",", "# fuzzy_lowercase_identifier", "# p[2], # TRAP_TYPE", "p", "[", "3", "]", ",", "# EnterprisePart (objectIdentifier)", "p", "[", "4", "]", ",", "# VarPart", "p", "[", "5", "]", ",", "# description", "p", "[", "6", "]", ",", "# reference", "p", "[", "8", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
CurlyBracesInEnterprises.p_EnterprisePart
EnterprisePart : ENTERPRISE objectIdentifier | ENTERPRISE '{' objectIdentifier '}
pysmi/parser/smi.py
def p_EnterprisePart(self, p): """EnterprisePart : ENTERPRISE objectIdentifier | ENTERPRISE '{' objectIdentifier '}'""" n = len(p) if n == 3: p[0] = p[2] elif n == 5: # common mistake case p[0] = p[3]
def p_EnterprisePart(self, p): """EnterprisePart : ENTERPRISE objectIdentifier | ENTERPRISE '{' objectIdentifier '}'""" n = len(p) if n == 3: p[0] = p[2] elif n == 5: # common mistake case p[0] = p[3]
[ "EnterprisePart", ":", "ENTERPRISE", "objectIdentifier", "|", "ENTERPRISE", "{", "objectIdentifier", "}" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L1360-L1367
[ "def", "p_EnterprisePart", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]", "elif", "n", "==", "5", ":", "# common mistake case", "p", "[", "0", "]", "=", "p", "[", "3", "]" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
NoCells.p_CreationPart
CreationPart : CREATION_REQUIRES '{' Cells '}' | CREATION_REQUIRES '{' '}' | empty
pysmi/parser/smi.py
def p_CreationPart(self, p): """CreationPart : CREATION_REQUIRES '{' Cells '}' | CREATION_REQUIRES '{' '}' | empty""" n = len(p) if n == 5: p[0] = (p[1], p[3])
def p_CreationPart(self, p): """CreationPart : CREATION_REQUIRES '{' Cells '}' | CREATION_REQUIRES '{' '}' | empty""" n = len(p) if n == 5: p[0] = (p[1], p[3])
[ "CreationPart", ":", "CREATION_REQUIRES", "{", "Cells", "}", "|", "CREATION_REQUIRES", "{", "}", "|", "empty" ]
etingof/pysmi
python
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L1374-L1380
[ "def", "p_CreationPart", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "5", ":", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
379a0a384c81875731be51a054bdacced6260fd8
valid
AIC
r"""Akaike Information Criterion :param rho: rho at order k :param N: sample size :param k: AR order. If k is the AR order and N the size of the sample, then Akaike criterion is .. math:: AIC(k) = \log(\rho_k) + 2\frac{k+1}{N} :: AIC(64, [0.5,0.3,0.2], [1,2,3]) :validation: double checked versus octave.
src/spectrum/criteria.py
def AIC(N, rho, k): r"""Akaike Information Criterion :param rho: rho at order k :param N: sample size :param k: AR order. If k is the AR order and N the size of the sample, then Akaike criterion is .. math:: AIC(k) = \log(\rho_k) + 2\frac{k+1}{N} :: AIC(64, [0.5,0.3,0.2], [1,2,3]) :validation: double checked versus octave. """ from numpy import log, array #k+1 #todo check convention. agrees with octave res = N * log(array(rho)) + 2.* (array(k)+1) return res
def AIC(N, rho, k): r"""Akaike Information Criterion :param rho: rho at order k :param N: sample size :param k: AR order. If k is the AR order and N the size of the sample, then Akaike criterion is .. math:: AIC(k) = \log(\rho_k) + 2\frac{k+1}{N} :: AIC(64, [0.5,0.3,0.2], [1,2,3]) :validation: double checked versus octave. """ from numpy import log, array #k+1 #todo check convention. agrees with octave res = N * log(array(rho)) + 2.* (array(k)+1) return res
[ "r", "Akaike", "Information", "Criterion" ]
cokelaer/spectrum
python
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L157-L178
[ "def", "AIC", "(", "N", ",", "rho", ",", "k", ")", ":", "from", "numpy", "import", "log", ",", "array", "#k+1 #todo check convention. agrees with octave", "res", "=", "N", "*", "log", "(", "array", "(", "rho", ")", ")", "+", "2.", "*", "(", "array", "(", "k", ")", "+", "1", ")", "return", "res" ]
bad6c32e3f10e185098748f67bb421b378b06afe
valid
AICc
r"""corrected Akaike information criterion .. math:: AICc(k) = log(\rho_k) + 2 \frac{k+1}{N-k-2} :validation: double checked versus octave.
src/spectrum/criteria.py
def AICc(N, rho, k, norm=True): r"""corrected Akaike information criterion .. math:: AICc(k) = log(\rho_k) + 2 \frac{k+1}{N-k-2} :validation: double checked versus octave. """ from numpy import log, array p = k #todo check convention. agrees with octave res = log(rho) + 2. * (p+1) / (N-p-2) return res
def AICc(N, rho, k, norm=True): r"""corrected Akaike information criterion .. math:: AICc(k) = log(\rho_k) + 2 \frac{k+1}{N-k-2} :validation: double checked versus octave. """ from numpy import log, array p = k #todo check convention. agrees with octave res = log(rho) + 2. * (p+1) / (N-p-2) return res
[ "r", "corrected", "Akaike", "information", "criterion" ]
cokelaer/spectrum
python
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L181-L192
[ "def", "AICc", "(", "N", ",", "rho", ",", "k", ",", "norm", "=", "True", ")", ":", "from", "numpy", "import", "log", ",", "array", "p", "=", "k", "#todo check convention. agrees with octave", "res", "=", "log", "(", "rho", ")", "+", "2.", "*", "(", "p", "+", "1", ")", "/", "(", "N", "-", "p", "-", "2", ")", "return", "res" ]
bad6c32e3f10e185098748f67bb421b378b06afe
valid
KIC
r"""Kullback information criterion .. math:: KIC(k) = log(\rho_k) + 3 \frac{k+1}{N} :validation: double checked versus octave.
src/spectrum/criteria.py
def KIC(N, rho, k): r"""Kullback information criterion .. math:: KIC(k) = log(\rho_k) + 3 \frac{k+1}{N} :validation: double checked versus octave. """ from numpy import log, array res = log(rho) + 3. * (k+1.) /float(N) return res
def KIC(N, rho, k): r"""Kullback information criterion .. math:: KIC(k) = log(\rho_k) + 3 \frac{k+1}{N} :validation: double checked versus octave. """ from numpy import log, array res = log(rho) + 3. * (k+1.) /float(N) return res
[ "r", "Kullback", "information", "criterion" ]
cokelaer/spectrum
python
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L195-L204
[ "def", "KIC", "(", "N", ",", "rho", ",", "k", ")", ":", "from", "numpy", "import", "log", ",", "array", "res", "=", "log", "(", "rho", ")", "+", "3.", "*", "(", "k", "+", "1.", ")", "/", "float", "(", "N", ")", "return", "res" ]
bad6c32e3f10e185098748f67bb421b378b06afe
valid
AKICc
r"""approximate corrected Kullback information .. math:: AKICc(k) = log(rho_k) + \frac{p}{N*(N-k)} + (3-\frac{k+2}{N})*\frac{k+1}{N-k-2}
src/spectrum/criteria.py
def AKICc(N, rho, k): r"""approximate corrected Kullback information .. math:: AKICc(k) = log(rho_k) + \frac{p}{N*(N-k)} + (3-\frac{k+2}{N})*\frac{k+1}{N-k-2} """ from numpy import log, array p = k res = log(rho) + p/N/(N-p) + (3.-(p+2.)/N) * (p+1.) / (N-p-2.) return res
def AKICc(N, rho, k): r"""approximate corrected Kullback information .. math:: AKICc(k) = log(rho_k) + \frac{p}{N*(N-k)} + (3-\frac{k+2}{N})*\frac{k+1}{N-k-2} """ from numpy import log, array p = k res = log(rho) + p/N/(N-p) + (3.-(p+2.)/N) * (p+1.) / (N-p-2.) return res
[ "r", "approximate", "corrected", "Kullback", "information" ]
cokelaer/spectrum
python
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L207-L216
[ "def", "AKICc", "(", "N", ",", "rho", ",", "k", ")", ":", "from", "numpy", "import", "log", ",", "array", "p", "=", "k", "res", "=", "log", "(", "rho", ")", "+", "p", "/", "N", "/", "(", "N", "-", "p", ")", "+", "(", "3.", "-", "(", "p", "+", "2.", ")", "/", "N", ")", "*", "(", "p", "+", "1.", ")", "/", "(", "N", "-", "p", "-", "2.", ")", "return", "res" ]
bad6c32e3f10e185098748f67bb421b378b06afe
valid
FPE
r"""Final prediction error criterion .. math:: FPE(k) = \frac{N + k + 1}{N - k - 1} \rho_k :validation: double checked versus octave.
src/spectrum/criteria.py
def FPE(N,rho, k=None): r"""Final prediction error criterion .. math:: FPE(k) = \frac{N + k + 1}{N - k - 1} \rho_k :validation: double checked versus octave. """ #k #todo check convention. agrees with octave fpe = rho * (N + k + 1.) / (N- k -1) return fpe
def FPE(N,rho, k=None): r"""Final prediction error criterion .. math:: FPE(k) = \frac{N + k + 1}{N - k - 1} \rho_k :validation: double checked versus octave. """ #k #todo check convention. agrees with octave fpe = rho * (N + k + 1.) / (N- k -1) return fpe
[ "r", "Final", "prediction", "error", "criterion" ]
cokelaer/spectrum
python
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L219-L229
[ "def", "FPE", "(", "N", ",", "rho", ",", "k", "=", "None", ")", ":", "#k #todo check convention. agrees with octave", "fpe", "=", "rho", "*", "(", "N", "+", "k", "+", "1.", ")", "/", "(", "N", "-", "k", "-", "1", ")", "return", "fpe" ]
bad6c32e3f10e185098748f67bb421b378b06afe
valid
MDL
r"""Minimum Description Length .. math:: MDL(k) = N log \rho_k + p \log N :validation: results
src/spectrum/criteria.py
def MDL(N, rho, k): r"""Minimum Description Length .. math:: MDL(k) = N log \rho_k + p \log N :validation: results """ from numpy import log #p = arange(1, len(rho)+1) mdl = N* log(rho) + k * log(N) return mdl
def MDL(N, rho, k): r"""Minimum Description Length .. math:: MDL(k) = N log \rho_k + p \log N :validation: results """ from numpy import log #p = arange(1, len(rho)+1) mdl = N* log(rho) + k * log(N) return mdl
[ "r", "Minimum", "Description", "Length" ]
cokelaer/spectrum
python
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L232-L242
[ "def", "MDL", "(", "N", ",", "rho", ",", "k", ")", ":", "from", "numpy", "import", "log", "#p = arange(1, len(rho)+1)", "mdl", "=", "N", "*", "log", "(", "rho", ")", "+", "k", "*", "log", "(", "N", ")", "return", "mdl" ]
bad6c32e3f10e185098748f67bb421b378b06afe
valid
CAT
r"""Criterion Autoregressive Transfer Function : .. math:: CAT(k) = \frac{1}{N} \sum_{i=1}^k \frac{1}{\rho_i} - \frac{\rho_i}{\rho_k} .. todo:: validation
src/spectrum/criteria.py
def CAT(N, rho, k): r"""Criterion Autoregressive Transfer Function : .. math:: CAT(k) = \frac{1}{N} \sum_{i=1}^k \frac{1}{\rho_i} - \frac{\rho_i}{\rho_k} .. todo:: validation """ from numpy import zeros, arange cat = zeros(len(rho)) for p in arange(1, len(rho)+1): rho_p = float(N)/(N-p)*rho[p-1] s = 0 for j in range(1, p+1): rho_j = float(N)/(N-j)*rho[j-1] s = s + 1./rho_j #print(s, s/float(N), 1./rho_p) cat[p-1] = s/float(N) - 1./rho_p return cat
def CAT(N, rho, k): r"""Criterion Autoregressive Transfer Function : .. math:: CAT(k) = \frac{1}{N} \sum_{i=1}^k \frac{1}{\rho_i} - \frac{\rho_i}{\rho_k} .. todo:: validation """ from numpy import zeros, arange cat = zeros(len(rho)) for p in arange(1, len(rho)+1): rho_p = float(N)/(N-p)*rho[p-1] s = 0 for j in range(1, p+1): rho_j = float(N)/(N-j)*rho[j-1] s = s + 1./rho_j #print(s, s/float(N), 1./rho_p) cat[p-1] = s/float(N) - 1./rho_p return cat
[ "r", "Criterion", "Autoregressive", "Transfer", "Function", ":" ]
cokelaer/spectrum
python
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/criteria.py#L245-L262
[ "def", "CAT", "(", "N", ",", "rho", ",", "k", ")", ":", "from", "numpy", "import", "zeros", ",", "arange", "cat", "=", "zeros", "(", "len", "(", "rho", ")", ")", "for", "p", "in", "arange", "(", "1", ",", "len", "(", "rho", ")", "+", "1", ")", ":", "rho_p", "=", "float", "(", "N", ")", "/", "(", "N", "-", "p", ")", "*", "rho", "[", "p", "-", "1", "]", "s", "=", "0", "for", "j", "in", "range", "(", "1", ",", "p", "+", "1", ")", ":", "rho_j", "=", "float", "(", "N", ")", "/", "(", "N", "-", "j", ")", "*", "rho", "[", "j", "-", "1", "]", "s", "=", "s", "+", "1.", "/", "rho_j", "#print(s, s/float(N), 1./rho_p)", "cat", "[", "p", "-", "1", "]", "=", "s", "/", "float", "(", "N", ")", "-", "1.", "/", "rho_p", "return", "cat" ]
bad6c32e3f10e185098748f67bb421b378b06afe