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
test
NNTPClient.list
LIST command. A wrapper for all of the other list commands. The output of this command depends on the keyword specified. The output format for each keyword can be found in the list function that corresponds to the keyword. Args: keyword: Information requested. arg: Pattern or keyword specific argument. Note: Keywords supported by this function are include ACTIVE, ACTIVE.TIMES, DISTRIB.PATS, HEADERS, NEWSGROUPS, OVERVIEW.FMT and EXTENSIONS. Raises: NotImplementedError: For unsupported keywords.
nntp/nntp.py
def list(self, keyword=None, arg=None): """LIST command. A wrapper for all of the other list commands. The output of this command depends on the keyword specified. The output format for each keyword can be found in the list function that corresponds to the keyword. Args: keyword: Information requested. arg: Pattern or keyword specific argument. Note: Keywords supported by this function are include ACTIVE, ACTIVE.TIMES, DISTRIB.PATS, HEADERS, NEWSGROUPS, OVERVIEW.FMT and EXTENSIONS. Raises: NotImplementedError: For unsupported keywords. """ return [x for x in self.list_gen(keyword, arg)]
def list(self, keyword=None, arg=None): """LIST command. A wrapper for all of the other list commands. The output of this command depends on the keyword specified. The output format for each keyword can be found in the list function that corresponds to the keyword. Args: keyword: Information requested. arg: Pattern or keyword specific argument. Note: Keywords supported by this function are include ACTIVE, ACTIVE.TIMES, DISTRIB.PATS, HEADERS, NEWSGROUPS, OVERVIEW.FMT and EXTENSIONS. Raises: NotImplementedError: For unsupported keywords. """ return [x for x in self.list_gen(keyword, arg)]
[ "LIST", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L931-L949
[ "def", "list", "(", "self", ",", "keyword", "=", "None", ",", "arg", "=", "None", ")", ":", "return", "[", "x", "for", "x", "in", "self", ".", "list_gen", "(", "keyword", ",", "arg", ")", "]" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.group
GROUP command.
nntp/nntp.py
def group(self, name): """GROUP command. """ args = name code, message = self.command("GROUP", args) if code != 211: raise NNTPReplyError(code, message) parts = message.split(None, 4) try: total = int(parts[0]) first = int(parts[1]) last = int(parts[2]) group = parts[3] except (IndexError, ValueError): raise NNTPDataError("Invalid GROUP status '%s'" % message) return total, first, last, group
def group(self, name): """GROUP command. """ args = name code, message = self.command("GROUP", args) if code != 211: raise NNTPReplyError(code, message) parts = message.split(None, 4) try: total = int(parts[0]) first = int(parts[1]) last = int(parts[2]) group = parts[3] except (IndexError, ValueError): raise NNTPDataError("Invalid GROUP status '%s'" % message) return total, first, last, group
[ "GROUP", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L951-L969
[ "def", "group", "(", "self", ",", "name", ")", ":", "args", "=", "name", "code", ",", "message", "=", "self", ".", "command", "(", "\"GROUP\"", ",", "args", ")", "if", "code", "!=", "211", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "parts", "=", "message", ".", "split", "(", "None", ",", "4", ")", "try", ":", "total", "=", "int", "(", "parts", "[", "0", "]", ")", "first", "=", "int", "(", "parts", "[", "1", "]", ")", "last", "=", "int", "(", "parts", "[", "2", "]", ")", "group", "=", "parts", "[", "3", "]", "except", "(", "IndexError", ",", "ValueError", ")", ":", "raise", "NNTPDataError", "(", "\"Invalid GROUP status '%s'\"", "%", "message", ")", "return", "total", ",", "first", ",", "last", ",", "group" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.next
NEXT command.
nntp/nntp.py
def next(self): """NEXT command. """ code, message = self.command("NEXT") if code != 223: raise NNTPReplyError(code, message) parts = message.split(None, 3) try: article = int(parts[0]) ident = parts[1] except (IndexError, ValueError): raise NNTPDataError("Invalid NEXT status") return article, ident
def next(self): """NEXT command. """ code, message = self.command("NEXT") if code != 223: raise NNTPReplyError(code, message) parts = message.split(None, 3) try: article = int(parts[0]) ident = parts[1] except (IndexError, ValueError): raise NNTPDataError("Invalid NEXT status") return article, ident
[ "NEXT", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L971-L985
[ "def", "next", "(", "self", ")", ":", "code", ",", "message", "=", "self", ".", "command", "(", "\"NEXT\"", ")", "if", "code", "!=", "223", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "parts", "=", "message", ".", "split", "(", "None", ",", "3", ")", "try", ":", "article", "=", "int", "(", "parts", "[", "0", "]", ")", "ident", "=", "parts", "[", "1", "]", "except", "(", "IndexError", ",", "ValueError", ")", ":", "raise", "NNTPDataError", "(", "\"Invalid NEXT status\"", ")", "return", "article", ",", "ident" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.article
ARTICLE command.
nntp/nntp.py
def article(self, msgid_article=None, decode=None): """ARTICLE command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("ARTICLE", args) if code != 220: raise NNTPReplyError(code, message) parts = message.split(None, 1) try: articleno = int(parts[0]) except ValueError: raise NNTPProtocolError(message) # headers headers = utils.parse_headers(self.info_gen(code, message)) # decoding setup decode = "yEnc" in headers.get("subject", "") escape = 0 crc32 = 0 # body body = [] for line in self.info_gen(code, message): # decode body if required if decode: if line.startswith("=y"): continue line, escape, crc32 = yenc.decode(line, escape, crc32) body.append(line) return articleno, headers, "".join(body)
def article(self, msgid_article=None, decode=None): """ARTICLE command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("ARTICLE", args) if code != 220: raise NNTPReplyError(code, message) parts = message.split(None, 1) try: articleno = int(parts[0]) except ValueError: raise NNTPProtocolError(message) # headers headers = utils.parse_headers(self.info_gen(code, message)) # decoding setup decode = "yEnc" in headers.get("subject", "") escape = 0 crc32 = 0 # body body = [] for line in self.info_gen(code, message): # decode body if required if decode: if line.startswith("=y"): continue line, escape, crc32 = yenc.decode(line, escape, crc32) body.append(line) return articleno, headers, "".join(body)
[ "ARTICLE", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1004-L1042
[ "def", "article", "(", "self", ",", "msgid_article", "=", "None", ",", "decode", "=", "None", ")", ":", "args", "=", "None", "if", "msgid_article", "is", "not", "None", ":", "args", "=", "utils", ".", "unparse_msgid_article", "(", "msgid_article", ")", "code", ",", "message", "=", "self", ".", "command", "(", "\"ARTICLE\"", ",", "args", ")", "if", "code", "!=", "220", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "parts", "=", "message", ".", "split", "(", "None", ",", "1", ")", "try", ":", "articleno", "=", "int", "(", "parts", "[", "0", "]", ")", "except", "ValueError", ":", "raise", "NNTPProtocolError", "(", "message", ")", "# headers", "headers", "=", "utils", ".", "parse_headers", "(", "self", ".", "info_gen", "(", "code", ",", "message", ")", ")", "# decoding setup", "decode", "=", "\"yEnc\"", "in", "headers", ".", "get", "(", "\"subject\"", ",", "\"\"", ")", "escape", "=", "0", "crc32", "=", "0", "# body", "body", "=", "[", "]", "for", "line", "in", "self", ".", "info_gen", "(", "code", ",", "message", ")", ":", "# decode body if required", "if", "decode", ":", "if", "line", ".", "startswith", "(", "\"=y\"", ")", ":", "continue", "line", ",", "escape", ",", "crc32", "=", "yenc", ".", "decode", "(", "line", ",", "escape", ",", "crc32", ")", "body", ".", "append", "(", "line", ")", "return", "articleno", ",", "headers", ",", "\"\"", ".", "join", "(", "body", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.head
HEAD command.
nntp/nntp.py
def head(self, msgid_article=None): """HEAD command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("HEAD", args) if code != 221: raise NNTPReplyError(code, message) return utils.parse_headers(self.info_gen(code, message))
def head(self, msgid_article=None): """HEAD command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("HEAD", args) if code != 221: raise NNTPReplyError(code, message) return utils.parse_headers(self.info_gen(code, message))
[ "HEAD", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1044-L1055
[ "def", "head", "(", "self", ",", "msgid_article", "=", "None", ")", ":", "args", "=", "None", "if", "msgid_article", "is", "not", "None", ":", "args", "=", "utils", ".", "unparse_msgid_article", "(", "msgid_article", ")", "code", ",", "message", "=", "self", ".", "command", "(", "\"HEAD\"", ",", "args", ")", "if", "code", "!=", "221", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "return", "utils", ".", "parse_headers", "(", "self", ".", "info_gen", "(", "code", ",", "message", ")", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.body
BODY command.
nntp/nntp.py
def body(self, msgid_article=None, decode=False): """BODY command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("BODY", args) if code != 222: raise NNTPReplyError(code, message) escape = 0 crc32 = 0 body = [] for line in self.info_gen(code, message): # decode body if required if decode: if line.startswith("=y"): continue line, escape, crc32 = yenc.decode(line, escape, crc32) # body body.append(line) return "".join(body)
def body(self, msgid_article=None, decode=False): """BODY command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("BODY", args) if code != 222: raise NNTPReplyError(code, message) escape = 0 crc32 = 0 body = [] for line in self.info_gen(code, message): # decode body if required if decode: if line.startswith("=y"): continue line, escape, crc32 = yenc.decode(line, escape, crc32) # body body.append(line) return "".join(body)
[ "BODY", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1058-L1084
[ "def", "body", "(", "self", ",", "msgid_article", "=", "None", ",", "decode", "=", "False", ")", ":", "args", "=", "None", "if", "msgid_article", "is", "not", "None", ":", "args", "=", "utils", ".", "unparse_msgid_article", "(", "msgid_article", ")", "code", ",", "message", "=", "self", ".", "command", "(", "\"BODY\"", ",", "args", ")", "if", "code", "!=", "222", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "escape", "=", "0", "crc32", "=", "0", "body", "=", "[", "]", "for", "line", "in", "self", ".", "info_gen", "(", "code", ",", "message", ")", ":", "# decode body if required", "if", "decode", ":", "if", "line", ".", "startswith", "(", "\"=y\"", ")", ":", "continue", "line", ",", "escape", ",", "crc32", "=", "yenc", ".", "decode", "(", "line", ",", "escape", ",", "crc32", ")", "# body", "body", ".", "append", "(", "line", ")", "return", "\"\"", ".", "join", "(", "body", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.xgtitle
XGTITLE command.
nntp/nntp.py
def xgtitle(self, pattern=None): """XGTITLE command. """ args = pattern code, message = self.command("XGTITLE", args) if code != 282: raise NNTPReplyError(code, message) return self.info(code, message)
def xgtitle(self, pattern=None): """XGTITLE command. """ args = pattern code, message = self.command("XGTITLE", args) if code != 282: raise NNTPReplyError(code, message) return self.info(code, message)
[ "XGTITLE", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1086-L1095
[ "def", "xgtitle", "(", "self", ",", "pattern", "=", "None", ")", ":", "args", "=", "pattern", "code", ",", "message", "=", "self", ".", "command", "(", "\"XGTITLE\"", ",", "args", ")", "if", "code", "!=", "282", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "return", "self", ".", "info", "(", "code", ",", "message", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.xhdr
XHDR command.
nntp/nntp.py
def xhdr(self, header, msgid_range=None): """XHDR command. """ args = header if range is not None: args += " " + utils.unparse_msgid_range(msgid_range) code, message = self.command("XHDR", args) if code != 221: raise NNTPReplyError(code, message) return self.info(code, message)
def xhdr(self, header, msgid_range=None): """XHDR command. """ args = header if range is not None: args += " " + utils.unparse_msgid_range(msgid_range) code, message = self.command("XHDR", args) if code != 221: raise NNTPReplyError(code, message) return self.info(code, message)
[ "XHDR", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1097-L1108
[ "def", "xhdr", "(", "self", ",", "header", ",", "msgid_range", "=", "None", ")", ":", "args", "=", "header", "if", "range", "is", "not", "None", ":", "args", "+=", "\" \"", "+", "utils", ".", "unparse_msgid_range", "(", "msgid_range", ")", "code", ",", "message", "=", "self", ".", "command", "(", "\"XHDR\"", ",", "args", ")", "if", "code", "!=", "221", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "return", "self", ".", "info", "(", "code", ",", "message", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.xzhdr
XZHDR command. Args: msgid_range: A message-id as a string, or an article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]) - if last is omitted then all articles after first are included. A msgid_range of None (the default) uses the current article.
nntp/nntp.py
def xzhdr(self, header, msgid_range=None): """XZHDR command. Args: msgid_range: A message-id as a string, or an article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]) - if last is omitted then all articles after first are included. A msgid_range of None (the default) uses the current article. """ args = header if msgid_range is not None: args += " " + utils.unparse_msgid_range(msgid_range) code, message = self.command("XZHDR", args) if code != 221: raise NNTPReplyError(code, message) return self.info(code, message, compressed=True)
def xzhdr(self, header, msgid_range=None): """XZHDR command. Args: msgid_range: A message-id as a string, or an article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]) - if last is omitted then all articles after first are included. A msgid_range of None (the default) uses the current article. """ args = header if msgid_range is not None: args += " " + utils.unparse_msgid_range(msgid_range) code, message = self.command("XZHDR", args) if code != 221: raise NNTPReplyError(code, message) return self.info(code, message, compressed=True)
[ "XZHDR", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1110-L1128
[ "def", "xzhdr", "(", "self", ",", "header", ",", "msgid_range", "=", "None", ")", ":", "args", "=", "header", "if", "msgid_range", "is", "not", "None", ":", "args", "+=", "\" \"", "+", "utils", ".", "unparse_msgid_range", "(", "msgid_range", ")", "code", ",", "message", "=", "self", ".", "command", "(", "\"XZHDR\"", ",", "args", ")", "if", "code", "!=", "221", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "return", "self", ".", "info", "(", "code", ",", "message", ",", "compressed", "=", "True", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.xover_gen
Generator for the XOVER command. The XOVER command returns information from the overview database for the article(s) specified. <http://tools.ietf.org/html/rfc2980#section-2.8> Args: range: An article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]). If last is omitted then all articles after first are included. A range of None (the default) uses the current article. Returns: A list of fields as given by the overview database for each available article in the specified range. The fields that are returned can be determined using the LIST OVERVIEW.FMT command if the server supports it. Raises: NNTPReplyError: If no such article exists or the currently selected newsgroup is invalid.
nntp/nntp.py
def xover_gen(self, range=None): """Generator for the XOVER command. The XOVER command returns information from the overview database for the article(s) specified. <http://tools.ietf.org/html/rfc2980#section-2.8> Args: range: An article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]). If last is omitted then all articles after first are included. A range of None (the default) uses the current article. Returns: A list of fields as given by the overview database for each available article in the specified range. The fields that are returned can be determined using the LIST OVERVIEW.FMT command if the server supports it. Raises: NNTPReplyError: If no such article exists or the currently selected newsgroup is invalid. """ args = None if range is not None: args = utils.unparse_range(range) code, message = self.command("XOVER", args) if code != 224: raise NNTPReplyError(code, message) for line in self.info_gen(code, message): yield line.rstrip().split("\t")
def xover_gen(self, range=None): """Generator for the XOVER command. The XOVER command returns information from the overview database for the article(s) specified. <http://tools.ietf.org/html/rfc2980#section-2.8> Args: range: An article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]). If last is omitted then all articles after first are included. A range of None (the default) uses the current article. Returns: A list of fields as given by the overview database for each available article in the specified range. The fields that are returned can be determined using the LIST OVERVIEW.FMT command if the server supports it. Raises: NNTPReplyError: If no such article exists or the currently selected newsgroup is invalid. """ args = None if range is not None: args = utils.unparse_range(range) code, message = self.command("XOVER", args) if code != 224: raise NNTPReplyError(code, message) for line in self.info_gen(code, message): yield line.rstrip().split("\t")
[ "Generator", "for", "the", "XOVER", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1130-L1163
[ "def", "xover_gen", "(", "self", ",", "range", "=", "None", ")", ":", "args", "=", "None", "if", "range", "is", "not", "None", ":", "args", "=", "utils", ".", "unparse_range", "(", "range", ")", "code", ",", "message", "=", "self", ".", "command", "(", "\"XOVER\"", ",", "args", ")", "if", "code", "!=", "224", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "for", "line", "in", "self", ".", "info_gen", "(", "code", ",", "message", ")", ":", "yield", "line", ".", "rstrip", "(", ")", ".", "split", "(", "\"\\t\"", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.xpat_gen
Generator for the XPAT command.
nntp/nntp.py
def xpat_gen(self, header, msgid_range, *pattern): """Generator for the XPAT command. """ args = " ".join( [header, utils.unparse_msgid_range(msgid_range)] + list(pattern) ) code, message = self.command("XPAT", args) if code != 221: raise NNTPReplyError(code, message) for line in self.info_gen(code, message): yield line.strip()
def xpat_gen(self, header, msgid_range, *pattern): """Generator for the XPAT command. """ args = " ".join( [header, utils.unparse_msgid_range(msgid_range)] + list(pattern) ) code, message = self.command("XPAT", args) if code != 221: raise NNTPReplyError(code, message) for line in self.info_gen(code, message): yield line.strip()
[ "Generator", "for", "the", "XPAT", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1258-L1270
[ "def", "xpat_gen", "(", "self", ",", "header", ",", "msgid_range", ",", "*", "pattern", ")", ":", "args", "=", "\" \"", ".", "join", "(", "[", "header", ",", "utils", ".", "unparse_msgid_range", "(", "msgid_range", ")", "]", "+", "list", "(", "pattern", ")", ")", "code", ",", "message", "=", "self", ".", "command", "(", "\"XPAT\"", ",", "args", ")", "if", "code", "!=", "221", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "for", "line", "in", "self", ".", "info_gen", "(", "code", ",", "message", ")", ":", "yield", "line", ".", "strip", "(", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.xpat
XPAT command.
nntp/nntp.py
def xpat(self, header, id_range, *pattern): """XPAT command. """ return [x for x in self.xpat_gen(header, id_range, *pattern)]
def xpat(self, header, id_range, *pattern): """XPAT command. """ return [x for x in self.xpat_gen(header, id_range, *pattern)]
[ "XPAT", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1272-L1275
[ "def", "xpat", "(", "self", ",", "header", ",", "id_range", ",", "*", "pattern", ")", ":", "return", "[", "x", "for", "x", "in", "self", ".", "xpat_gen", "(", "header", ",", "id_range", ",", "*", "pattern", ")", "]" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.xfeature_compress_gzip
XFEATURE COMPRESS GZIP command.
nntp/nntp.py
def xfeature_compress_gzip(self, terminator=False): """XFEATURE COMPRESS GZIP command. """ args = "TERMINATOR" if terminator else None code, message = self.command("XFEATURE COMPRESS GZIP", args) if code != 290: raise NNTPReplyError(code, message) return True
def xfeature_compress_gzip(self, terminator=False): """XFEATURE COMPRESS GZIP command. """ args = "TERMINATOR" if terminator else None code, message = self.command("XFEATURE COMPRESS GZIP", args) if code != 290: raise NNTPReplyError(code, message) return True
[ "XFEATURE", "COMPRESS", "GZIP", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1277-L1286
[ "def", "xfeature_compress_gzip", "(", "self", ",", "terminator", "=", "False", ")", ":", "args", "=", "\"TERMINATOR\"", "if", "terminator", "else", "None", "code", ",", "message", "=", "self", ".", "command", "(", "\"XFEATURE COMPRESS GZIP\"", ",", "args", ")", "if", "code", "!=", "290", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "return", "True" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
NNTPClient.post
POST command. Args: headers: A dictionary of headers. body: A string or file like object containing the post content. Raises: NNTPDataError: If binary characters are detected in the message body. Returns: A value that evaluates to true if posting the message succeeded. (See note for further details) Note: '\\n' line terminators are converted to '\\r\\n' Note: Though not part of any specification it is common for usenet servers to return the message-id for a successfully posted message. If a message-id is identified in the response from the server then that message-id will be returned by the function, otherwise True will be returned. Note: Due to protocol issues if illegal characters are found in the body the message will still be posted but will be truncated as soon as an illegal character is detected. No illegal characters will be sent to the server. For information illegal characters include embedded carriage returns '\\r' and null characters '\\0' (because this function converts line feeds to CRLF, embedded line feeds are not an issue)
nntp/nntp.py
def post(self, headers={}, body=""): """POST command. Args: headers: A dictionary of headers. body: A string or file like object containing the post content. Raises: NNTPDataError: If binary characters are detected in the message body. Returns: A value that evaluates to true if posting the message succeeded. (See note for further details) Note: '\\n' line terminators are converted to '\\r\\n' Note: Though not part of any specification it is common for usenet servers to return the message-id for a successfully posted message. If a message-id is identified in the response from the server then that message-id will be returned by the function, otherwise True will be returned. Note: Due to protocol issues if illegal characters are found in the body the message will still be posted but will be truncated as soon as an illegal character is detected. No illegal characters will be sent to the server. For information illegal characters include embedded carriage returns '\\r' and null characters '\\0' (because this function converts line feeds to CRLF, embedded line feeds are not an issue) """ code, message = self.command("POST") if code != 340: raise NNTPReplyError(code, message) # send headers hdrs = utils.unparse_headers(headers) self.socket.sendall(hdrs) if isinstance(body, basestring): body = cStringIO.StringIO(body) # send body illegal = False for line in body: if line.startswith("."): line = "." + line if line.endswith("\r\n"): line = line[:-2] elif line.endswith("\n"): line = line[:-1] if any(c in line for c in "\0\r"): illegal = True break self.socket.sendall(line + "\r\n") self.socket.sendall(".\r\n") # get status code, message = self.status() # check if illegal characters were detected if illegal: raise NNTPDataError("Illegal characters found") # check status if code != 240: raise NNTPReplyError(code, message) # return message-id possible message_id = message.split(None, 1)[0] if message_id.startswith("<") and message_id.endswith(">"): return message_id return True
def post(self, headers={}, body=""): """POST command. Args: headers: A dictionary of headers. body: A string or file like object containing the post content. Raises: NNTPDataError: If binary characters are detected in the message body. Returns: A value that evaluates to true if posting the message succeeded. (See note for further details) Note: '\\n' line terminators are converted to '\\r\\n' Note: Though not part of any specification it is common for usenet servers to return the message-id for a successfully posted message. If a message-id is identified in the response from the server then that message-id will be returned by the function, otherwise True will be returned. Note: Due to protocol issues if illegal characters are found in the body the message will still be posted but will be truncated as soon as an illegal character is detected. No illegal characters will be sent to the server. For information illegal characters include embedded carriage returns '\\r' and null characters '\\0' (because this function converts line feeds to CRLF, embedded line feeds are not an issue) """ code, message = self.command("POST") if code != 340: raise NNTPReplyError(code, message) # send headers hdrs = utils.unparse_headers(headers) self.socket.sendall(hdrs) if isinstance(body, basestring): body = cStringIO.StringIO(body) # send body illegal = False for line in body: if line.startswith("."): line = "." + line if line.endswith("\r\n"): line = line[:-2] elif line.endswith("\n"): line = line[:-1] if any(c in line for c in "\0\r"): illegal = True break self.socket.sendall(line + "\r\n") self.socket.sendall(".\r\n") # get status code, message = self.status() # check if illegal characters were detected if illegal: raise NNTPDataError("Illegal characters found") # check status if code != 240: raise NNTPReplyError(code, message) # return message-id possible message_id = message.split(None, 1)[0] if message_id.startswith("<") and message_id.endswith(">"): return message_id return True
[ "POST", "command", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L1288-L1364
[ "def", "post", "(", "self", ",", "headers", "=", "{", "}", ",", "body", "=", "\"\"", ")", ":", "code", ",", "message", "=", "self", ".", "command", "(", "\"POST\"", ")", "if", "code", "!=", "340", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "# send headers", "hdrs", "=", "utils", ".", "unparse_headers", "(", "headers", ")", "self", ".", "socket", ".", "sendall", "(", "hdrs", ")", "if", "isinstance", "(", "body", ",", "basestring", ")", ":", "body", "=", "cStringIO", ".", "StringIO", "(", "body", ")", "# send body", "illegal", "=", "False", "for", "line", "in", "body", ":", "if", "line", ".", "startswith", "(", "\".\"", ")", ":", "line", "=", "\".\"", "+", "line", "if", "line", ".", "endswith", "(", "\"\\r\\n\"", ")", ":", "line", "=", "line", "[", ":", "-", "2", "]", "elif", "line", ".", "endswith", "(", "\"\\n\"", ")", ":", "line", "=", "line", "[", ":", "-", "1", "]", "if", "any", "(", "c", "in", "line", "for", "c", "in", "\"\\0\\r\"", ")", ":", "illegal", "=", "True", "break", "self", ".", "socket", ".", "sendall", "(", "line", "+", "\"\\r\\n\"", ")", "self", ".", "socket", ".", "sendall", "(", "\".\\r\\n\"", ")", "# get status", "code", ",", "message", "=", "self", ".", "status", "(", ")", "# check if illegal characters were detected", "if", "illegal", ":", "raise", "NNTPDataError", "(", "\"Illegal characters found\"", ")", "# check status", "if", "code", "!=", "240", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "# return message-id possible", "message_id", "=", "message", ".", "split", "(", "None", ",", "1", ")", "[", "0", "]", "if", "message_id", ".", "startswith", "(", "\"<\"", ")", "and", "message_id", ".", "endswith", "(", "\">\"", ")", ":", "return", "message_id", "return", "True" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
_lower
assumes that classes that inherit list, tuple or dict have a constructor that is compatible with those base classes. If you are using classes that don't satisfy this requirement you can subclass them and add a lower() method for the class
nntp/iodict.py
def _lower(v): """assumes that classes that inherit list, tuple or dict have a constructor that is compatible with those base classes. If you are using classes that don't satisfy this requirement you can subclass them and add a lower() method for the class""" if hasattr(v, "lower"): return v.lower() if isinstance(v, (list, tuple)): return v.__class__(_lower(x) for x in v) if isinstance(v, dict): return v.__class__(_lower(v.items())) return v
def _lower(v): """assumes that classes that inherit list, tuple or dict have a constructor that is compatible with those base classes. If you are using classes that don't satisfy this requirement you can subclass them and add a lower() method for the class""" if hasattr(v, "lower"): return v.lower() if isinstance(v, (list, tuple)): return v.__class__(_lower(x) for x in v) if isinstance(v, dict): return v.__class__(_lower(v.items())) return v
[ "assumes", "that", "classes", "that", "inherit", "list", "tuple", "or", "dict", "have", "a", "constructor", "that", "is", "compatible", "with", "those", "base", "classes", ".", "If", "you", "are", "using", "classes", "that", "don", "t", "satisfy", "this", "requirement", "you", "can", "subclass", "them", "and", "add", "a", "lower", "()", "method", "for", "the", "class" ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/iodict.py#L24-L35
[ "def", "_lower", "(", "v", ")", ":", "if", "hasattr", "(", "v", ",", "\"lower\"", ")", ":", "return", "v", ".", "lower", "(", ")", "if", "isinstance", "(", "v", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "v", ".", "__class__", "(", "_lower", "(", "x", ")", "for", "x", "in", "v", ")", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "return", "v", ".", "__class__", "(", "_lower", "(", "v", ".", "items", "(", ")", ")", ")", "return", "v" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
I
The standard quadratic limb darkening law. :param ndarray r: The radius vector :param limbdark: A :py:class:`pysyzygy.transit.LIMBDARK` instance containing the limb darkening law information :returns: The stellar intensity as a function of `r`
pysyzygy/plot.py
def I(r, limbdark): ''' The standard quadratic limb darkening law. :param ndarray r: The radius vector :param limbdark: A :py:class:`pysyzygy.transit.LIMBDARK` instance containing the limb darkening law information :returns: The stellar intensity as a function of `r` ''' if limbdark.ldmodel == QUADRATIC: u1 = limbdark.u1 u2 = limbdark.u2 return (1-u1*(1-np.sqrt(1-r**2))-u2*(1-np.sqrt(1-r**2))**2)/(1-u1/3-u2/6)/np.pi elif limbdark.ldmodel == KIPPING: a = np.sqrt(limbdark.q1) b = 2*limbdark.q2 u1 = a*b u2 = a*(1 - b) return (1-u1*(1-np.sqrt(1-r**2))-u2*(1-np.sqrt(1-r**2))**2)/(1-u1/3-u2/6)/np.pi elif limbdark.ldmodel == NONLINEAR: raise Exception('Nonlinear model not yet implemented!') # TODO! else: raise Exception('Invalid limb darkening model.')
def I(r, limbdark): ''' The standard quadratic limb darkening law. :param ndarray r: The radius vector :param limbdark: A :py:class:`pysyzygy.transit.LIMBDARK` instance containing the limb darkening law information :returns: The stellar intensity as a function of `r` ''' if limbdark.ldmodel == QUADRATIC: u1 = limbdark.u1 u2 = limbdark.u2 return (1-u1*(1-np.sqrt(1-r**2))-u2*(1-np.sqrt(1-r**2))**2)/(1-u1/3-u2/6)/np.pi elif limbdark.ldmodel == KIPPING: a = np.sqrt(limbdark.q1) b = 2*limbdark.q2 u1 = a*b u2 = a*(1 - b) return (1-u1*(1-np.sqrt(1-r**2))-u2*(1-np.sqrt(1-r**2))**2)/(1-u1/3-u2/6)/np.pi elif limbdark.ldmodel == NONLINEAR: raise Exception('Nonlinear model not yet implemented!') # TODO! else: raise Exception('Invalid limb darkening model.')
[ "The", "standard", "quadratic", "limb", "darkening", "law", ".", ":", "param", "ndarray", "r", ":", "The", "radius", "vector", ":", "param", "limbdark", ":", "A", ":", "py", ":", "class", ":", "pysyzygy", ".", "transit", ".", "LIMBDARK", "instance", "containing", "the", "limb", "darkening", "law", "information", ":", "returns", ":", "The", "stellar", "intensity", "as", "a", "function", "of", "r" ]
rodluger/pysyzygy
python
https://github.com/rodluger/pysyzygy/blob/d2b64251047cc0f0d0adeb6feab4054e7fce4b7a/pysyzygy/plot.py#L30-L55
[ "def", "I", "(", "r", ",", "limbdark", ")", ":", "if", "limbdark", ".", "ldmodel", "==", "QUADRATIC", ":", "u1", "=", "limbdark", ".", "u1", "u2", "=", "limbdark", ".", "u2", "return", "(", "1", "-", "u1", "*", "(", "1", "-", "np", ".", "sqrt", "(", "1", "-", "r", "**", "2", ")", ")", "-", "u2", "*", "(", "1", "-", "np", ".", "sqrt", "(", "1", "-", "r", "**", "2", ")", ")", "**", "2", ")", "/", "(", "1", "-", "u1", "/", "3", "-", "u2", "/", "6", ")", "/", "np", ".", "pi", "elif", "limbdark", ".", "ldmodel", "==", "KIPPING", ":", "a", "=", "np", ".", "sqrt", "(", "limbdark", ".", "q1", ")", "b", "=", "2", "*", "limbdark", ".", "q2", "u1", "=", "a", "*", "b", "u2", "=", "a", "*", "(", "1", "-", "b", ")", "return", "(", "1", "-", "u1", "*", "(", "1", "-", "np", ".", "sqrt", "(", "1", "-", "r", "**", "2", ")", ")", "-", "u2", "*", "(", "1", "-", "np", ".", "sqrt", "(", "1", "-", "r", "**", "2", ")", ")", "**", "2", ")", "/", "(", "1", "-", "u1", "/", "3", "-", "u2", "/", "6", ")", "/", "np", ".", "pi", "elif", "limbdark", ".", "ldmodel", "==", "NONLINEAR", ":", "raise", "Exception", "(", "'Nonlinear model not yet implemented!'", ")", "# TODO!", "else", ":", "raise", "Exception", "(", "'Invalid limb darkening model.'", ")" ]
d2b64251047cc0f0d0adeb6feab4054e7fce4b7a
test
PlotTransit
Plots a light curve described by `kwargs` :param bool compact: Display the compact version of the plot? Default `False` :param bool ldplot: Displat the limb darkening inset? Default `True` :param str plottitle: The title of the plot. Default `""` :param float xlim: The half-width of the orbit plot in stellar radii. Default is to \ auto adjust this :param bool binned: Bin the light curve model to the exposure time? Default `True` :param kwargs: Any keyword arguments to be passed to :py:func:`pysyzygy.transit.Transit` :returns fig: The :py:mod:`matplotlib` figure object
pysyzygy/plot.py
def PlotTransit(compact = False, ldplot = True, plottitle = "", xlim = None, binned = True, **kwargs): ''' Plots a light curve described by `kwargs` :param bool compact: Display the compact version of the plot? Default `False` :param bool ldplot: Displat the limb darkening inset? Default `True` :param str plottitle: The title of the plot. Default `""` :param float xlim: The half-width of the orbit plot in stellar radii. Default is to \ auto adjust this :param bool binned: Bin the light curve model to the exposure time? Default `True` :param kwargs: Any keyword arguments to be passed to :py:func:`pysyzygy.transit.Transit` :returns fig: The :py:mod:`matplotlib` figure object ''' # Plotting fig = pl.figure(figsize = (12,8)) fig.subplots_adjust(hspace=0.3) ax1, ax2 = pl.subplot(211), pl.subplot(212) if not compact: fig.subplots_adjust(right = 0.7) t0 = kwargs.pop('t0', 0.) trn = Transit(**kwargs) try: trn.Compute() notransit = False except Exception as e: if str(e) == "Object does not transit the star.": notransit = True else: raise Exception(e) time = trn.arrays.time + t0 if not notransit: if binned: trn.Bin() flux = trn.arrays.bflx else: flux = trn.arrays.flux time = np.concatenate(([-1.e5], time, [1.e5])) # Add baseline on each side flux = np.concatenate(([1.], flux, [1.])) ax1.plot(time, flux, '-', color='DarkBlue') rng = np.max(flux) - np.min(flux) if rng > 0: ax1.set_ylim(np.min(flux) - 0.1*rng, np.max(flux) + 0.1*rng) left = np.argmax(flux < (1. - 1.e-8)) right = np.argmax(flux[left:] > (1. - 1.e-8)) + left rng = time[right] - time[left] ax1.set_xlim(time[left] - rng, time[right] + rng) ax1.set_xlabel('Time (Days)', fontweight='bold') ax1.set_ylabel('Normalized Flux', fontweight='bold') # Adjust these for full-orbit plotting maxpts = kwargs.get('maxpts', 10000); kwargs.update({'maxpts': maxpts}) per = kwargs.get('per', 10.); kwargs.update({'per': per}) kwargs.update({'fullorbit': True}) kwargs.update({'exppts': 30}) kwargs.update({'exptime': 50 * per / maxpts}) trn = Transit(**kwargs) try: trn.Compute() except Exception as e: if str(e) == "Object does not transit the star.": pass else: raise Exception(e) # Sky-projected motion x = trn.arrays.x y = trn.arrays.y z = trn.arrays.z inc = (np.arccos(trn.transit.bcirc/trn.transit.aRs)*180./np.pi) # Orbital inclination # Mask the star for j in range(len(x)): if (x[j]**2 + y[j]**2) < 1. and (z[j] > 0): x[j] = np.nan y[j] = np.nan # The star r = np.linspace(0,1,100) Ir = I(r,trn.limbdark)/I(0,trn.limbdark) for ri,Iri in zip(r[::-1],Ir[::-1]): star = pl.Circle((0, 0), ri, color=str(0.95*Iri), alpha=1.) ax2.add_artist(star) # Inset: Limb darkening if ldplot: if compact: inset1 = pl.axes([0.145, 0.32, .09, .1]) else: inset1 = fig.add_axes([0.725,0.3,0.2,0.15]) inset1.plot(r,Ir,'k-') pl.setp(inset1, xlim=(-0.1,1.1), ylim=(-0.1,1.1), xticks=[0,1], yticks=[0,1]) for tick in inset1.xaxis.get_major_ticks() + inset1.yaxis.get_major_ticks(): tick.label.set_fontsize(8) inset1.set_ylabel(r'I/I$_0$', fontsize=8, labelpad=-8) inset1.set_xlabel(r'r/R$_\star$', fontsize=8, labelpad=-8) inset1.set_title('Limb Darkening', fontweight='bold', fontsize=9) # Inset: Top view of orbit if compact: inset2 = pl.axes([0.135, 0.115, .1, .1]) else: inset2 = fig.add_axes([0.725,0.1,0.2,0.15]) pl.setp(inset2, xticks=[], yticks=[]) trn.transit.bcirc = trn.transit.aRs # This ensures we are face-on try: trn.Compute() except Exception as e: if str(e) == "Object does not transit the star.": pass else: raise Exception(e) xp = trn.arrays.x yp = trn.arrays.y inset2.plot(xp, yp, '-', color='DarkBlue', alpha=0.5) # Draw some invisible dots at the corners to set the window size xmin, xmax, ymin, ymax = np.nanmin(xp), np.nanmax(xp), np.nanmin(yp), np.nanmax(yp) xrng = xmax - xmin yrng = ymax - ymin xmin -= 0.1*xrng; xmax += 0.1*xrng; ymin -= 0.1*yrng; ymax += 0.1*yrng; inset2.scatter([xmin,xmin,xmax,xmax], [ymin,ymax,ymin,ymax], alpha = 0.) # Plot the star for ri,Iri in zip(r[::-10],Ir[::-10]): star = pl.Circle((0, 0), ri, color=str(0.95*Iri), alpha=1.) inset2.add_artist(star) # Plot the planet ycenter = yp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))][0] while ycenter > 0: xp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))] = np.nan ycenter = yp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))][0] planet = pl.Circle((0, ycenter), trn.transit.RpRs, color='DarkBlue', alpha=1.) inset2.add_artist(planet) inset2.set_title('Top View', fontweight='bold', fontsize=9) inset2.set_aspect('equal','datalim') # The orbit itself with np.errstate(invalid='ignore'): ax2.plot(x, y, '-', color='DarkBlue', lw = 1. if per < 30. else max(1. - (per - 30.) / 100., 0.3) ) # The planet with np.errstate(invalid = 'ignore'): ycenter = y[np.where(np.abs(x) == np.nanmin(np.abs(x)))][0] while ycenter > 0: x[np.where(np.abs(x) == np.nanmin(np.abs(x)))] = np.nan ycenter = y[np.where(np.abs(x) == np.nanmin(np.abs(x)))][0] planet = pl.Circle((0, ycenter), trn.transit.RpRs, color='DarkBlue', alpha=1.) ax2.add_artist(planet) # Force aspect if xlim is None: xlim = 1.1 * max(np.nanmax(x), np.nanmax(-x)) ax2.set_ylim(-xlim/3.2,xlim/3.2) ax2.set_xlim(-xlim,xlim) ax2.set_xlabel(r'X (R$_\star$)', fontweight='bold') ax2.set_ylabel(r'Y (R$_\star$)', fontweight='bold') ax1.set_title(plottitle, fontsize=12) if not compact: rect = 0.725,0.55,0.2,0.35 ax3 = fig.add_axes(rect) ax3.xaxis.set_visible(False) ax3.yaxis.set_visible(False) # Table of parameters ltable = [ r'$P:$', r'$e:$', r'$i:$', r'$\omega:$', r'$\rho_\star:$', r'$M_p:$', r'$R_p:$', r'$q_1:$', r'$q_2:$'] rtable = [ r'$%.4f\ \mathrm{days}$' % trn.transit.per, r'$%.5f$' % trn.transit.ecc, r'$%.4f^\circ$' % inc, r'$%.3f^\circ$' % (trn.transit.w*180./np.pi), r'$%.5f\ \mathrm{g/cm^3}$' % trn.transit.rhos, r'$%.5f\ M_\star$' % trn.transit.MpMs, r'$%.5f\ R_\star$' % trn.transit.RpRs, r'$%.5f$' % trn.limbdark.q1, r'$%.5f$' % trn.limbdark.q2] yt = 0.875 for l,r in zip(ltable, rtable): ax3.annotate(l, xy=(0.25, yt), xycoords="axes fraction", ha='right', fontsize=16) ax3.annotate(r, xy=(0.35, yt), xycoords="axes fraction", fontsize=16) yt -= 0.1 return fig
def PlotTransit(compact = False, ldplot = True, plottitle = "", xlim = None, binned = True, **kwargs): ''' Plots a light curve described by `kwargs` :param bool compact: Display the compact version of the plot? Default `False` :param bool ldplot: Displat the limb darkening inset? Default `True` :param str plottitle: The title of the plot. Default `""` :param float xlim: The half-width of the orbit plot in stellar radii. Default is to \ auto adjust this :param bool binned: Bin the light curve model to the exposure time? Default `True` :param kwargs: Any keyword arguments to be passed to :py:func:`pysyzygy.transit.Transit` :returns fig: The :py:mod:`matplotlib` figure object ''' # Plotting fig = pl.figure(figsize = (12,8)) fig.subplots_adjust(hspace=0.3) ax1, ax2 = pl.subplot(211), pl.subplot(212) if not compact: fig.subplots_adjust(right = 0.7) t0 = kwargs.pop('t0', 0.) trn = Transit(**kwargs) try: trn.Compute() notransit = False except Exception as e: if str(e) == "Object does not transit the star.": notransit = True else: raise Exception(e) time = trn.arrays.time + t0 if not notransit: if binned: trn.Bin() flux = trn.arrays.bflx else: flux = trn.arrays.flux time = np.concatenate(([-1.e5], time, [1.e5])) # Add baseline on each side flux = np.concatenate(([1.], flux, [1.])) ax1.plot(time, flux, '-', color='DarkBlue') rng = np.max(flux) - np.min(flux) if rng > 0: ax1.set_ylim(np.min(flux) - 0.1*rng, np.max(flux) + 0.1*rng) left = np.argmax(flux < (1. - 1.e-8)) right = np.argmax(flux[left:] > (1. - 1.e-8)) + left rng = time[right] - time[left] ax1.set_xlim(time[left] - rng, time[right] + rng) ax1.set_xlabel('Time (Days)', fontweight='bold') ax1.set_ylabel('Normalized Flux', fontweight='bold') # Adjust these for full-orbit plotting maxpts = kwargs.get('maxpts', 10000); kwargs.update({'maxpts': maxpts}) per = kwargs.get('per', 10.); kwargs.update({'per': per}) kwargs.update({'fullorbit': True}) kwargs.update({'exppts': 30}) kwargs.update({'exptime': 50 * per / maxpts}) trn = Transit(**kwargs) try: trn.Compute() except Exception as e: if str(e) == "Object does not transit the star.": pass else: raise Exception(e) # Sky-projected motion x = trn.arrays.x y = trn.arrays.y z = trn.arrays.z inc = (np.arccos(trn.transit.bcirc/trn.transit.aRs)*180./np.pi) # Orbital inclination # Mask the star for j in range(len(x)): if (x[j]**2 + y[j]**2) < 1. and (z[j] > 0): x[j] = np.nan y[j] = np.nan # The star r = np.linspace(0,1,100) Ir = I(r,trn.limbdark)/I(0,trn.limbdark) for ri,Iri in zip(r[::-1],Ir[::-1]): star = pl.Circle((0, 0), ri, color=str(0.95*Iri), alpha=1.) ax2.add_artist(star) # Inset: Limb darkening if ldplot: if compact: inset1 = pl.axes([0.145, 0.32, .09, .1]) else: inset1 = fig.add_axes([0.725,0.3,0.2,0.15]) inset1.plot(r,Ir,'k-') pl.setp(inset1, xlim=(-0.1,1.1), ylim=(-0.1,1.1), xticks=[0,1], yticks=[0,1]) for tick in inset1.xaxis.get_major_ticks() + inset1.yaxis.get_major_ticks(): tick.label.set_fontsize(8) inset1.set_ylabel(r'I/I$_0$', fontsize=8, labelpad=-8) inset1.set_xlabel(r'r/R$_\star$', fontsize=8, labelpad=-8) inset1.set_title('Limb Darkening', fontweight='bold', fontsize=9) # Inset: Top view of orbit if compact: inset2 = pl.axes([0.135, 0.115, .1, .1]) else: inset2 = fig.add_axes([0.725,0.1,0.2,0.15]) pl.setp(inset2, xticks=[], yticks=[]) trn.transit.bcirc = trn.transit.aRs # This ensures we are face-on try: trn.Compute() except Exception as e: if str(e) == "Object does not transit the star.": pass else: raise Exception(e) xp = trn.arrays.x yp = trn.arrays.y inset2.plot(xp, yp, '-', color='DarkBlue', alpha=0.5) # Draw some invisible dots at the corners to set the window size xmin, xmax, ymin, ymax = np.nanmin(xp), np.nanmax(xp), np.nanmin(yp), np.nanmax(yp) xrng = xmax - xmin yrng = ymax - ymin xmin -= 0.1*xrng; xmax += 0.1*xrng; ymin -= 0.1*yrng; ymax += 0.1*yrng; inset2.scatter([xmin,xmin,xmax,xmax], [ymin,ymax,ymin,ymax], alpha = 0.) # Plot the star for ri,Iri in zip(r[::-10],Ir[::-10]): star = pl.Circle((0, 0), ri, color=str(0.95*Iri), alpha=1.) inset2.add_artist(star) # Plot the planet ycenter = yp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))][0] while ycenter > 0: xp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))] = np.nan ycenter = yp[np.where(np.abs(xp) == np.nanmin(np.abs(xp)))][0] planet = pl.Circle((0, ycenter), trn.transit.RpRs, color='DarkBlue', alpha=1.) inset2.add_artist(planet) inset2.set_title('Top View', fontweight='bold', fontsize=9) inset2.set_aspect('equal','datalim') # The orbit itself with np.errstate(invalid='ignore'): ax2.plot(x, y, '-', color='DarkBlue', lw = 1. if per < 30. else max(1. - (per - 30.) / 100., 0.3) ) # The planet with np.errstate(invalid = 'ignore'): ycenter = y[np.where(np.abs(x) == np.nanmin(np.abs(x)))][0] while ycenter > 0: x[np.where(np.abs(x) == np.nanmin(np.abs(x)))] = np.nan ycenter = y[np.where(np.abs(x) == np.nanmin(np.abs(x)))][0] planet = pl.Circle((0, ycenter), trn.transit.RpRs, color='DarkBlue', alpha=1.) ax2.add_artist(planet) # Force aspect if xlim is None: xlim = 1.1 * max(np.nanmax(x), np.nanmax(-x)) ax2.set_ylim(-xlim/3.2,xlim/3.2) ax2.set_xlim(-xlim,xlim) ax2.set_xlabel(r'X (R$_\star$)', fontweight='bold') ax2.set_ylabel(r'Y (R$_\star$)', fontweight='bold') ax1.set_title(plottitle, fontsize=12) if not compact: rect = 0.725,0.55,0.2,0.35 ax3 = fig.add_axes(rect) ax3.xaxis.set_visible(False) ax3.yaxis.set_visible(False) # Table of parameters ltable = [ r'$P:$', r'$e:$', r'$i:$', r'$\omega:$', r'$\rho_\star:$', r'$M_p:$', r'$R_p:$', r'$q_1:$', r'$q_2:$'] rtable = [ r'$%.4f\ \mathrm{days}$' % trn.transit.per, r'$%.5f$' % trn.transit.ecc, r'$%.4f^\circ$' % inc, r'$%.3f^\circ$' % (trn.transit.w*180./np.pi), r'$%.5f\ \mathrm{g/cm^3}$' % trn.transit.rhos, r'$%.5f\ M_\star$' % trn.transit.MpMs, r'$%.5f\ R_\star$' % trn.transit.RpRs, r'$%.5f$' % trn.limbdark.q1, r'$%.5f$' % trn.limbdark.q2] yt = 0.875 for l,r in zip(ltable, rtable): ax3.annotate(l, xy=(0.25, yt), xycoords="axes fraction", ha='right', fontsize=16) ax3.annotate(r, xy=(0.35, yt), xycoords="axes fraction", fontsize=16) yt -= 0.1 return fig
[ "Plots", "a", "light", "curve", "described", "by", "kwargs", ":", "param", "bool", "compact", ":", "Display", "the", "compact", "version", "of", "the", "plot?", "Default", "False", ":", "param", "bool", "ldplot", ":", "Displat", "the", "limb", "darkening", "inset?", "Default", "True", ":", "param", "str", "plottitle", ":", "The", "title", "of", "the", "plot", ".", "Default", ":", "param", "float", "xlim", ":", "The", "half", "-", "width", "of", "the", "orbit", "plot", "in", "stellar", "radii", ".", "Default", "is", "to", "\\", "auto", "adjust", "this", ":", "param", "bool", "binned", ":", "Bin", "the", "light", "curve", "model", "to", "the", "exposure", "time?", "Default", "True", ":", "param", "kwargs", ":", "Any", "keyword", "arguments", "to", "be", "passed", "to", ":", "py", ":", "func", ":", "pysyzygy", ".", "transit", ".", "Transit", ":", "returns", "fig", ":", "The", ":", "py", ":", "mod", ":", "matplotlib", "figure", "object" ]
rodluger/pysyzygy
python
https://github.com/rodluger/pysyzygy/blob/d2b64251047cc0f0d0adeb6feab4054e7fce4b7a/pysyzygy/plot.py#L57-L256
[ "def", "PlotTransit", "(", "compact", "=", "False", ",", "ldplot", "=", "True", ",", "plottitle", "=", "\"\"", ",", "xlim", "=", "None", ",", "binned", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Plotting", "fig", "=", "pl", ".", "figure", "(", "figsize", "=", "(", "12", ",", "8", ")", ")", "fig", ".", "subplots_adjust", "(", "hspace", "=", "0.3", ")", "ax1", ",", "ax2", "=", "pl", ".", "subplot", "(", "211", ")", ",", "pl", ".", "subplot", "(", "212", ")", "if", "not", "compact", ":", "fig", ".", "subplots_adjust", "(", "right", "=", "0.7", ")", "t0", "=", "kwargs", ".", "pop", "(", "'t0'", ",", "0.", ")", "trn", "=", "Transit", "(", "*", "*", "kwargs", ")", "try", ":", "trn", ".", "Compute", "(", ")", "notransit", "=", "False", "except", "Exception", "as", "e", ":", "if", "str", "(", "e", ")", "==", "\"Object does not transit the star.\"", ":", "notransit", "=", "True", "else", ":", "raise", "Exception", "(", "e", ")", "time", "=", "trn", ".", "arrays", ".", "time", "+", "t0", "if", "not", "notransit", ":", "if", "binned", ":", "trn", ".", "Bin", "(", ")", "flux", "=", "trn", ".", "arrays", ".", "bflx", "else", ":", "flux", "=", "trn", ".", "arrays", ".", "flux", "time", "=", "np", ".", "concatenate", "(", "(", "[", "-", "1.e5", "]", ",", "time", ",", "[", "1.e5", "]", ")", ")", "# Add baseline on each side", "flux", "=", "np", ".", "concatenate", "(", "(", "[", "1.", "]", ",", "flux", ",", "[", "1.", "]", ")", ")", "ax1", ".", "plot", "(", "time", ",", "flux", ",", "'-'", ",", "color", "=", "'DarkBlue'", ")", "rng", "=", "np", ".", "max", "(", "flux", ")", "-", "np", ".", "min", "(", "flux", ")", "if", "rng", ">", "0", ":", "ax1", ".", "set_ylim", "(", "np", ".", "min", "(", "flux", ")", "-", "0.1", "*", "rng", ",", "np", ".", "max", "(", "flux", ")", "+", "0.1", "*", "rng", ")", "left", "=", "np", ".", "argmax", "(", "flux", "<", "(", "1.", "-", "1.e-8", ")", ")", "right", "=", "np", ".", "argmax", "(", "flux", "[", "left", ":", "]", ">", "(", "1.", "-", "1.e-8", ")", ")", "+", "left", "rng", "=", "time", "[", "right", "]", "-", "time", "[", "left", "]", "ax1", ".", "set_xlim", "(", "time", "[", "left", "]", "-", "rng", ",", "time", "[", "right", "]", "+", "rng", ")", "ax1", ".", "set_xlabel", "(", "'Time (Days)'", ",", "fontweight", "=", "'bold'", ")", "ax1", ".", "set_ylabel", "(", "'Normalized Flux'", ",", "fontweight", "=", "'bold'", ")", "# Adjust these for full-orbit plotting", "maxpts", "=", "kwargs", ".", "get", "(", "'maxpts'", ",", "10000", ")", "kwargs", ".", "update", "(", "{", "'maxpts'", ":", "maxpts", "}", ")", "per", "=", "kwargs", ".", "get", "(", "'per'", ",", "10.", ")", "kwargs", ".", "update", "(", "{", "'per'", ":", "per", "}", ")", "kwargs", ".", "update", "(", "{", "'fullorbit'", ":", "True", "}", ")", "kwargs", ".", "update", "(", "{", "'exppts'", ":", "30", "}", ")", "kwargs", ".", "update", "(", "{", "'exptime'", ":", "50", "*", "per", "/", "maxpts", "}", ")", "trn", "=", "Transit", "(", "*", "*", "kwargs", ")", "try", ":", "trn", ".", "Compute", "(", ")", "except", "Exception", "as", "e", ":", "if", "str", "(", "e", ")", "==", "\"Object does not transit the star.\"", ":", "pass", "else", ":", "raise", "Exception", "(", "e", ")", "# Sky-projected motion", "x", "=", "trn", ".", "arrays", ".", "x", "y", "=", "trn", ".", "arrays", ".", "y", "z", "=", "trn", ".", "arrays", ".", "z", "inc", "=", "(", "np", ".", "arccos", "(", "trn", ".", "transit", ".", "bcirc", "/", "trn", ".", "transit", ".", "aRs", ")", "*", "180.", "/", "np", ".", "pi", ")", "# Orbital inclination", "# Mask the star", "for", "j", "in", "range", "(", "len", "(", "x", ")", ")", ":", "if", "(", "x", "[", "j", "]", "**", "2", "+", "y", "[", "j", "]", "**", "2", ")", "<", "1.", "and", "(", "z", "[", "j", "]", ">", "0", ")", ":", "x", "[", "j", "]", "=", "np", ".", "nan", "y", "[", "j", "]", "=", "np", ".", "nan", "# The star", "r", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "100", ")", "Ir", "=", "I", "(", "r", ",", "trn", ".", "limbdark", ")", "/", "I", "(", "0", ",", "trn", ".", "limbdark", ")", "for", "ri", ",", "Iri", "in", "zip", "(", "r", "[", ":", ":", "-", "1", "]", ",", "Ir", "[", ":", ":", "-", "1", "]", ")", ":", "star", "=", "pl", ".", "Circle", "(", "(", "0", ",", "0", ")", ",", "ri", ",", "color", "=", "str", "(", "0.95", "*", "Iri", ")", ",", "alpha", "=", "1.", ")", "ax2", ".", "add_artist", "(", "star", ")", "# Inset: Limb darkening", "if", "ldplot", ":", "if", "compact", ":", "inset1", "=", "pl", ".", "axes", "(", "[", "0.145", ",", "0.32", ",", ".09", ",", ".1", "]", ")", "else", ":", "inset1", "=", "fig", ".", "add_axes", "(", "[", "0.725", ",", "0.3", ",", "0.2", ",", "0.15", "]", ")", "inset1", ".", "plot", "(", "r", ",", "Ir", ",", "'k-'", ")", "pl", ".", "setp", "(", "inset1", ",", "xlim", "=", "(", "-", "0.1", ",", "1.1", ")", ",", "ylim", "=", "(", "-", "0.1", ",", "1.1", ")", ",", "xticks", "=", "[", "0", ",", "1", "]", ",", "yticks", "=", "[", "0", ",", "1", "]", ")", "for", "tick", "in", "inset1", ".", "xaxis", ".", "get_major_ticks", "(", ")", "+", "inset1", ".", "yaxis", ".", "get_major_ticks", "(", ")", ":", "tick", ".", "label", ".", "set_fontsize", "(", "8", ")", "inset1", ".", "set_ylabel", "(", "r'I/I$_0$'", ",", "fontsize", "=", "8", ",", "labelpad", "=", "-", "8", ")", "inset1", ".", "set_xlabel", "(", "r'r/R$_\\star$'", ",", "fontsize", "=", "8", ",", "labelpad", "=", "-", "8", ")", "inset1", ".", "set_title", "(", "'Limb Darkening'", ",", "fontweight", "=", "'bold'", ",", "fontsize", "=", "9", ")", "# Inset: Top view of orbit", "if", "compact", ":", "inset2", "=", "pl", ".", "axes", "(", "[", "0.135", ",", "0.115", ",", ".1", ",", ".1", "]", ")", "else", ":", "inset2", "=", "fig", ".", "add_axes", "(", "[", "0.725", ",", "0.1", ",", "0.2", ",", "0.15", "]", ")", "pl", ".", "setp", "(", "inset2", ",", "xticks", "=", "[", "]", ",", "yticks", "=", "[", "]", ")", "trn", ".", "transit", ".", "bcirc", "=", "trn", ".", "transit", ".", "aRs", "# This ensures we are face-on", "try", ":", "trn", ".", "Compute", "(", ")", "except", "Exception", "as", "e", ":", "if", "str", "(", "e", ")", "==", "\"Object does not transit the star.\"", ":", "pass", "else", ":", "raise", "Exception", "(", "e", ")", "xp", "=", "trn", ".", "arrays", ".", "x", "yp", "=", "trn", ".", "arrays", ".", "y", "inset2", ".", "plot", "(", "xp", ",", "yp", ",", "'-'", ",", "color", "=", "'DarkBlue'", ",", "alpha", "=", "0.5", ")", "# Draw some invisible dots at the corners to set the window size", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "np", ".", "nanmin", "(", "xp", ")", ",", "np", ".", "nanmax", "(", "xp", ")", ",", "np", ".", "nanmin", "(", "yp", ")", ",", "np", ".", "nanmax", "(", "yp", ")", "xrng", "=", "xmax", "-", "xmin", "yrng", "=", "ymax", "-", "ymin", "xmin", "-=", "0.1", "*", "xrng", "xmax", "+=", "0.1", "*", "xrng", "ymin", "-=", "0.1", "*", "yrng", "ymax", "+=", "0.1", "*", "yrng", "inset2", ".", "scatter", "(", "[", "xmin", ",", "xmin", ",", "xmax", ",", "xmax", "]", ",", "[", "ymin", ",", "ymax", ",", "ymin", ",", "ymax", "]", ",", "alpha", "=", "0.", ")", "# Plot the star", "for", "ri", ",", "Iri", "in", "zip", "(", "r", "[", ":", ":", "-", "10", "]", ",", "Ir", "[", ":", ":", "-", "10", "]", ")", ":", "star", "=", "pl", ".", "Circle", "(", "(", "0", ",", "0", ")", ",", "ri", ",", "color", "=", "str", "(", "0.95", "*", "Iri", ")", ",", "alpha", "=", "1.", ")", "inset2", ".", "add_artist", "(", "star", ")", "# Plot the planet", "ycenter", "=", "yp", "[", "np", ".", "where", "(", "np", ".", "abs", "(", "xp", ")", "==", "np", ".", "nanmin", "(", "np", ".", "abs", "(", "xp", ")", ")", ")", "]", "[", "0", "]", "while", "ycenter", ">", "0", ":", "xp", "[", "np", ".", "where", "(", "np", ".", "abs", "(", "xp", ")", "==", "np", ".", "nanmin", "(", "np", ".", "abs", "(", "xp", ")", ")", ")", "]", "=", "np", ".", "nan", "ycenter", "=", "yp", "[", "np", ".", "where", "(", "np", ".", "abs", "(", "xp", ")", "==", "np", ".", "nanmin", "(", "np", ".", "abs", "(", "xp", ")", ")", ")", "]", "[", "0", "]", "planet", "=", "pl", ".", "Circle", "(", "(", "0", ",", "ycenter", ")", ",", "trn", ".", "transit", ".", "RpRs", ",", "color", "=", "'DarkBlue'", ",", "alpha", "=", "1.", ")", "inset2", ".", "add_artist", "(", "planet", ")", "inset2", ".", "set_title", "(", "'Top View'", ",", "fontweight", "=", "'bold'", ",", "fontsize", "=", "9", ")", "inset2", ".", "set_aspect", "(", "'equal'", ",", "'datalim'", ")", "# The orbit itself", "with", "np", ".", "errstate", "(", "invalid", "=", "'ignore'", ")", ":", "ax2", ".", "plot", "(", "x", ",", "y", ",", "'-'", ",", "color", "=", "'DarkBlue'", ",", "lw", "=", "1.", "if", "per", "<", "30.", "else", "max", "(", "1.", "-", "(", "per", "-", "30.", ")", "/", "100.", ",", "0.3", ")", ")", "# The planet", "with", "np", ".", "errstate", "(", "invalid", "=", "'ignore'", ")", ":", "ycenter", "=", "y", "[", "np", ".", "where", "(", "np", ".", "abs", "(", "x", ")", "==", "np", ".", "nanmin", "(", "np", ".", "abs", "(", "x", ")", ")", ")", "]", "[", "0", "]", "while", "ycenter", ">", "0", ":", "x", "[", "np", ".", "where", "(", "np", ".", "abs", "(", "x", ")", "==", "np", ".", "nanmin", "(", "np", ".", "abs", "(", "x", ")", ")", ")", "]", "=", "np", ".", "nan", "ycenter", "=", "y", "[", "np", ".", "where", "(", "np", ".", "abs", "(", "x", ")", "==", "np", ".", "nanmin", "(", "np", ".", "abs", "(", "x", ")", ")", ")", "]", "[", "0", "]", "planet", "=", "pl", ".", "Circle", "(", "(", "0", ",", "ycenter", ")", ",", "trn", ".", "transit", ".", "RpRs", ",", "color", "=", "'DarkBlue'", ",", "alpha", "=", "1.", ")", "ax2", ".", "add_artist", "(", "planet", ")", "# Force aspect", "if", "xlim", "is", "None", ":", "xlim", "=", "1.1", "*", "max", "(", "np", ".", "nanmax", "(", "x", ")", ",", "np", ".", "nanmax", "(", "-", "x", ")", ")", "ax2", ".", "set_ylim", "(", "-", "xlim", "/", "3.2", ",", "xlim", "/", "3.2", ")", "ax2", ".", "set_xlim", "(", "-", "xlim", ",", "xlim", ")", "ax2", ".", "set_xlabel", "(", "r'X (R$_\\star$)'", ",", "fontweight", "=", "'bold'", ")", "ax2", ".", "set_ylabel", "(", "r'Y (R$_\\star$)'", ",", "fontweight", "=", "'bold'", ")", "ax1", ".", "set_title", "(", "plottitle", ",", "fontsize", "=", "12", ")", "if", "not", "compact", ":", "rect", "=", "0.725", ",", "0.55", ",", "0.2", ",", "0.35", "ax3", "=", "fig", ".", "add_axes", "(", "rect", ")", "ax3", ".", "xaxis", ".", "set_visible", "(", "False", ")", "ax3", ".", "yaxis", ".", "set_visible", "(", "False", ")", "# Table of parameters", "ltable", "=", "[", "r'$P:$'", ",", "r'$e:$'", ",", "r'$i:$'", ",", "r'$\\omega:$'", ",", "r'$\\rho_\\star:$'", ",", "r'$M_p:$'", ",", "r'$R_p:$'", ",", "r'$q_1:$'", ",", "r'$q_2:$'", "]", "rtable", "=", "[", "r'$%.4f\\ \\mathrm{days}$'", "%", "trn", ".", "transit", ".", "per", ",", "r'$%.5f$'", "%", "trn", ".", "transit", ".", "ecc", ",", "r'$%.4f^\\circ$'", "%", "inc", ",", "r'$%.3f^\\circ$'", "%", "(", "trn", ".", "transit", ".", "w", "*", "180.", "/", "np", ".", "pi", ")", ",", "r'$%.5f\\ \\mathrm{g/cm^3}$'", "%", "trn", ".", "transit", ".", "rhos", ",", "r'$%.5f\\ M_\\star$'", "%", "trn", ".", "transit", ".", "MpMs", ",", "r'$%.5f\\ R_\\star$'", "%", "trn", ".", "transit", ".", "RpRs", ",", "r'$%.5f$'", "%", "trn", ".", "limbdark", ".", "q1", ",", "r'$%.5f$'", "%", "trn", ".", "limbdark", ".", "q2", "]", "yt", "=", "0.875", "for", "l", ",", "r", "in", "zip", "(", "ltable", ",", "rtable", ")", ":", "ax3", ".", "annotate", "(", "l", ",", "xy", "=", "(", "0.25", ",", "yt", ")", ",", "xycoords", "=", "\"axes fraction\"", ",", "ha", "=", "'right'", ",", "fontsize", "=", "16", ")", "ax3", ".", "annotate", "(", "r", ",", "xy", "=", "(", "0.35", ",", "yt", ")", ",", "xycoords", "=", "\"axes fraction\"", ",", "fontsize", "=", "16", ")", "yt", "-=", "0.1", "return", "fig" ]
d2b64251047cc0f0d0adeb6feab4054e7fce4b7a
test
_offset
Parse timezone to offset in seconds. Args: value: A timezone in the '+0000' format. An integer would also work. Returns: The timezone offset from GMT in seconds as an integer.
nntp/date.py
def _offset(value): """Parse timezone to offset in seconds. Args: value: A timezone in the '+0000' format. An integer would also work. Returns: The timezone offset from GMT in seconds as an integer. """ o = int(value) if o == 0: return 0 a = abs(o) s = a*36+(a%100)*24 return (o//a)*s
def _offset(value): """Parse timezone to offset in seconds. Args: value: A timezone in the '+0000' format. An integer would also work. Returns: The timezone offset from GMT in seconds as an integer. """ o = int(value) if o == 0: return 0 a = abs(o) s = a*36+(a%100)*24 return (o//a)*s
[ "Parse", "timezone", "to", "offset", "in", "seconds", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L51-L65
[ "def", "_offset", "(", "value", ")", ":", "o", "=", "int", "(", "value", ")", "if", "o", "==", "0", ":", "return", "0", "a", "=", "abs", "(", "o", ")", "s", "=", "a", "*", "36", "+", "(", "a", "%", "100", ")", "*", "24", "return", "(", "o", "//", "a", ")", "*", "s" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
timestamp_d_b_Y_H_M_S
Convert timestamp string to time in seconds since epoch. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. Note: The timezone is ignored it is simply assumed to be UTC/GMT.
nntp/date.py
def timestamp_d_b_Y_H_M_S(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. Note: The timezone is ignored it is simply assumed to be UTC/GMT. """ d, b, Y, t, Z = value.split() H, M, S = t.split(":") return int(calendar.timegm(( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), 0, 0, 0 )))
def timestamp_d_b_Y_H_M_S(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. Note: The timezone is ignored it is simply assumed to be UTC/GMT. """ d, b, Y, t, Z = value.split() H, M, S = t.split(":") return int(calendar.timegm(( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), 0, 0, 0 )))
[ "Convert", "timestamp", "string", "to", "time", "in", "seconds", "since", "epoch", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L67-L89
[ "def", "timestamp_d_b_Y_H_M_S", "(", "value", ")", ":", "d", ",", "b", ",", "Y", ",", "t", ",", "Z", "=", "value", ".", "split", "(", ")", "H", ",", "M", ",", "S", "=", "t", ".", "split", "(", "\":\"", ")", "return", "int", "(", "calendar", ".", "timegm", "(", "(", "int", "(", "Y", ")", ",", "_months", "[", "b", ".", "lower", "(", ")", "]", ",", "int", "(", "d", ")", ",", "int", "(", "H", ")", ",", "int", "(", "M", ")", ",", "int", "(", "S", ")", ",", "0", ",", "0", ",", "0", ")", ")", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
datetimeobj_d_b_Y_H_M_S
Convert timestamp string to a datetime object. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. Note: The timezone is ignored it is simply assumed to be UTC/GMT.
nntp/date.py
def datetimeobj_d_b_Y_H_M_S(value): """Convert timestamp string to a datetime object. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. Note: The timezone is ignored it is simply assumed to be UTC/GMT. """ d, b, Y, t, Z = value.split() H, M, S = t.split(":") return datetime.datetime( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), tzinfo=TZ_GMT )
def datetimeobj_d_b_Y_H_M_S(value): """Convert timestamp string to a datetime object. Timestamps strings like '18 Jun 2013 12:00:00 GMT' are able to be converted by this function. Args: value: A timestamp string in the format '%d %b %Y %H:%M:%S GMT'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. Note: The timezone is ignored it is simply assumed to be UTC/GMT. """ d, b, Y, t, Z = value.split() H, M, S = t.split(":") return datetime.datetime( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), tzinfo=TZ_GMT )
[ "Convert", "timestamp", "string", "to", "a", "datetime", "object", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L91-L113
[ "def", "datetimeobj_d_b_Y_H_M_S", "(", "value", ")", ":", "d", ",", "b", ",", "Y", ",", "t", ",", "Z", "=", "value", ".", "split", "(", ")", "H", ",", "M", ",", "S", "=", "t", ".", "split", "(", "\":\"", ")", "return", "datetime", ".", "datetime", "(", "int", "(", "Y", ")", ",", "_months", "[", "b", ".", "lower", "(", ")", "]", ",", "int", "(", "d", ")", ",", "int", "(", "H", ")", ",", "int", "(", "M", ")", ",", "int", "(", "S", ")", ",", "tzinfo", "=", "TZ_GMT", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
timestamp_a__d_b_Y_H_M_S_z
Convert timestamp string to time in seconds since epoch. Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be converted by this function. Args: value: A timestamp string in the format '%a, %d %b %Y %H:%M:%S %z'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid.
nntp/date.py
def timestamp_a__d_b_Y_H_M_S_z(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be converted by this function. Args: value: A timestamp string in the format '%a, %d %b %Y %H:%M:%S %z'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. """ a, d, b, Y, t, z = value.split() H, M, S = t.split(":") return int(calendar.timegm(( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), 0, 0, 0 ))) - _offset(z)
def timestamp_a__d_b_Y_H_M_S_z(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be converted by this function. Args: value: A timestamp string in the format '%a, %d %b %Y %H:%M:%S %z'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. """ a, d, b, Y, t, z = value.split() H, M, S = t.split(":") return int(calendar.timegm(( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), 0, 0, 0 ))) - _offset(z)
[ "Convert", "timestamp", "string", "to", "time", "in", "seconds", "since", "epoch", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L115-L135
[ "def", "timestamp_a__d_b_Y_H_M_S_z", "(", "value", ")", ":", "a", ",", "d", ",", "b", ",", "Y", ",", "t", ",", "z", "=", "value", ".", "split", "(", ")", "H", ",", "M", ",", "S", "=", "t", ".", "split", "(", "\":\"", ")", "return", "int", "(", "calendar", ".", "timegm", "(", "(", "int", "(", "Y", ")", ",", "_months", "[", "b", ".", "lower", "(", ")", "]", ",", "int", "(", "d", ")", ",", "int", "(", "H", ")", ",", "int", "(", "M", ")", ",", "int", "(", "S", ")", ",", "0", ",", "0", ",", "0", ")", ")", ")", "-", "_offset", "(", "z", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
datetimeobj_a__d_b_Y_H_M_S_z
Convert timestamp string to a datetime object. Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be converted by this function. Args: value: A timestamp string in the format '%a, %d %b %Y %H:%M:%S %z'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid.
nntp/date.py
def datetimeobj_a__d_b_Y_H_M_S_z(value): """Convert timestamp string to a datetime object. Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be converted by this function. Args: value: A timestamp string in the format '%a, %d %b %Y %H:%M:%S %z'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. """ a, d, b, Y, t, z = value.split() H, M, S = t.split(":") return datetime.datetime( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), tzinfo=dateutil.tz.tzoffset(None, _offset(z)) )
def datetimeobj_a__d_b_Y_H_M_S_z(value): """Convert timestamp string to a datetime object. Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be converted by this function. Args: value: A timestamp string in the format '%a, %d %b %Y %H:%M:%S %z'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. KeyError: If the abbrieviated month is invalid. """ a, d, b, Y, t, z = value.split() H, M, S = t.split(":") return datetime.datetime( int(Y), _months[b.lower()], int(d), int(H), int(M), int(S), tzinfo=dateutil.tz.tzoffset(None, _offset(z)) )
[ "Convert", "timestamp", "string", "to", "a", "datetime", "object", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L137-L158
[ "def", "datetimeobj_a__d_b_Y_H_M_S_z", "(", "value", ")", ":", "a", ",", "d", ",", "b", ",", "Y", ",", "t", ",", "z", "=", "value", ".", "split", "(", ")", "H", ",", "M", ",", "S", "=", "t", ".", "split", "(", "\":\"", ")", "return", "datetime", ".", "datetime", "(", "int", "(", "Y", ")", ",", "_months", "[", "b", ".", "lower", "(", ")", "]", ",", "int", "(", "d", ")", ",", "int", "(", "H", ")", ",", "int", "(", "M", ")", ",", "int", "(", "S", ")", ",", "tzinfo", "=", "dateutil", ".", "tz", ".", "tzoffset", "(", "None", ",", "_offset", "(", "z", ")", ")", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
timestamp_YmdHMS
Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. Note: The timezone is assumed to be UTC/GMT.
nntp/date.py
def timestamp_YmdHMS(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. Note: The timezone is assumed to be UTC/GMT. """ i = int(value) S = i M = S//100 H = M//100 d = H//100 m = d//100 Y = m//100 return int(calendar.timegm(( Y % 10000, m % 100, d % 100, H % 100, M % 100, S % 100, 0, 0, 0) ))
def timestamp_YmdHMS(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an integer. Raises: ValueError: If timestamp is invalid. Note: The timezone is assumed to be UTC/GMT. """ i = int(value) S = i M = S//100 H = M//100 d = H//100 m = d//100 Y = m//100 return int(calendar.timegm(( Y % 10000, m % 100, d % 100, H % 100, M % 100, S % 100, 0, 0, 0) ))
[ "Convert", "timestamp", "string", "to", "time", "in", "seconds", "since", "epoch", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L160-L186
[ "def", "timestamp_YmdHMS", "(", "value", ")", ":", "i", "=", "int", "(", "value", ")", "S", "=", "i", "M", "=", "S", "//", "100", "H", "=", "M", "//", "100", "d", "=", "H", "//", "100", "m", "=", "d", "//", "100", "Y", "=", "m", "//", "100", "return", "int", "(", "calendar", ".", "timegm", "(", "(", "Y", "%", "10000", ",", "m", "%", "100", ",", "d", "%", "100", ",", "H", "%", "100", ",", "M", "%", "100", ",", "S", "%", "100", ",", "0", ",", "0", ",", "0", ")", ")", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
datetimeobj_YmdHMS
Convert timestamp string to a datetime object. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. Note: The timezone is assumed to be UTC/GMT.
nntp/date.py
def datetimeobj_YmdHMS(value): """Convert timestamp string to a datetime object. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. Note: The timezone is assumed to be UTC/GMT. """ i = int(value) S = i M = S//100 H = M//100 d = H//100 m = d//100 Y = m//100 return datetime.datetime( Y % 10000, m % 100, d % 100, H % 100, M % 100, S % 100, tzinfo=TZ_GMT )
def datetimeobj_YmdHMS(value): """Convert timestamp string to a datetime object. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. Note: The timezone is assumed to be UTC/GMT. """ i = int(value) S = i M = S//100 H = M//100 d = H//100 m = d//100 Y = m//100 return datetime.datetime( Y % 10000, m % 100, d % 100, H % 100, M % 100, S % 100, tzinfo=TZ_GMT )
[ "Convert", "timestamp", "string", "to", "a", "datetime", "object", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L188-L214
[ "def", "datetimeobj_YmdHMS", "(", "value", ")", ":", "i", "=", "int", "(", "value", ")", "S", "=", "i", "M", "=", "S", "//", "100", "H", "=", "M", "//", "100", "d", "=", "H", "//", "100", "m", "=", "d", "//", "100", "Y", "=", "m", "//", "100", "return", "datetime", ".", "datetime", "(", "Y", "%", "10000", ",", "m", "%", "100", ",", "d", "%", "100", ",", "H", "%", "100", ",", "M", "%", "100", ",", "S", "%", "100", ",", "tzinfo", "=", "TZ_GMT", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
datetimeobj_epoch
Convert timestamp string to a datetime object. Timestamps strings like '1383470155' are able to be converted by this function. Args: value: A timestamp string as seconds since epoch. Returns: A datetime object. Raises: ValueError: If timestamp is invalid.
nntp/date.py
def datetimeobj_epoch(value): """Convert timestamp string to a datetime object. Timestamps strings like '1383470155' are able to be converted by this function. Args: value: A timestamp string as seconds since epoch. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. """ return datetime.datetime.utcfromtimestamp(int(value)).replace(tzinfo=TZ_GMT)
def datetimeobj_epoch(value): """Convert timestamp string to a datetime object. Timestamps strings like '1383470155' are able to be converted by this function. Args: value: A timestamp string as seconds since epoch. Returns: A datetime object. Raises: ValueError: If timestamp is invalid. """ return datetime.datetime.utcfromtimestamp(int(value)).replace(tzinfo=TZ_GMT)
[ "Convert", "timestamp", "string", "to", "a", "datetime", "object", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L230-L245
[ "def", "datetimeobj_epoch", "(", "value", ")", ":", "return", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "int", "(", "value", ")", ")", ".", "replace", "(", "tzinfo", "=", "TZ_GMT", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
timestamp_fmt
Convert timestamp string to time in seconds since epoch. Wraps the datetime.datetime.strptime(). This is slow use the other timestamp_*() functions if possible. Args: value: A timestamp string. fmt: A timestamp format string. Returns: The time in seconds since epoch as an integer.
nntp/date.py
def timestamp_fmt(value, fmt): """Convert timestamp string to time in seconds since epoch. Wraps the datetime.datetime.strptime(). This is slow use the other timestamp_*() functions if possible. Args: value: A timestamp string. fmt: A timestamp format string. Returns: The time in seconds since epoch as an integer. """ return int(calendar.timegm( datetime.datetime.strptime(value, fmt).utctimetuple() ))
def timestamp_fmt(value, fmt): """Convert timestamp string to time in seconds since epoch. Wraps the datetime.datetime.strptime(). This is slow use the other timestamp_*() functions if possible. Args: value: A timestamp string. fmt: A timestamp format string. Returns: The time in seconds since epoch as an integer. """ return int(calendar.timegm( datetime.datetime.strptime(value, fmt).utctimetuple() ))
[ "Convert", "timestamp", "string", "to", "time", "in", "seconds", "since", "epoch", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L247-L262
[ "def", "timestamp_fmt", "(", "value", ",", "fmt", ")", ":", "return", "int", "(", "calendar", ".", "timegm", "(", "datetime", ".", "datetime", ".", "strptime", "(", "value", ",", "fmt", ")", ".", "utctimetuple", "(", ")", ")", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
timestamp_any
Convert timestamp string to time in seconds since epoch. Most timestamps strings are supported in fact this wraps the dateutil.parser.parse() method. This is SLOW use the other timestamp_*() functions if possible. Args: value: A timestamp string. Returns: The time in seconds since epoch as an integer.
nntp/date.py
def timestamp_any(value): """Convert timestamp string to time in seconds since epoch. Most timestamps strings are supported in fact this wraps the dateutil.parser.parse() method. This is SLOW use the other timestamp_*() functions if possible. Args: value: A timestamp string. Returns: The time in seconds since epoch as an integer. """ return int(calendar.timegm(dateutil.parser.parse(value).utctimetuple()))
def timestamp_any(value): """Convert timestamp string to time in seconds since epoch. Most timestamps strings are supported in fact this wraps the dateutil.parser.parse() method. This is SLOW use the other timestamp_*() functions if possible. Args: value: A timestamp string. Returns: The time in seconds since epoch as an integer. """ return int(calendar.timegm(dateutil.parser.parse(value).utctimetuple()))
[ "Convert", "timestamp", "string", "to", "time", "in", "seconds", "since", "epoch", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L279-L292
[ "def", "timestamp_any", "(", "value", ")", ":", "return", "int", "(", "calendar", ".", "timegm", "(", "dateutil", ".", "parser", ".", "parse", "(", "value", ")", ".", "utctimetuple", "(", ")", ")", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
timestamp
Parse a datetime to a unix timestamp. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other timestamp_*() functions for more details. Args: value: A string representing a datetime. fmt: A timestamp format string like for time.strptime(). Returns: The time in seconds since epoch as and integer for the value specified.
nntp/date.py
def timestamp(value, fmt=None): """Parse a datetime to a unix timestamp. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other timestamp_*() functions for more details. Args: value: A string representing a datetime. fmt: A timestamp format string like for time.strptime(). Returns: The time in seconds since epoch as and integer for the value specified. """ if fmt: return _timestamp_formats.get(fmt, lambda v: timestamp_fmt(v, fmt) )(value) l = len(value) if 19 <= l <= 24 and value[3] == " ": # '%d %b %Y %H:%M:%Sxxxx' try: return timestamp_d_b_Y_H_M_S(value) except (KeyError, ValueError, OverflowError): pass if 30 <= l <= 31: # '%a, %d %b %Y %H:%M:%S %z' try: return timestamp_a__d_b_Y_H_M_S_z(value) except (KeyError, ValueError, OverflowError): pass if l == 14: # '%Y%m%d%H%M%S' try: return timestamp_YmdHMS(value) except (ValueError, OverflowError): pass # epoch timestamp try: return timestamp_epoch(value) except ValueError: pass # slow version return timestamp_any(value)
def timestamp(value, fmt=None): """Parse a datetime to a unix timestamp. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other timestamp_*() functions for more details. Args: value: A string representing a datetime. fmt: A timestamp format string like for time.strptime(). Returns: The time in seconds since epoch as and integer for the value specified. """ if fmt: return _timestamp_formats.get(fmt, lambda v: timestamp_fmt(v, fmt) )(value) l = len(value) if 19 <= l <= 24 and value[3] == " ": # '%d %b %Y %H:%M:%Sxxxx' try: return timestamp_d_b_Y_H_M_S(value) except (KeyError, ValueError, OverflowError): pass if 30 <= l <= 31: # '%a, %d %b %Y %H:%M:%S %z' try: return timestamp_a__d_b_Y_H_M_S_z(value) except (KeyError, ValueError, OverflowError): pass if l == 14: # '%Y%m%d%H%M%S' try: return timestamp_YmdHMS(value) except (ValueError, OverflowError): pass # epoch timestamp try: return timestamp_epoch(value) except ValueError: pass # slow version return timestamp_any(value)
[ "Parse", "a", "datetime", "to", "a", "unix", "timestamp", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L316-L374
[ "def", "timestamp", "(", "value", ",", "fmt", "=", "None", ")", ":", "if", "fmt", ":", "return", "_timestamp_formats", ".", "get", "(", "fmt", ",", "lambda", "v", ":", "timestamp_fmt", "(", "v", ",", "fmt", ")", ")", "(", "value", ")", "l", "=", "len", "(", "value", ")", "if", "19", "<=", "l", "<=", "24", "and", "value", "[", "3", "]", "==", "\" \"", ":", "# '%d %b %Y %H:%M:%Sxxxx'", "try", ":", "return", "timestamp_d_b_Y_H_M_S", "(", "value", ")", "except", "(", "KeyError", ",", "ValueError", ",", "OverflowError", ")", ":", "pass", "if", "30", "<=", "l", "<=", "31", ":", "# '%a, %d %b %Y %H:%M:%S %z'", "try", ":", "return", "timestamp_a__d_b_Y_H_M_S_z", "(", "value", ")", "except", "(", "KeyError", ",", "ValueError", ",", "OverflowError", ")", ":", "pass", "if", "l", "==", "14", ":", "# '%Y%m%d%H%M%S'", "try", ":", "return", "timestamp_YmdHMS", "(", "value", ")", "except", "(", "ValueError", ",", "OverflowError", ")", ":", "pass", "# epoch timestamp", "try", ":", "return", "timestamp_epoch", "(", "value", ")", "except", "ValueError", ":", "pass", "# slow version", "return", "timestamp_any", "(", "value", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
datetimeobj
Parse a datetime to a datetime object. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other datetimeobj_*() functions for more details. Args: value: A string representing a datetime. Returns: A datetime object.
nntp/date.py
def datetimeobj(value, fmt=None): """Parse a datetime to a datetime object. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other datetimeobj_*() functions for more details. Args: value: A string representing a datetime. Returns: A datetime object. """ if fmt: return _datetimeobj_formats.get(fmt, lambda v: datetimeobj_fmt(v, fmt) )(value) l = len(value) if 19 <= l <= 24 and value[3] == " ": # '%d %b %Y %H:%M:%Sxxxx' try: return datetimeobj_d_b_Y_H_M_S(value) except (KeyError, ValueError): pass if 30 <= l <= 31: # '%a, %d %b %Y %H:%M:%S %z' try: return datetimeobj_a__d_b_Y_H_M_S_z(value) except (KeyError, ValueError): pass if l == 14: # '%Y%m%d%H%M%S' try: return datetimeobj_YmdHMS(value) except ValueError: pass # epoch timestamp try: return datetimeobj_epoch(value) except ValueError: pass # slow version return datetimeobj_any(value)
def datetimeobj(value, fmt=None): """Parse a datetime to a datetime object. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other datetimeobj_*() functions for more details. Args: value: A string representing a datetime. Returns: A datetime object. """ if fmt: return _datetimeobj_formats.get(fmt, lambda v: datetimeobj_fmt(v, fmt) )(value) l = len(value) if 19 <= l <= 24 and value[3] == " ": # '%d %b %Y %H:%M:%Sxxxx' try: return datetimeobj_d_b_Y_H_M_S(value) except (KeyError, ValueError): pass if 30 <= l <= 31: # '%a, %d %b %Y %H:%M:%S %z' try: return datetimeobj_a__d_b_Y_H_M_S_z(value) except (KeyError, ValueError): pass if l == 14: # '%Y%m%d%H%M%S' try: return datetimeobj_YmdHMS(value) except ValueError: pass # epoch timestamp try: return datetimeobj_epoch(value) except ValueError: pass # slow version return datetimeobj_any(value)
[ "Parse", "a", "datetime", "to", "a", "datetime", "object", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/date.py#L383-L440
[ "def", "datetimeobj", "(", "value", ",", "fmt", "=", "None", ")", ":", "if", "fmt", ":", "return", "_datetimeobj_formats", ".", "get", "(", "fmt", ",", "lambda", "v", ":", "datetimeobj_fmt", "(", "v", ",", "fmt", ")", ")", "(", "value", ")", "l", "=", "len", "(", "value", ")", "if", "19", "<=", "l", "<=", "24", "and", "value", "[", "3", "]", "==", "\" \"", ":", "# '%d %b %Y %H:%M:%Sxxxx'", "try", ":", "return", "datetimeobj_d_b_Y_H_M_S", "(", "value", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "pass", "if", "30", "<=", "l", "<=", "31", ":", "# '%a, %d %b %Y %H:%M:%S %z'", "try", ":", "return", "datetimeobj_a__d_b_Y_H_M_S_z", "(", "value", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "pass", "if", "l", "==", "14", ":", "# '%Y%m%d%H%M%S'", "try", ":", "return", "datetimeobj_YmdHMS", "(", "value", ")", "except", "ValueError", ":", "pass", "# epoch timestamp", "try", ":", "return", "datetimeobj_epoch", "(", "value", ")", "except", "ValueError", ":", "pass", "# slow version", "return", "datetimeobj_any", "(", "value", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
AlertReportConfig._fix_alert_config_dict
Fix the alert config .args() dict for the correct key name
logentries_api/special_alerts.py
def _fix_alert_config_dict(alert_config): """ Fix the alert config .args() dict for the correct key name """ data = alert_config.args() data['params_set'] = data.get('args') del data['args'] return data
def _fix_alert_config_dict(alert_config): """ Fix the alert config .args() dict for the correct key name """ data = alert_config.args() data['params_set'] = data.get('args') del data['args'] return data
[ "Fix", "the", "alert", "config", ".", "args", "()", "dict", "for", "the", "correct", "key", "name" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L165-L172
[ "def", "_fix_alert_config_dict", "(", "alert_config", ")", ":", "data", "=", "alert_config", ".", "args", "(", ")", "data", "[", "'params_set'", "]", "=", "data", ".", "get", "(", "'args'", ")", "del", "data", "[", "'args'", "]", "return", "data" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
SpecialAlertBase._get_login_payload
returns the payload the login page expects :rtype: dict
logentries_api/special_alerts.py
def _get_login_payload(self, username, password): """ returns the payload the login page expects :rtype: dict """ payload = { 'csrfmiddlewaretoken': self._get_csrf_token(), 'ajax': '1', 'next': '/app/', 'username': username, 'password': password } return payload
def _get_login_payload(self, username, password): """ returns the payload the login page expects :rtype: dict """ payload = { 'csrfmiddlewaretoken': self._get_csrf_token(), 'ajax': '1', 'next': '/app/', 'username': username, 'password': password } return payload
[ "returns", "the", "payload", "the", "login", "page", "expects", ":", "rtype", ":", "dict" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L246-L258
[ "def", "_get_login_payload", "(", "self", ",", "username", ",", "password", ")", ":", "payload", "=", "{", "'csrfmiddlewaretoken'", ":", "self", ".", "_get_csrf_token", "(", ")", ",", "'ajax'", ":", "'1'", ",", "'next'", ":", "'/app/'", ",", "'username'", ":", "username", ",", "'password'", ":", "password", "}", "return", "payload" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
SpecialAlertBase._api_post
Convenience method for posting
logentries_api/special_alerts.py
def _api_post(self, url, **kwargs): """ Convenience method for posting """ response = self.session.post( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response.json()
def _api_post(self, url, **kwargs): """ Convenience method for posting """ response = self.session.post( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response.json()
[ "Convenience", "method", "for", "posting" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L274-L289
[ "def", "_api_post", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "session", ".", "post", "(", "url", "=", "url", ",", "headers", "=", "self", ".", "_get_api_headers", "(", ")", ",", "*", "*", "kwargs", ")", "if", "not", "response", ".", "ok", ":", "raise", "ServerException", "(", "'{0}: {1}'", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "text", "or", "response", ".", "reason", ")", ")", "return", "response", ".", "json", "(", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
SpecialAlertBase._api_delete
Convenience method for deleting
logentries_api/special_alerts.py
def _api_delete(self, url, **kwargs): """ Convenience method for deleting """ response = self.session.delete( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response
def _api_delete(self, url, **kwargs): """ Convenience method for deleting """ response = self.session.delete( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response
[ "Convenience", "method", "for", "deleting" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L291-L306
[ "def", "_api_delete", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "session", ".", "delete", "(", "url", "=", "url", ",", "headers", "=", "self", ".", "_get_api_headers", "(", ")", ",", "*", "*", "kwargs", ")", "if", "not", "response", ".", "ok", ":", "raise", "ServerException", "(", "'{0}: {1}'", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "text", "or", "response", ".", "reason", ")", ")", "return", "response" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
SpecialAlertBase._api_get
Convenience method for getting
logentries_api/special_alerts.py
def _api_get(self, url, **kwargs): """ Convenience method for getting """ response = self.session.get( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response.json()
def _api_get(self, url, **kwargs): """ Convenience method for getting """ response = self.session.get( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response.json()
[ "Convenience", "method", "for", "getting" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L308-L323
[ "def", "_api_get", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "session", ".", "get", "(", "url", "=", "url", ",", "headers", "=", "self", ".", "_get_api_headers", "(", ")", ",", "*", "*", "kwargs", ")", "if", "not", "response", ".", "ok", ":", "raise", "ServerException", "(", "'{0}: {1}'", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "text", "or", "response", ".", "reason", ")", ")", "return", "response", ".", "json", "(", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
SpecialAlertBase._login
._login() makes three requests: * One to the /login/ page to get a CSRF cookie * One to /login/ajax/ to get a logged-in session cookie * One to /app/ to get the beginning of the account id :param username: A valid username (email) :type username: str :param password: A valid password :type password: str :return: The account's url id :rtype: str
logentries_api/special_alerts.py
def _login(self, username, password): """ ._login() makes three requests: * One to the /login/ page to get a CSRF cookie * One to /login/ajax/ to get a logged-in session cookie * One to /app/ to get the beginning of the account id :param username: A valid username (email) :type username: str :param password: A valid password :type password: str :return: The account's url id :rtype: str """ login_url = 'https://logentries.com/login/' login_page_response = self.session.get(url=login_url, headers=self.default_headers) if not login_page_response.ok: raise ServerException(login_page_response.text) login_headers = { 'Referer': login_url, 'X-Requested-With': 'XMLHttpRequest', } login_headers.update(self.default_headers) login_response = self.session.post( 'https://logentries.com/login/ajax/', headers=login_headers, data=self._get_login_payload( username, password), ) if not login_response.ok: raise ServerException(login_response.text) app_response = self.session.get('https://logentries.com/app/', headers=self.default_headers) return app_response.url.split('/')[-1]
def _login(self, username, password): """ ._login() makes three requests: * One to the /login/ page to get a CSRF cookie * One to /login/ajax/ to get a logged-in session cookie * One to /app/ to get the beginning of the account id :param username: A valid username (email) :type username: str :param password: A valid password :type password: str :return: The account's url id :rtype: str """ login_url = 'https://logentries.com/login/' login_page_response = self.session.get(url=login_url, headers=self.default_headers) if not login_page_response.ok: raise ServerException(login_page_response.text) login_headers = { 'Referer': login_url, 'X-Requested-With': 'XMLHttpRequest', } login_headers.update(self.default_headers) login_response = self.session.post( 'https://logentries.com/login/ajax/', headers=login_headers, data=self._get_login_payload( username, password), ) if not login_response.ok: raise ServerException(login_response.text) app_response = self.session.get('https://logentries.com/app/', headers=self.default_headers) return app_response.url.split('/')[-1]
[ ".", "_login", "()", "makes", "three", "requests", ":" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L325-L362
[ "def", "_login", "(", "self", ",", "username", ",", "password", ")", ":", "login_url", "=", "'https://logentries.com/login/'", "login_page_response", "=", "self", ".", "session", ".", "get", "(", "url", "=", "login_url", ",", "headers", "=", "self", ".", "default_headers", ")", "if", "not", "login_page_response", ".", "ok", ":", "raise", "ServerException", "(", "login_page_response", ".", "text", ")", "login_headers", "=", "{", "'Referer'", ":", "login_url", ",", "'X-Requested-With'", ":", "'XMLHttpRequest'", ",", "}", "login_headers", ".", "update", "(", "self", ".", "default_headers", ")", "login_response", "=", "self", ".", "session", ".", "post", "(", "'https://logentries.com/login/ajax/'", ",", "headers", "=", "login_headers", ",", "data", "=", "self", ".", "_get_login_payload", "(", "username", ",", "password", ")", ",", ")", "if", "not", "login_response", ".", "ok", ":", "raise", "ServerException", "(", "login_response", ".", "text", ")", "app_response", "=", "self", ".", "session", ".", "get", "(", "'https://logentries.com/app/'", ",", "headers", "=", "self", ".", "default_headers", ")", "return", "app_response", ".", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
SpecialAlertBase.list_scheduled_queries
List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries
logentries_api/special_alerts.py
def list_scheduled_queries(self): """ List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries/'.format( account_id=self.account_id) return self._api_get(url=url).get('scheduled_searches')
def list_scheduled_queries(self): """ List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries/'.format( account_id=self.account_id) return self._api_get(url=url).get('scheduled_searches')
[ "List", "all", "scheduled_queries" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L364-L377
[ "def", "list_scheduled_queries", "(", "self", ")", ":", "url", "=", "'https://logentries.com/rest/{account_id}/api/scheduled_queries/'", ".", "format", "(", "account_id", "=", "self", ".", "account_id", ")", "return", "self", ".", "_api_get", "(", "url", "=", "url", ")", ".", "get", "(", "'scheduled_searches'", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
SpecialAlertBase.list_tags
List all tags for the account. The response differs from ``Hooks().list()``, in that tag dicts for anomaly alerts include a 'scheduled_query_id' key with the value being the UUID for the associated scheduled query :return: A list of all tag dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries
logentries_api/special_alerts.py
def list_tags(self): """ List all tags for the account. The response differs from ``Hooks().list()``, in that tag dicts for anomaly alerts include a 'scheduled_query_id' key with the value being the UUID for the associated scheduled query :return: A list of all tag dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ url = 'https://logentries.com/rest/{account_id}/api/tags/'.format( account_id=self.account_id) return self._api_get(url=url).get('tags')
def list_tags(self): """ List all tags for the account. The response differs from ``Hooks().list()``, in that tag dicts for anomaly alerts include a 'scheduled_query_id' key with the value being the UUID for the associated scheduled query :return: A list of all tag dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ url = 'https://logentries.com/rest/{account_id}/api/tags/'.format( account_id=self.account_id) return self._api_get(url=url).get('tags')
[ "List", "all", "tags", "for", "the", "account", "." ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L379-L396
[ "def", "list_tags", "(", "self", ")", ":", "url", "=", "'https://logentries.com/rest/{account_id}/api/tags/'", ".", "format", "(", "account_id", "=", "self", ".", "account_id", ")", "return", "self", ".", "_api_get", "(", "url", "=", "url", ")", ".", "get", "(", "'tags'", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
SpecialAlertBase.get
Get alert by name or id :param name_or_id: The alert's name or id :type name_or_id: str :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries
logentries_api/special_alerts.py
def get(self, name_or_id): """ Get alert by name or id :param name_or_id: The alert's name or id :type name_or_id: str :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ return [ tag for tag in self.list_tags() if name_or_id == tag.get('id') or name_or_id == tag.get('name') ]
def get(self, name_or_id): """ Get alert by name or id :param name_or_id: The alert's name or id :type name_or_id: str :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ return [ tag for tag in self.list_tags() if name_or_id == tag.get('id') or name_or_id == tag.get('name') ]
[ "Get", "alert", "by", "name", "or", "id" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L398-L419
[ "def", "get", "(", "self", ",", "name_or_id", ")", ":", "return", "[", "tag", "for", "tag", "in", "self", ".", "list_tags", "(", ")", "if", "name_or_id", "==", "tag", ".", "get", "(", "'id'", ")", "or", "name_or_id", "==", "tag", ".", "get", "(", "'name'", ")", "]" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
InactivityAlert.create
Create an inactivity alert :param name: A name for the inactivity alert :type name: str :param patterns: A list of regexes to match :type patterns: list of str :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param trigger_config: A AlertTriggerConfig describing how far back to look for inactivity. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param alert_reports: A list of AlertReportConfigs to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response :rtype: dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries
logentries_api/special_alerts.py
def create(self, name, patterns, logs, trigger_config, alert_reports): """ Create an inactivity alert :param name: A name for the inactivity alert :type name: str :param patterns: A list of regexes to match :type patterns: list of str :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param trigger_config: A AlertTriggerConfig describing how far back to look for inactivity. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param alert_reports: A list of AlertReportConfigs to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response :rtype: dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ data = { 'tag': { 'actions': [ alert_report.to_dict() for alert_report in alert_reports ], 'name': name, 'patterns': patterns, 'sources': [ {'id': log} for log in logs ], 'sub_type': 'InactivityAlert', 'type': 'AlertNotify' } } data['tag'].update(trigger_config.to_dict()) return self._api_post( url=self.url_template.format(account_id=self.account_id), data=json.dumps(data, sort_keys=True) )
def create(self, name, patterns, logs, trigger_config, alert_reports): """ Create an inactivity alert :param name: A name for the inactivity alert :type name: str :param patterns: A list of regexes to match :type patterns: list of str :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param trigger_config: A AlertTriggerConfig describing how far back to look for inactivity. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param alert_reports: A list of AlertReportConfigs to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response :rtype: dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ data = { 'tag': { 'actions': [ alert_report.to_dict() for alert_report in alert_reports ], 'name': name, 'patterns': patterns, 'sources': [ {'id': log} for log in logs ], 'sub_type': 'InactivityAlert', 'type': 'AlertNotify' } } data['tag'].update(trigger_config.to_dict()) return self._api_post( url=self.url_template.format(account_id=self.account_id), data=json.dumps(data, sort_keys=True) )
[ "Create", "an", "inactivity", "alert" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L429-L480
[ "def", "create", "(", "self", ",", "name", ",", "patterns", ",", "logs", ",", "trigger_config", ",", "alert_reports", ")", ":", "data", "=", "{", "'tag'", ":", "{", "'actions'", ":", "[", "alert_report", ".", "to_dict", "(", ")", "for", "alert_report", "in", "alert_reports", "]", ",", "'name'", ":", "name", ",", "'patterns'", ":", "patterns", ",", "'sources'", ":", "[", "{", "'id'", ":", "log", "}", "for", "log", "in", "logs", "]", ",", "'sub_type'", ":", "'InactivityAlert'", ",", "'type'", ":", "'AlertNotify'", "}", "}", "data", "[", "'tag'", "]", ".", "update", "(", "trigger_config", ".", "to_dict", "(", ")", ")", "return", "self", ".", "_api_post", "(", "url", "=", "self", ".", "url_template", ".", "format", "(", "account_id", "=", "self", ".", "account_id", ")", ",", "data", "=", "json", ".", "dumps", "(", "data", ",", "sort_keys", "=", "True", ")", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
InactivityAlert.delete
Delete the specified InactivityAlert :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries
logentries_api/special_alerts.py
def delete(self, tag_id): """ Delete the specified InactivityAlert :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries """ tag_url = 'https://logentries.com/rest/{account_id}/api/tags/{tag_id}' self._api_delete( url=tag_url.format( account_id=self.account_id, tag_id=tag_id ) )
def delete(self, tag_id): """ Delete the specified InactivityAlert :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries """ tag_url = 'https://logentries.com/rest/{account_id}/api/tags/{tag_id}' self._api_delete( url=tag_url.format( account_id=self.account_id, tag_id=tag_id ) )
[ "Delete", "the", "specified", "InactivityAlert" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L482-L500
[ "def", "delete", "(", "self", ",", "tag_id", ")", ":", "tag_url", "=", "'https://logentries.com/rest/{account_id}/api/tags/{tag_id}'", "self", ".", "_api_delete", "(", "url", "=", "tag_url", ".", "format", "(", "account_id", "=", "self", ".", "account_id", ",", "tag_id", "=", "tag_id", ")", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
AnomalyAlert._create_scheduled_query
Create the scheduled query
logentries_api/special_alerts.py
def _create_scheduled_query(self, query, change, scope_unit, scope_count): """ Create the scheduled query """ query_data = { 'scheduled_query': { 'name': 'ForAnomalyReport', 'query': query, 'threshold_type': '%', 'threshold_value': change, 'time_period': scope_unit.title(), 'time_value': scope_count, } } query_url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries' return self._api_post( url=query_url.format(account_id=self.account_id), data=json.dumps(query_data, sort_keys=True) )
def _create_scheduled_query(self, query, change, scope_unit, scope_count): """ Create the scheduled query """ query_data = { 'scheduled_query': { 'name': 'ForAnomalyReport', 'query': query, 'threshold_type': '%', 'threshold_value': change, 'time_period': scope_unit.title(), 'time_value': scope_count, } } query_url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries' return self._api_post( url=query_url.format(account_id=self.account_id), data=json.dumps(query_data, sort_keys=True) )
[ "Create", "the", "scheduled", "query" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L508-L528
[ "def", "_create_scheduled_query", "(", "self", ",", "query", ",", "change", ",", "scope_unit", ",", "scope_count", ")", ":", "query_data", "=", "{", "'scheduled_query'", ":", "{", "'name'", ":", "'ForAnomalyReport'", ",", "'query'", ":", "query", ",", "'threshold_type'", ":", "'%'", ",", "'threshold_value'", ":", "change", ",", "'time_period'", ":", "scope_unit", ".", "title", "(", ")", ",", "'time_value'", ":", "scope_count", ",", "}", "}", "query_url", "=", "'https://logentries.com/rest/{account_id}/api/scheduled_queries'", "return", "self", ".", "_api_post", "(", "url", "=", "query_url", ".", "format", "(", "account_id", "=", "self", ".", "account_id", ")", ",", "data", "=", "json", ".", "dumps", "(", "query_data", ",", "sort_keys", "=", "True", ")", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
AnomalyAlert.create
Create an anomaly alert. This call makes 2 requests, one to create a "scheduled_query", and another to create the alert. :param name: The name for the alert :type name: str :param query: The `LEQL`_ query to use for detecting anomalies. Must result in a numerical value, so it should look something like ``where(...) calculate(COUNT)`` :type query: str :param scope_count: How many ``scope_unit`` s to inspect for detecting an anomaly :type scope_count: int :param scope_unit: How far to look back in detecting an anomaly. Must be one of "hour", "day", or "week" :type scope_unit: str :param increase_positive: Detect a positive increase for the anomaly. A value of ``False`` results in detecting a decrease for the anomaly. :type increase_positive: bool :param percentage_change: The percentage of change to detect. Must be a number between 0 and 100 (inclusive). :type percentage_change: int :param trigger_config: A AlertTriggerConfig describing how far back to look back to compare to the anomaly scope. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param alert_reports: A list of AlertReportConfig to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response of the alert creation :rtype: dict :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries .. _Leql: https://blog.logentries.com/2015/06/introducing-leql/
logentries_api/special_alerts.py
def create(self, name, query, scope_count, scope_unit, increase_positive, percentage_change, trigger_config, logs, alert_reports): """ Create an anomaly alert. This call makes 2 requests, one to create a "scheduled_query", and another to create the alert. :param name: The name for the alert :type name: str :param query: The `LEQL`_ query to use for detecting anomalies. Must result in a numerical value, so it should look something like ``where(...) calculate(COUNT)`` :type query: str :param scope_count: How many ``scope_unit`` s to inspect for detecting an anomaly :type scope_count: int :param scope_unit: How far to look back in detecting an anomaly. Must be one of "hour", "day", or "week" :type scope_unit: str :param increase_positive: Detect a positive increase for the anomaly. A value of ``False`` results in detecting a decrease for the anomaly. :type increase_positive: bool :param percentage_change: The percentage of change to detect. Must be a number between 0 and 100 (inclusive). :type percentage_change: int :param trigger_config: A AlertTriggerConfig describing how far back to look back to compare to the anomaly scope. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param alert_reports: A list of AlertReportConfig to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response of the alert creation :rtype: dict :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries .. _Leql: https://blog.logentries.com/2015/06/introducing-leql/ """ change = '{pos}{change}'.format( pos='+' if increase_positive else '-', change=str(percentage_change) ) query_response = self._create_scheduled_query( query=query, change=change, scope_unit=scope_unit, scope_count=scope_count, ) scheduled_query_id = query_response.get('scheduled_query', {}).get('id') tag_data = { 'tag': { 'actions': [ alert_report.to_dict() for alert_report in alert_reports ], 'name': name, 'scheduled_query_id': scheduled_query_id, 'sources': [ {'id': log} for log in logs ], 'sub_type': 'AnomalyAlert', 'type': 'AlertNotify' } } tag_data['tag'].update(trigger_config.to_dict()) tag_url = 'https://logentries.com/rest/{account_id}/api/tags'.format( account_id=self.account_id ) return self._api_post( url=tag_url, data=json.dumps(tag_data, sort_keys=True), )
def create(self, name, query, scope_count, scope_unit, increase_positive, percentage_change, trigger_config, logs, alert_reports): """ Create an anomaly alert. This call makes 2 requests, one to create a "scheduled_query", and another to create the alert. :param name: The name for the alert :type name: str :param query: The `LEQL`_ query to use for detecting anomalies. Must result in a numerical value, so it should look something like ``where(...) calculate(COUNT)`` :type query: str :param scope_count: How many ``scope_unit`` s to inspect for detecting an anomaly :type scope_count: int :param scope_unit: How far to look back in detecting an anomaly. Must be one of "hour", "day", or "week" :type scope_unit: str :param increase_positive: Detect a positive increase for the anomaly. A value of ``False`` results in detecting a decrease for the anomaly. :type increase_positive: bool :param percentage_change: The percentage of change to detect. Must be a number between 0 and 100 (inclusive). :type percentage_change: int :param trigger_config: A AlertTriggerConfig describing how far back to look back to compare to the anomaly scope. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param alert_reports: A list of AlertReportConfig to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response of the alert creation :rtype: dict :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries .. _Leql: https://blog.logentries.com/2015/06/introducing-leql/ """ change = '{pos}{change}'.format( pos='+' if increase_positive else '-', change=str(percentage_change) ) query_response = self._create_scheduled_query( query=query, change=change, scope_unit=scope_unit, scope_count=scope_count, ) scheduled_query_id = query_response.get('scheduled_query', {}).get('id') tag_data = { 'tag': { 'actions': [ alert_report.to_dict() for alert_report in alert_reports ], 'name': name, 'scheduled_query_id': scheduled_query_id, 'sources': [ {'id': log} for log in logs ], 'sub_type': 'AnomalyAlert', 'type': 'AlertNotify' } } tag_data['tag'].update(trigger_config.to_dict()) tag_url = 'https://logentries.com/rest/{account_id}/api/tags'.format( account_id=self.account_id ) return self._api_post( url=tag_url, data=json.dumps(tag_data, sort_keys=True), )
[ "Create", "an", "anomaly", "alert", ".", "This", "call", "makes", "2", "requests", "one", "to", "create", "a", "scheduled_query", "and", "another", "to", "create", "the", "alert", "." ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L530-L630
[ "def", "create", "(", "self", ",", "name", ",", "query", ",", "scope_count", ",", "scope_unit", ",", "increase_positive", ",", "percentage_change", ",", "trigger_config", ",", "logs", ",", "alert_reports", ")", ":", "change", "=", "'{pos}{change}'", ".", "format", "(", "pos", "=", "'+'", "if", "increase_positive", "else", "'-'", ",", "change", "=", "str", "(", "percentage_change", ")", ")", "query_response", "=", "self", ".", "_create_scheduled_query", "(", "query", "=", "query", ",", "change", "=", "change", ",", "scope_unit", "=", "scope_unit", ",", "scope_count", "=", "scope_count", ",", ")", "scheduled_query_id", "=", "query_response", ".", "get", "(", "'scheduled_query'", ",", "{", "}", ")", ".", "get", "(", "'id'", ")", "tag_data", "=", "{", "'tag'", ":", "{", "'actions'", ":", "[", "alert_report", ".", "to_dict", "(", ")", "for", "alert_report", "in", "alert_reports", "]", ",", "'name'", ":", "name", ",", "'scheduled_query_id'", ":", "scheduled_query_id", ",", "'sources'", ":", "[", "{", "'id'", ":", "log", "}", "for", "log", "in", "logs", "]", ",", "'sub_type'", ":", "'AnomalyAlert'", ",", "'type'", ":", "'AlertNotify'", "}", "}", "tag_data", "[", "'tag'", "]", ".", "update", "(", "trigger_config", ".", "to_dict", "(", ")", ")", "tag_url", "=", "'https://logentries.com/rest/{account_id}/api/tags'", ".", "format", "(", "account_id", "=", "self", ".", "account_id", ")", "return", "self", ".", "_api_post", "(", "url", "=", "tag_url", ",", "data", "=", "json", ".", "dumps", "(", "tag_data", ",", "sort_keys", "=", "True", ")", ",", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
AnomalyAlert.delete
Delete a specified anomaly alert tag and its scheduled query This method makes 3 requests: * One to get the associated scheduled_query_id * One to delete the alert * One to delete get scheduled query :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries
logentries_api/special_alerts.py
def delete(self, tag_id): """ Delete a specified anomaly alert tag and its scheduled query This method makes 3 requests: * One to get the associated scheduled_query_id * One to delete the alert * One to delete get scheduled query :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries """ this_alert = [tag for tag in self.list_tags() if tag.get('id') == tag_id] if len(this_alert) < 1: return query_id = this_alert[0].get('scheduled_query_id') tag_url = 'https://logentries.com/rest/{account_id}/api/tags/{tag_id}' self._api_delete( url=tag_url.format( account_id=self.account_id, tag_id=tag_id ) ) query_url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries/{query_id}' self._api_delete( url=query_url.format( account_id=self.account_id, query_id=query_id ) )
def delete(self, tag_id): """ Delete a specified anomaly alert tag and its scheduled query This method makes 3 requests: * One to get the associated scheduled_query_id * One to delete the alert * One to delete get scheduled query :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries """ this_alert = [tag for tag in self.list_tags() if tag.get('id') == tag_id] if len(this_alert) < 1: return query_id = this_alert[0].get('scheduled_query_id') tag_url = 'https://logentries.com/rest/{account_id}/api/tags/{tag_id}' self._api_delete( url=tag_url.format( account_id=self.account_id, tag_id=tag_id ) ) query_url = 'https://logentries.com/rest/{account_id}/api/scheduled_queries/{query_id}' self._api_delete( url=query_url.format( account_id=self.account_id, query_id=query_id ) )
[ "Delete", "a", "specified", "anomaly", "alert", "tag", "and", "its", "scheduled", "query" ]
ambitioninc/python-logentries-api
python
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L632-L671
[ "def", "delete", "(", "self", ",", "tag_id", ")", ":", "this_alert", "=", "[", "tag", "for", "tag", "in", "self", ".", "list_tags", "(", ")", "if", "tag", ".", "get", "(", "'id'", ")", "==", "tag_id", "]", "if", "len", "(", "this_alert", ")", "<", "1", ":", "return", "query_id", "=", "this_alert", "[", "0", "]", ".", "get", "(", "'scheduled_query_id'", ")", "tag_url", "=", "'https://logentries.com/rest/{account_id}/api/tags/{tag_id}'", "self", ".", "_api_delete", "(", "url", "=", "tag_url", ".", "format", "(", "account_id", "=", "self", ".", "account_id", ",", "tag_id", "=", "tag_id", ")", ")", "query_url", "=", "'https://logentries.com/rest/{account_id}/api/scheduled_queries/{query_id}'", "self", ".", "_api_delete", "(", "url", "=", "query_url", ".", "format", "(", "account_id", "=", "self", ".", "account_id", ",", "query_id", "=", "query_id", ")", ")" ]
77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc
test
unparse_range
Unparse a range argument. Args: obj: An article range. There are a number of valid formats; an integer specifying a single article or a tuple specifying an article range. If the range doesn't give a start article then all articles up to the specified last article are included. If the range doesn't specify a last article then all articles from the first specified article up to the current last article for the group are included. Returns: The range as a string that can be used by an NNTP command. Note: Sample valid formats. 4678 (,5234) (4245,) (4245, 5234)
nntp/utils.py
def unparse_range(obj): """Unparse a range argument. Args: obj: An article range. There are a number of valid formats; an integer specifying a single article or a tuple specifying an article range. If the range doesn't give a start article then all articles up to the specified last article are included. If the range doesn't specify a last article then all articles from the first specified article up to the current last article for the group are included. Returns: The range as a string that can be used by an NNTP command. Note: Sample valid formats. 4678 (,5234) (4245,) (4245, 5234) """ if isinstance(obj, (int, long)): return str(obj) if isinstance(obj, tuple): arg = str(obj[0]) + "-" if len(obj) > 1: arg += str(obj[1]) return arg raise ValueError("Must be an integer or tuple")
def unparse_range(obj): """Unparse a range argument. Args: obj: An article range. There are a number of valid formats; an integer specifying a single article or a tuple specifying an article range. If the range doesn't give a start article then all articles up to the specified last article are included. If the range doesn't specify a last article then all articles from the first specified article up to the current last article for the group are included. Returns: The range as a string that can be used by an NNTP command. Note: Sample valid formats. 4678 (,5234) (4245,) (4245, 5234) """ if isinstance(obj, (int, long)): return str(obj) if isinstance(obj, tuple): arg = str(obj[0]) + "-" if len(obj) > 1: arg += str(obj[1]) return arg raise ValueError("Must be an integer or tuple")
[ "Unparse", "a", "range", "argument", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/utils.py#L49-L78
[ "def", "unparse_range", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "int", ",", "long", ")", ")", ":", "return", "str", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "tuple", ")", ":", "arg", "=", "str", "(", "obj", "[", "0", "]", ")", "+", "\"-\"", "if", "len", "(", "obj", ")", ">", "1", ":", "arg", "+=", "str", "(", "obj", "[", "1", "]", ")", "return", "arg", "raise", "ValueError", "(", "\"Must be an integer or tuple\"", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
parse_newsgroup
Parse a newsgroup info line to python types. Args: line: An info response line containing newsgroup info. Returns: A tuple of group name, low-water as integer, high-water as integer and posting status. Raises: ValueError: If the newsgroup info cannot be parsed. Note: Posting status is a character is one of (but not limited to): "y" posting allowed "n" posting not allowed "m" posting is moderated
nntp/utils.py
def parse_newsgroup(line): """Parse a newsgroup info line to python types. Args: line: An info response line containing newsgroup info. Returns: A tuple of group name, low-water as integer, high-water as integer and posting status. Raises: ValueError: If the newsgroup info cannot be parsed. Note: Posting status is a character is one of (but not limited to): "y" posting allowed "n" posting not allowed "m" posting is moderated """ parts = line.split() try: group = parts[0] low = int(parts[1]) high = int(parts[2]) status = parts[3] except (IndexError, ValueError): raise ValueError("Invalid newsgroup info") return group, low, high, status
def parse_newsgroup(line): """Parse a newsgroup info line to python types. Args: line: An info response line containing newsgroup info. Returns: A tuple of group name, low-water as integer, high-water as integer and posting status. Raises: ValueError: If the newsgroup info cannot be parsed. Note: Posting status is a character is one of (but not limited to): "y" posting allowed "n" posting not allowed "m" posting is moderated """ parts = line.split() try: group = parts[0] low = int(parts[1]) high = int(parts[2]) status = parts[3] except (IndexError, ValueError): raise ValueError("Invalid newsgroup info") return group, low, high, status
[ "Parse", "a", "newsgroup", "info", "line", "to", "python", "types", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/utils.py#L128-L155
[ "def", "parse_newsgroup", "(", "line", ")", ":", "parts", "=", "line", ".", "split", "(", ")", "try", ":", "group", "=", "parts", "[", "0", "]", "low", "=", "int", "(", "parts", "[", "1", "]", ")", "high", "=", "int", "(", "parts", "[", "2", "]", ")", "status", "=", "parts", "[", "3", "]", "except", "(", "IndexError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "\"Invalid newsgroup info\"", ")", "return", "group", ",", "low", ",", "high", ",", "status" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
parse_header
Parse a header line. Args: line: A header line as a string. Returns: None if end of headers is found. A string giving the continuation line if a continuation is found. A tuple of name, value when a header line is found. Raises: ValueError: If the line cannot be parsed as a header.
nntp/utils.py
def parse_header(line): """Parse a header line. Args: line: A header line as a string. Returns: None if end of headers is found. A string giving the continuation line if a continuation is found. A tuple of name, value when a header line is found. Raises: ValueError: If the line cannot be parsed as a header. """ if not line or line == "\r\n": return None if line[0] in " \t": return line[1:].rstrip() name, value = line.split(":", 1) return (name.strip(), value.strip())
def parse_header(line): """Parse a header line. Args: line: A header line as a string. Returns: None if end of headers is found. A string giving the continuation line if a continuation is found. A tuple of name, value when a header line is found. Raises: ValueError: If the line cannot be parsed as a header. """ if not line or line == "\r\n": return None if line[0] in " \t": return line[1:].rstrip() name, value = line.split(":", 1) return (name.strip(), value.strip())
[ "Parse", "a", "header", "line", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/utils.py#L157-L176
[ "def", "parse_header", "(", "line", ")", ":", "if", "not", "line", "or", "line", "==", "\"\\r\\n\"", ":", "return", "None", "if", "line", "[", "0", "]", "in", "\" \\t\"", ":", "return", "line", "[", "1", ":", "]", ".", "rstrip", "(", ")", "name", ",", "value", "=", "line", ".", "split", "(", "\":\"", ",", "1", ")", "return", "(", "name", ".", "strip", "(", ")", ",", "value", ".", "strip", "(", ")", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
parse_headers
Parse a string a iterable object (including file like objects) to a python dictionary. Args: obj: An iterable object including file-like objects. Returns: An dictionary of headers. If a header is repeated then the last value for that header is given. Raises: ValueError: If the first line is a continuation line or the headers cannot be parsed.
nntp/utils.py
def parse_headers(obj): """Parse a string a iterable object (including file like objects) to a python dictionary. Args: obj: An iterable object including file-like objects. Returns: An dictionary of headers. If a header is repeated then the last value for that header is given. Raises: ValueError: If the first line is a continuation line or the headers cannot be parsed. """ if isinstance(obj, basestring): obj = cStringIO.StringIO(obj) hdrs = [] for line in obj: hdr = parse_header(line) if not hdr: break if isinstance(hdr, basestring): if not hdrs: raise ValueError("First header is a continuation") hdrs[-1] = (hdrs[-1][0], hdrs[-1][1] + hdr) continue hdrs.append(hdr) return iodict.IODict(hdrs)
def parse_headers(obj): """Parse a string a iterable object (including file like objects) to a python dictionary. Args: obj: An iterable object including file-like objects. Returns: An dictionary of headers. If a header is repeated then the last value for that header is given. Raises: ValueError: If the first line is a continuation line or the headers cannot be parsed. """ if isinstance(obj, basestring): obj = cStringIO.StringIO(obj) hdrs = [] for line in obj: hdr = parse_header(line) if not hdr: break if isinstance(hdr, basestring): if not hdrs: raise ValueError("First header is a continuation") hdrs[-1] = (hdrs[-1][0], hdrs[-1][1] + hdr) continue hdrs.append(hdr) return iodict.IODict(hdrs)
[ "Parse", "a", "string", "a", "iterable", "object", "(", "including", "file", "like", "objects", ")", "to", "a", "python", "dictionary", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/utils.py#L178-L206
[ "def", "parse_headers", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "basestring", ")", ":", "obj", "=", "cStringIO", ".", "StringIO", "(", "obj", ")", "hdrs", "=", "[", "]", "for", "line", "in", "obj", ":", "hdr", "=", "parse_header", "(", "line", ")", "if", "not", "hdr", ":", "break", "if", "isinstance", "(", "hdr", ",", "basestring", ")", ":", "if", "not", "hdrs", ":", "raise", "ValueError", "(", "\"First header is a continuation\"", ")", "hdrs", "[", "-", "1", "]", "=", "(", "hdrs", "[", "-", "1", "]", "[", "0", "]", ",", "hdrs", "[", "-", "1", "]", "[", "1", "]", "+", "hdr", ")", "continue", "hdrs", ".", "append", "(", "hdr", ")", "return", "iodict", ".", "IODict", "(", "hdrs", ")" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
unparse_headers
Parse a dictionary of headers to a string. Args: hdrs: A dictionary of headers. Returns: The headers as a string that can be used in an NNTP POST.
nntp/utils.py
def unparse_headers(hdrs): """Parse a dictionary of headers to a string. Args: hdrs: A dictionary of headers. Returns: The headers as a string that can be used in an NNTP POST. """ return "".join([unparse_header(n, v) for n, v in hdrs.items()]) + "\r\n"
def unparse_headers(hdrs): """Parse a dictionary of headers to a string. Args: hdrs: A dictionary of headers. Returns: The headers as a string that can be used in an NNTP POST. """ return "".join([unparse_header(n, v) for n, v in hdrs.items()]) + "\r\n"
[ "Parse", "a", "dictionary", "of", "headers", "to", "a", "string", "." ]
greenbender/pynntp
python
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/utils.py#L220-L229
[ "def", "unparse_headers", "(", "hdrs", ")", ":", "return", "\"\"", ".", "join", "(", "[", "unparse_header", "(", "n", ",", "v", ")", "for", "n", ",", "v", "in", "hdrs", ".", "items", "(", ")", "]", ")", "+", "\"\\r\\n\"" ]
991a76331cdf5d8f9dbf5b18f6e29adc80749a2f
test
WebHookHandler.do_POST
Handles the POST request sent by Boundary Url Action
boundary/webhook_handler.py
def do_POST(self): """ Handles the POST request sent by Boundary Url Action """ self.send_response(urllib2.httplib.OK) self.end_headers() content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) print("Client: {0}".format(str(self.client_address))) print("headers: {0}".format(self.headers)) print("path: {0}".format(self.path)) print("body: {0}".format(body))
def do_POST(self): """ Handles the POST request sent by Boundary Url Action """ self.send_response(urllib2.httplib.OK) self.end_headers() content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) print("Client: {0}".format(str(self.client_address))) print("headers: {0}".format(self.headers)) print("path: {0}".format(self.path)) print("body: {0}".format(body))
[ "Handles", "the", "POST", "request", "sent", "by", "Boundary", "Url", "Action" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/webhook_handler.py#L182-L193
[ "def", "do_POST", "(", "self", ")", ":", "self", ".", "send_response", "(", "urllib2", ".", "httplib", ".", "OK", ")", "self", ".", "end_headers", "(", ")", "content_length", "=", "int", "(", "self", ".", "headers", "[", "'Content-Length'", "]", ")", "body", "=", "self", ".", "rfile", ".", "read", "(", "content_length", ")", "print", "(", "\"Client: {0}\"", ".", "format", "(", "str", "(", "self", ".", "client_address", ")", ")", ")", "print", "(", "\"headers: {0}\"", ".", "format", "(", "self", ".", "headers", ")", ")", "print", "(", "\"path: {0}\"", ".", "format", "(", "self", ".", "path", ")", ")", "print", "(", "\"body: {0}\"", ".", "format", "(", "body", ")", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
run
Run the tests that are loaded by each of the strings provided. Arguments: tests (iterable): the collection of tests (specified as `str` s) to run reporter (Reporter): a `Reporter` to use for the run. If unprovided, the default is to return a `virtue.reporters.Counter` (which produces no output). stop_after (int): a number of non-successful tests to allow before stopping the run.
virtue/runner.py
def run(tests=(), reporter=None, stop_after=None): """ Run the tests that are loaded by each of the strings provided. Arguments: tests (iterable): the collection of tests (specified as `str` s) to run reporter (Reporter): a `Reporter` to use for the run. If unprovided, the default is to return a `virtue.reporters.Counter` (which produces no output). stop_after (int): a number of non-successful tests to allow before stopping the run. """ if reporter is None: reporter = Counter() if stop_after is not None: reporter = _StopAfterWrapper(reporter=reporter, limit=stop_after) locator = ObjectLocator() cases = ( case for test in tests for loader in locator.locate_by_name(name=test) for case in loader.load() ) suite = unittest.TestSuite(cases) getattr(reporter, "startTestRun", lambda: None)() suite.run(reporter) getattr(reporter, "stopTestRun", lambda: None)() return reporter
def run(tests=(), reporter=None, stop_after=None): """ Run the tests that are loaded by each of the strings provided. Arguments: tests (iterable): the collection of tests (specified as `str` s) to run reporter (Reporter): a `Reporter` to use for the run. If unprovided, the default is to return a `virtue.reporters.Counter` (which produces no output). stop_after (int): a number of non-successful tests to allow before stopping the run. """ if reporter is None: reporter = Counter() if stop_after is not None: reporter = _StopAfterWrapper(reporter=reporter, limit=stop_after) locator = ObjectLocator() cases = ( case for test in tests for loader in locator.locate_by_name(name=test) for case in loader.load() ) suite = unittest.TestSuite(cases) getattr(reporter, "startTestRun", lambda: None)() suite.run(reporter) getattr(reporter, "stopTestRun", lambda: None)() return reporter
[ "Run", "the", "tests", "that", "are", "loaded", "by", "each", "of", "the", "strings", "provided", "." ]
Julian/Virtue
python
https://github.com/Julian/Virtue/blob/d08be37d759c38c94a160bc13fe8f51bb2aeeedd/virtue/runner.py#L8-L46
[ "def", "run", "(", "tests", "=", "(", ")", ",", "reporter", "=", "None", ",", "stop_after", "=", "None", ")", ":", "if", "reporter", "is", "None", ":", "reporter", "=", "Counter", "(", ")", "if", "stop_after", "is", "not", "None", ":", "reporter", "=", "_StopAfterWrapper", "(", "reporter", "=", "reporter", ",", "limit", "=", "stop_after", ")", "locator", "=", "ObjectLocator", "(", ")", "cases", "=", "(", "case", "for", "test", "in", "tests", "for", "loader", "in", "locator", ".", "locate_by_name", "(", "name", "=", "test", ")", "for", "case", "in", "loader", ".", "load", "(", ")", ")", "suite", "=", "unittest", ".", "TestSuite", "(", "cases", ")", "getattr", "(", "reporter", ",", "\"startTestRun\"", ",", "lambda", ":", "None", ")", "(", ")", "suite", ".", "run", "(", "reporter", ")", "getattr", "(", "reporter", ",", "\"stopTestRun\"", ",", "lambda", ":", "None", ")", "(", ")", "return", "reporter" ]
d08be37d759c38c94a160bc13fe8f51bb2aeeedd
test
defaults_docstring
Return a docstring from a list of defaults.
pymodeler/parameter.py
def defaults_docstring(defaults, header=None, indent=None, footer=None): """Return a docstring from a list of defaults. """ if indent is None: indent = '' if header is None: header = '' if footer is None: footer = '' width = 60 #hbar = indent + width * '=' + '\n' # horizontal bar hbar = '\n' s = hbar + (header) + hbar for key, value, desc in defaults: if isinstance(value, basestring): value = "'" + value + "'" if hasattr(value, '__call__'): value = "<" + value.__name__ + ">" s += indent +'%-12s\n' % ("%s :" % key) s += indent + indent + (indent + 23 * ' ').join(desc.split('\n')) s += ' [%s]\n\n' % str(value) s += hbar s += footer return s
def defaults_docstring(defaults, header=None, indent=None, footer=None): """Return a docstring from a list of defaults. """ if indent is None: indent = '' if header is None: header = '' if footer is None: footer = '' width = 60 #hbar = indent + width * '=' + '\n' # horizontal bar hbar = '\n' s = hbar + (header) + hbar for key, value, desc in defaults: if isinstance(value, basestring): value = "'" + value + "'" if hasattr(value, '__call__'): value = "<" + value.__name__ + ">" s += indent +'%-12s\n' % ("%s :" % key) s += indent + indent + (indent + 23 * ' ').join(desc.split('\n')) s += ' [%s]\n\n' % str(value) s += hbar s += footer return s
[ "Return", "a", "docstring", "from", "a", "list", "of", "defaults", "." ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L44-L70
[ "def", "defaults_docstring", "(", "defaults", ",", "header", "=", "None", ",", "indent", "=", "None", ",", "footer", "=", "None", ")", ":", "if", "indent", "is", "None", ":", "indent", "=", "''", "if", "header", "is", "None", ":", "header", "=", "''", "if", "footer", "is", "None", ":", "footer", "=", "''", "width", "=", "60", "#hbar = indent + width * '=' + '\\n' # horizontal bar", "hbar", "=", "'\\n'", "s", "=", "hbar", "+", "(", "header", ")", "+", "hbar", "for", "key", ",", "value", ",", "desc", "in", "defaults", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "value", "=", "\"'\"", "+", "value", "+", "\"'\"", "if", "hasattr", "(", "value", ",", "'__call__'", ")", ":", "value", "=", "\"<\"", "+", "value", ".", "__name__", "+", "\">\"", "s", "+=", "indent", "+", "'%-12s\\n'", "%", "(", "\"%s :\"", "%", "key", ")", "s", "+=", "indent", "+", "indent", "+", "(", "indent", "+", "23", "*", "' '", ")", ".", "join", "(", "desc", ".", "split", "(", "'\\n'", ")", ")", "s", "+=", "' [%s]\\n\\n'", "%", "str", "(", "value", ")", "s", "+=", "hbar", "s", "+=", "footer", "return", "s" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
defaults_decorator
Decorator to append default kwargs to a function.
pymodeler/parameter.py
def defaults_decorator(defaults): """Decorator to append default kwargs to a function. """ def decorator(func): """Function that appends default kwargs to a function. """ kwargs = dict(header='Keyword arguments\n-----------------\n', indent=' ', footer='\n') doc = defaults_docstring(defaults, **kwargs) if func.__doc__ is None: func.__doc__ = '' func.__doc__ += doc return func return decorator
def defaults_decorator(defaults): """Decorator to append default kwargs to a function. """ def decorator(func): """Function that appends default kwargs to a function. """ kwargs = dict(header='Keyword arguments\n-----------------\n', indent=' ', footer='\n') doc = defaults_docstring(defaults, **kwargs) if func.__doc__ is None: func.__doc__ = '' func.__doc__ += doc return func return decorator
[ "Decorator", "to", "append", "default", "kwargs", "to", "a", "function", "." ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L73-L88
[ "def", "defaults_decorator", "(", "defaults", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"Function that appends default kwargs to a function.\n \"\"\"", "kwargs", "=", "dict", "(", "header", "=", "'Keyword arguments\\n-----------------\\n'", ",", "indent", "=", "' '", ",", "footer", "=", "'\\n'", ")", "doc", "=", "defaults_docstring", "(", "defaults", ",", "*", "*", "kwargs", ")", "if", "func", ".", "__doc__", "is", "None", ":", "func", ".", "__doc__", "=", "''", "func", ".", "__doc__", "+=", "doc", "return", "func", "return", "decorator" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Property._load
Load kwargs key,value pairs into __dict__
pymodeler/parameter.py
def _load(self, **kwargs): """Load kwargs key,value pairs into __dict__ """ defaults = dict([(d[0], d[1]) for d in self.defaults]) # Require kwargs are in defaults for k in kwargs: if k not in defaults: msg = "Unrecognized attribute of %s: %s" % ( self.__class__.__name__, k) raise AttributeError(msg) defaults.update(kwargs) # This doesn't overwrite the properties self.__dict__.update(defaults) # This should now be set self.check_type(self.__dict__['default']) # This sets the underlying property values (i.e., __value__) self.set(**defaults)
def _load(self, **kwargs): """Load kwargs key,value pairs into __dict__ """ defaults = dict([(d[0], d[1]) for d in self.defaults]) # Require kwargs are in defaults for k in kwargs: if k not in defaults: msg = "Unrecognized attribute of %s: %s" % ( self.__class__.__name__, k) raise AttributeError(msg) defaults.update(kwargs) # This doesn't overwrite the properties self.__dict__.update(defaults) # This should now be set self.check_type(self.__dict__['default']) # This sets the underlying property values (i.e., __value__) self.set(**defaults)
[ "Load", "kwargs", "key", "value", "pairs", "into", "__dict__" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L147-L166
[ "def", "_load", "(", "self", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "dict", "(", "[", "(", "d", "[", "0", "]", ",", "d", "[", "1", "]", ")", "for", "d", "in", "self", ".", "defaults", "]", ")", "# Require kwargs are in defaults", "for", "k", "in", "kwargs", ":", "if", "k", "not", "in", "defaults", ":", "msg", "=", "\"Unrecognized attribute of %s: %s\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "k", ")", "raise", "AttributeError", "(", "msg", ")", "defaults", ".", "update", "(", "kwargs", ")", "# This doesn't overwrite the properties", "self", ".", "__dict__", ".", "update", "(", "defaults", ")", "# This should now be set", "self", ".", "check_type", "(", "self", ".", "__dict__", "[", "'default'", "]", ")", "# This sets the underlying property values (i.e., __value__)", "self", ".", "set", "(", "*", "*", "defaults", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Property.defaults_docstring
Add the default values to the class docstring
pymodeler/parameter.py
def defaults_docstring(cls, header=None, indent=None, footer=None): """Add the default values to the class docstring""" return defaults_docstring(cls.defaults, header=header, indent=indent, footer=footer)
def defaults_docstring(cls, header=None, indent=None, footer=None): """Add the default values to the class docstring""" return defaults_docstring(cls.defaults, header=header, indent=indent, footer=footer)
[ "Add", "the", "default", "values", "to", "the", "class", "docstring" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L169-L172
[ "def", "defaults_docstring", "(", "cls", ",", "header", "=", "None", ",", "indent", "=", "None", ",", "footer", "=", "None", ")", ":", "return", "defaults_docstring", "(", "cls", ".", "defaults", ",", "header", "=", "header", ",", "indent", "=", "indent", ",", "footer", "=", "footer", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Property.set_value
Set the value This invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes.
pymodeler/parameter.py
def set_value(self, value): """Set the value This invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ self.check_bounds(value) self.check_type(value) self.__value__ = value
def set_value(self, value): """Set the value This invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ self.check_bounds(value) self.check_type(value) self.__value__ = value
[ "Set", "the", "value" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L209-L217
[ "def", "set_value", "(", "self", ",", "value", ")", ":", "self", ".", "check_bounds", "(", "value", ")", "self", ".", "check_type", "(", "value", ")", "self", ".", "__value__", "=", "value" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Property.check_type
Hook for type-checking, invoked during assignment. raises TypeError if neither value nor self.dtype are None and they do not match. will not raise an exception if either value or self.dtype is None
pymodeler/parameter.py
def check_type(self, value): """Hook for type-checking, invoked during assignment. raises TypeError if neither value nor self.dtype are None and they do not match. will not raise an exception if either value or self.dtype is None """ if self.__dict__['dtype'] is None: return elif value is None: return elif isinstance(value, self.__dict__['dtype']): return msg = "Value of type %s, when %s was expected." % ( type(value), self.__dict__['dtype']) raise TypeError(msg)
def check_type(self, value): """Hook for type-checking, invoked during assignment. raises TypeError if neither value nor self.dtype are None and they do not match. will not raise an exception if either value or self.dtype is None """ if self.__dict__['dtype'] is None: return elif value is None: return elif isinstance(value, self.__dict__['dtype']): return msg = "Value of type %s, when %s was expected." % ( type(value), self.__dict__['dtype']) raise TypeError(msg)
[ "Hook", "for", "type", "-", "checking", "invoked", "during", "assignment", "." ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L252-L268
[ "def", "check_type", "(", "self", ",", "value", ")", ":", "if", "self", ".", "__dict__", "[", "'dtype'", "]", "is", "None", ":", "return", "elif", "value", "is", "None", ":", "return", "elif", "isinstance", "(", "value", ",", "self", ".", "__dict__", "[", "'dtype'", "]", ")", ":", "return", "msg", "=", "\"Value of type %s, when %s was expected.\"", "%", "(", "type", "(", "value", ")", ",", "self", ".", "__dict__", "[", "'dtype'", "]", ")", "raise", "TypeError", "(", "msg", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Derived.value
Return the current value. This first checks if the value is cached (i.e., if `self.__value__` is not None) If it is not cached then it invokes the `loader` function to compute the value, and caches the computed value
pymodeler/parameter.py
def value(self): """Return the current value. This first checks if the value is cached (i.e., if `self.__value__` is not None) If it is not cached then it invokes the `loader` function to compute the value, and caches the computed value """ if self.__value__ is None: try: loader = self.__dict__['loader'] except KeyError: raise AttributeError("Loader is not defined") # Try to run the loader. # Don't catch expections here, let the Model class figure it out val = loader() # Try to set the value try: self.set_value(val) except TypeError: msg = "Loader must return variable of type %s or None, got %s" % (self.__dict__['dtype'], type(val)) raise TypeError(msg) return self.__value__
def value(self): """Return the current value. This first checks if the value is cached (i.e., if `self.__value__` is not None) If it is not cached then it invokes the `loader` function to compute the value, and caches the computed value """ if self.__value__ is None: try: loader = self.__dict__['loader'] except KeyError: raise AttributeError("Loader is not defined") # Try to run the loader. # Don't catch expections here, let the Model class figure it out val = loader() # Try to set the value try: self.set_value(val) except TypeError: msg = "Loader must return variable of type %s or None, got %s" % (self.__dict__['dtype'], type(val)) raise TypeError(msg) return self.__value__
[ "Return", "the", "current", "value", "." ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L290-L317
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "__value__", "is", "None", ":", "try", ":", "loader", "=", "self", ".", "__dict__", "[", "'loader'", "]", "except", "KeyError", ":", "raise", "AttributeError", "(", "\"Loader is not defined\"", ")", "# Try to run the loader.", "# Don't catch expections here, let the Model class figure it out", "val", "=", "loader", "(", ")", "# Try to set the value", "try", ":", "self", ".", "set_value", "(", "val", ")", "except", "TypeError", ":", "msg", "=", "\"Loader must return variable of type %s or None, got %s\"", "%", "(", "self", ".", "__dict__", "[", "'dtype'", "]", ",", "type", "(", "val", ")", ")", "raise", "TypeError", "(", "msg", ")", "return", "self", ".", "__value__" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Parameter.check_type
Hook for type-checking, invoked during assignment. Allows size 1 numpy arrays and lists, but raises TypeError if value can not be cast to a scalar.
pymodeler/parameter.py
def check_type(self, value): """Hook for type-checking, invoked during assignment. Allows size 1 numpy arrays and lists, but raises TypeError if value can not be cast to a scalar. """ try: scalar = asscalar(value) except ValueError as e: raise TypeError(e) super(Parameter, self).check_type(scalar)
def check_type(self, value): """Hook for type-checking, invoked during assignment. Allows size 1 numpy arrays and lists, but raises TypeError if value can not be cast to a scalar. """ try: scalar = asscalar(value) except ValueError as e: raise TypeError(e) super(Parameter, self).check_type(scalar)
[ "Hook", "for", "type", "-", "checking", "invoked", "during", "assignment", ".", "Allows", "size", "1", "numpy", "arrays", "and", "lists", "but", "raises", "TypeError", "if", "value", "can", "not", "be", "cast", "to", "a", "scalar", "." ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L349-L360
[ "def", "check_type", "(", "self", ",", "value", ")", ":", "try", ":", "scalar", "=", "asscalar", "(", "value", ")", "except", "ValueError", "as", "e", ":", "raise", "TypeError", "(", "e", ")", "super", "(", "Parameter", ",", "self", ")", ".", "check_type", "(", "scalar", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Parameter.symmetric_error
Return the symmertic error Similar to above, but zero implies no error estimate, and otherwise this will either be the symmetric error, or the average of the low,high asymmetric errors.
pymodeler/parameter.py
def symmetric_error(self): """Return the symmertic error Similar to above, but zero implies no error estimate, and otherwise this will either be the symmetric error, or the average of the low,high asymmetric errors. """ # ADW: Should this be `np.nan`? if self.__errors__ is None: return 0. if np.isscalar(self.__errors__): return self.__errors__ return 0.5 * (self.__errors__[0] + self.__errors__[1])
def symmetric_error(self): """Return the symmertic error Similar to above, but zero implies no error estimate, and otherwise this will either be the symmetric error, or the average of the low,high asymmetric errors. """ # ADW: Should this be `np.nan`? if self.__errors__ is None: return 0. if np.isscalar(self.__errors__): return self.__errors__ return 0.5 * (self.__errors__[0] + self.__errors__[1])
[ "Return", "the", "symmertic", "error" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L575-L587
[ "def", "symmetric_error", "(", "self", ")", ":", "# ADW: Should this be `np.nan`?", "if", "self", ".", "__errors__", "is", "None", ":", "return", "0.", "if", "np", ".", "isscalar", "(", "self", ".", "__errors__", ")", ":", "return", "self", ".", "__errors__", "return", "0.5", "*", "(", "self", ".", "__errors__", "[", "0", "]", "+", "self", ".", "__errors__", "[", "1", "]", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Parameter.set_free
Set free/fixed status
pymodeler/parameter.py
def set_free(self, free): """Set free/fixed status """ if free is None: self.__free__ = False return self.__free__ = bool(free)
def set_free(self, free): """Set free/fixed status """ if free is None: self.__free__ = False return self.__free__ = bool(free)
[ "Set", "free", "/", "fixed", "status" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L613-L618
[ "def", "set_free", "(", "self", ",", "free", ")", ":", "if", "free", "is", "None", ":", "self", ".", "__free__", "=", "False", "return", "self", ".", "__free__", "=", "bool", "(", "free", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Parameter.set_errors
Set parameter error estimate
pymodeler/parameter.py
def set_errors(self, errors): """Set parameter error estimate """ if errors is None: self.__errors__ = None return self.__errors__ = [asscalar(e) for e in errors]
def set_errors(self, errors): """Set parameter error estimate """ if errors is None: self.__errors__ = None return self.__errors__ = [asscalar(e) for e in errors]
[ "Set", "parameter", "error", "estimate" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L620-L625
[ "def", "set_errors", "(", "self", ",", "errors", ")", ":", "if", "errors", "is", "None", ":", "self", ".", "__errors__", "=", "None", "return", "self", ".", "__errors__", "=", "[", "asscalar", "(", "e", ")", "for", "e", "in", "errors", "]" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Parameter.set
Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes.
pymodeler/parameter.py
def set(self, **kwargs): """Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ # Probably want to reset bounds if set fails if 'bounds' in kwargs: self.set_bounds(kwargs.pop('bounds')) if 'free' in kwargs: self.set_free(kwargs.pop('free')) if 'errors' in kwargs: self.set_errors(kwargs.pop('errors')) if 'value' in kwargs: self.set_value(kwargs.pop('value'))
def set(self, **kwargs): """Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ # Probably want to reset bounds if set fails if 'bounds' in kwargs: self.set_bounds(kwargs.pop('bounds')) if 'free' in kwargs: self.set_free(kwargs.pop('free')) if 'errors' in kwargs: self.set_errors(kwargs.pop('errors')) if 'value' in kwargs: self.set_value(kwargs.pop('value'))
[ "Set", "the", "value", "bounds", "free", "errors", "based", "on", "corresponding", "kwargs" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/parameter.py#L627-L641
[ "def", "set", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Probably want to reset bounds if set fails", "if", "'bounds'", "in", "kwargs", ":", "self", ".", "set_bounds", "(", "kwargs", ".", "pop", "(", "'bounds'", ")", ")", "if", "'free'", "in", "kwargs", ":", "self", ".", "set_free", "(", "kwargs", ".", "pop", "(", "'free'", ")", ")", "if", "'errors'", "in", "kwargs", ":", "self", ".", "set_errors", "(", "kwargs", ".", "pop", "(", "'errors'", ")", ")", "if", "'value'", "in", "kwargs", ":", "self", ".", "set_value", "(", "kwargs", ".", "pop", "(", "'value'", ")", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
MetricCreateBulk.load_and_parse
Load the metrics file from the given path
boundary/metric_create_bulk.py
def load_and_parse(self): """ Load the metrics file from the given path """ f = open(self.file_path, "r") metrics_json = f.read() self.metrics = json.loads(metrics_json)
def load_and_parse(self): """ Load the metrics file from the given path """ f = open(self.file_path, "r") metrics_json = f.read() self.metrics = json.loads(metrics_json)
[ "Load", "the", "metrics", "file", "from", "the", "given", "path" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/metric_create_bulk.py#L55-L61
[ "def", "load_and_parse", "(", "self", ")", ":", "f", "=", "open", "(", "self", ".", "file_path", ",", "\"r\"", ")", "metrics_json", "=", "f", ".", "read", "(", ")", "self", ".", "metrics", "=", "json", ".", "loads", "(", "metrics_json", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
MetricCreateBulk.import_metrics
1) Get command line arguments 2) Read the JSON file 3) Parse into a dictionary 4) Create or update definitions using API call
boundary/metric_create_bulk.py
def import_metrics(self): """ 1) Get command line arguments 2) Read the JSON file 3) Parse into a dictionary 4) Create or update definitions using API call """ self.v2Metrics = self.metricDefinitionV2(self.metrics) if self.v2Metrics: metrics = self.metrics else: metrics = self.metrics['result'] # Loop through the metrics and call the API # to create/update for m in metrics: if self.v2Metrics: metric = metrics[m] metric['name'] = m else: metric = m self.create_update(metric)
def import_metrics(self): """ 1) Get command line arguments 2) Read the JSON file 3) Parse into a dictionary 4) Create or update definitions using API call """ self.v2Metrics = self.metricDefinitionV2(self.metrics) if self.v2Metrics: metrics = self.metrics else: metrics = self.metrics['result'] # Loop through the metrics and call the API # to create/update for m in metrics: if self.v2Metrics: metric = metrics[m] metric['name'] = m else: metric = m self.create_update(metric)
[ "1", ")", "Get", "command", "line", "arguments", "2", ")", "Read", "the", "JSON", "file", "3", ")", "Parse", "into", "a", "dictionary", "4", ")", "Create", "or", "update", "definitions", "using", "API", "call" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/metric_create_bulk.py#L63-L86
[ "def", "import_metrics", "(", "self", ")", ":", "self", ".", "v2Metrics", "=", "self", ".", "metricDefinitionV2", "(", "self", ".", "metrics", ")", "if", "self", ".", "v2Metrics", ":", "metrics", "=", "self", ".", "metrics", "else", ":", "metrics", "=", "self", ".", "metrics", "[", "'result'", "]", "# Loop through the metrics and call the API", "# to create/update", "for", "m", "in", "metrics", ":", "if", "self", ".", "v2Metrics", ":", "metric", "=", "metrics", "[", "m", "]", "metric", "[", "'name'", "]", "=", "m", "else", ":", "metric", "=", "m", "self", ".", "create_update", "(", "metric", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
TzDescriptor.create_from_pytz
Create an instance using the result of the timezone() call in "pytz".
pytzpure/tz_descriptor.py
def create_from_pytz(cls, tz_info): """Create an instance using the result of the timezone() call in "pytz". """ zone_name = tz_info.zone utc_transition_times_list_raw = getattr(tz_info, '_utc_transition_times', None) utc_transition_times_list = [tuple(utt.timetuple()) for utt in utc_transition_times_list_raw] \ if utc_transition_times_list_raw is not None \ else None transition_info_list_raw = getattr(tz_info, '_transition_info', None) transition_info_list = [(utcoffset_td.total_seconds(), dst_td.total_seconds(), tzname) for (utcoffset_td, dst_td, tzname) in transition_info_list_raw] \ if transition_info_list_raw is not None \ else None try: utcoffset_dt = tz_info._utcoffset except AttributeError: utcoffset = None else: utcoffset = utcoffset_dt.total_seconds() tzname = getattr(tz_info, '_tzname', None) parent_class_name = getmro(tz_info.__class__)[1].__name__ return cls(zone_name, parent_class_name, utc_transition_times_list, transition_info_list, utcoffset, tzname)
def create_from_pytz(cls, tz_info): """Create an instance using the result of the timezone() call in "pytz". """ zone_name = tz_info.zone utc_transition_times_list_raw = getattr(tz_info, '_utc_transition_times', None) utc_transition_times_list = [tuple(utt.timetuple()) for utt in utc_transition_times_list_raw] \ if utc_transition_times_list_raw is not None \ else None transition_info_list_raw = getattr(tz_info, '_transition_info', None) transition_info_list = [(utcoffset_td.total_seconds(), dst_td.total_seconds(), tzname) for (utcoffset_td, dst_td, tzname) in transition_info_list_raw] \ if transition_info_list_raw is not None \ else None try: utcoffset_dt = tz_info._utcoffset except AttributeError: utcoffset = None else: utcoffset = utcoffset_dt.total_seconds() tzname = getattr(tz_info, '_tzname', None) parent_class_name = getmro(tz_info.__class__)[1].__name__ return cls(zone_name, parent_class_name, utc_transition_times_list, transition_info_list, utcoffset, tzname)
[ "Create", "an", "instance", "using", "the", "result", "of", "the", "timezone", "()", "call", "in", "pytz", "." ]
dsoprea/pytzPure
python
https://github.com/dsoprea/pytzPure/blob/ec8f7803ca1025d363ba954905ae7717a0524a0e/pytzpure/tz_descriptor.py#L36-L76
[ "def", "create_from_pytz", "(", "cls", ",", "tz_info", ")", ":", "zone_name", "=", "tz_info", ".", "zone", "utc_transition_times_list_raw", "=", "getattr", "(", "tz_info", ",", "'_utc_transition_times'", ",", "None", ")", "utc_transition_times_list", "=", "[", "tuple", "(", "utt", ".", "timetuple", "(", ")", ")", "for", "utt", "in", "utc_transition_times_list_raw", "]", "if", "utc_transition_times_list_raw", "is", "not", "None", "else", "None", "transition_info_list_raw", "=", "getattr", "(", "tz_info", ",", "'_transition_info'", ",", "None", ")", "transition_info_list", "=", "[", "(", "utcoffset_td", ".", "total_seconds", "(", ")", ",", "dst_td", ".", "total_seconds", "(", ")", ",", "tzname", ")", "for", "(", "utcoffset_td", ",", "dst_td", ",", "tzname", ")", "in", "transition_info_list_raw", "]", "if", "transition_info_list_raw", "is", "not", "None", "else", "None", "try", ":", "utcoffset_dt", "=", "tz_info", ".", "_utcoffset", "except", "AttributeError", ":", "utcoffset", "=", "None", "else", ":", "utcoffset", "=", "utcoffset_dt", ".", "total_seconds", "(", ")", "tzname", "=", "getattr", "(", "tz_info", ",", "'_tzname'", ",", "None", ")", "parent_class_name", "=", "getmro", "(", "tz_info", ".", "__class__", ")", "[", "1", "]", ".", "__name__", "return", "cls", "(", "zone_name", ",", "parent_class_name", ",", "utc_transition_times_list", ",", "transition_info_list", ",", "utcoffset", ",", "tzname", ")" ]
ec8f7803ca1025d363ba954905ae7717a0524a0e
test
MetricExport.extract_dictionary
Extract required fields from an array
boundary/metric_export.py
def extract_dictionary(self, metrics): """ Extract required fields from an array """ new_metrics = {} for m in metrics: metric = self.extract_fields(m) new_metrics[m['name']] = metric return new_metrics
def extract_dictionary(self, metrics): """ Extract required fields from an array """ new_metrics = {} for m in metrics: metric = self.extract_fields(m) new_metrics[m['name']] = metric return new_metrics
[ "Extract", "required", "fields", "from", "an", "array" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/metric_export.py#L59-L67
[ "def", "extract_dictionary", "(", "self", ",", "metrics", ")", ":", "new_metrics", "=", "{", "}", "for", "m", "in", "metrics", ":", "metric", "=", "self", ".", "extract_fields", "(", "m", ")", "new_metrics", "[", "m", "[", "'name'", "]", "]", "=", "metric", "return", "new_metrics" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
MetricExport.filter
Apply the criteria to filter out on the metrics required
boundary/metric_export.py
def filter(self): """ Apply the criteria to filter out on the metrics required """ if self.filter_expression is not None: new_metrics = [] metrics = self.metrics['result'] for m in metrics: if self.filter_expression.search(m['name']): new_metrics.append(m) else: new_metrics = self.metrics['result'] self.metrics = self.extract_dictionary(new_metrics)
def filter(self): """ Apply the criteria to filter out on the metrics required """ if self.filter_expression is not None: new_metrics = [] metrics = self.metrics['result'] for m in metrics: if self.filter_expression.search(m['name']): new_metrics.append(m) else: new_metrics = self.metrics['result'] self.metrics = self.extract_dictionary(new_metrics)
[ "Apply", "the", "criteria", "to", "filter", "out", "on", "the", "metrics", "required" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/metric_export.py#L69-L82
[ "def", "filter", "(", "self", ")", ":", "if", "self", ".", "filter_expression", "is", "not", "None", ":", "new_metrics", "=", "[", "]", "metrics", "=", "self", ".", "metrics", "[", "'result'", "]", "for", "m", "in", "metrics", ":", "if", "self", ".", "filter_expression", ".", "search", "(", "m", "[", "'name'", "]", ")", ":", "new_metrics", ".", "append", "(", "m", ")", "else", ":", "new_metrics", "=", "self", ".", "metrics", "[", "'result'", "]", "self", ".", "metrics", "=", "self", ".", "extract_dictionary", "(", "new_metrics", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
HostgroupGet.get_arguments
Extracts the specific arguments of this CLI
boundary/hostgroup_get.py
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.hostGroupId is not None: self.hostGroupId = self.args.hostGroupId self.path = "v1/hostgroup/{0}".format(str(self.hostGroupId))
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.hostGroupId is not None: self.hostGroupId = self.args.hostGroupId self.path = "v1/hostgroup/{0}".format(str(self.hostGroupId))
[ "Extracts", "the", "specific", "arguments", "of", "this", "CLI" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/hostgroup_get.py#L36-L44
[ "def", "get_arguments", "(", "self", ")", ":", "ApiCli", ".", "get_arguments", "(", "self", ")", "if", "self", ".", "args", ".", "hostGroupId", "is", "not", "None", ":", "self", ".", "hostGroupId", "=", "self", ".", "args", ".", "hostGroupId", "self", ".", "path", "=", "\"v1/hostgroup/{0}\"", ".", "format", "(", "str", "(", "self", ".", "hostGroupId", ")", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
EventCreate.get_arguments
Extracts the specific arguments of this CLI
boundary/event_create.py
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.tenant_id is not None: self._tenant_id = self.args.tenant_id if self.args.fingerprint_fields is not None: self._fingerprint_fields = self.args.fingerprint_fields if self.args.title is not None: self._title = self.args.title if self.args.source is not None: self._source = self.args.source if self.args.severity is not None: self._severity = self.args.severity if self.args.message is not None: self._message = self.args.message event = {} if self._title is not None: event['title'] = self._title if self._severity is not None: event['severity'] = self._severity if self._message is not None: event['message'] = self._message if self._source is not None: if 'source' not in event: event['source'] = {} if len(self._source) >= 1: event['source']['ref'] = self._source[0] if len(self._source) >= 2: event['source']['type'] = self._source[1] self._process_properties(self.args.properties) if self._properties is not None: event['properties'] = self._properties if self._fingerprint_fields is not None: event['fingerprintFields'] = self._fingerprint_fields self.data = json.dumps(event, sort_keys=True) self.headers = {'Content-Type': 'application/json'}
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.tenant_id is not None: self._tenant_id = self.args.tenant_id if self.args.fingerprint_fields is not None: self._fingerprint_fields = self.args.fingerprint_fields if self.args.title is not None: self._title = self.args.title if self.args.source is not None: self._source = self.args.source if self.args.severity is not None: self._severity = self.args.severity if self.args.message is not None: self._message = self.args.message event = {} if self._title is not None: event['title'] = self._title if self._severity is not None: event['severity'] = self._severity if self._message is not None: event['message'] = self._message if self._source is not None: if 'source' not in event: event['source'] = {} if len(self._source) >= 1: event['source']['ref'] = self._source[0] if len(self._source) >= 2: event['source']['type'] = self._source[1] self._process_properties(self.args.properties) if self._properties is not None: event['properties'] = self._properties if self._fingerprint_fields is not None: event['fingerprintFields'] = self._fingerprint_fields self.data = json.dumps(event, sort_keys=True) self.headers = {'Content-Type': 'application/json'}
[ "Extracts", "the", "specific", "arguments", "of", "this", "CLI" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/event_create.py#L94-L145
[ "def", "get_arguments", "(", "self", ")", ":", "ApiCli", ".", "get_arguments", "(", "self", ")", "if", "self", ".", "args", ".", "tenant_id", "is", "not", "None", ":", "self", ".", "_tenant_id", "=", "self", ".", "args", ".", "tenant_id", "if", "self", ".", "args", ".", "fingerprint_fields", "is", "not", "None", ":", "self", ".", "_fingerprint_fields", "=", "self", ".", "args", ".", "fingerprint_fields", "if", "self", ".", "args", ".", "title", "is", "not", "None", ":", "self", ".", "_title", "=", "self", ".", "args", ".", "title", "if", "self", ".", "args", ".", "source", "is", "not", "None", ":", "self", ".", "_source", "=", "self", ".", "args", ".", "source", "if", "self", ".", "args", ".", "severity", "is", "not", "None", ":", "self", ".", "_severity", "=", "self", ".", "args", ".", "severity", "if", "self", ".", "args", ".", "message", "is", "not", "None", ":", "self", ".", "_message", "=", "self", ".", "args", ".", "message", "event", "=", "{", "}", "if", "self", ".", "_title", "is", "not", "None", ":", "event", "[", "'title'", "]", "=", "self", ".", "_title", "if", "self", ".", "_severity", "is", "not", "None", ":", "event", "[", "'severity'", "]", "=", "self", ".", "_severity", "if", "self", ".", "_message", "is", "not", "None", ":", "event", "[", "'message'", "]", "=", "self", ".", "_message", "if", "self", ".", "_source", "is", "not", "None", ":", "if", "'source'", "not", "in", "event", ":", "event", "[", "'source'", "]", "=", "{", "}", "if", "len", "(", "self", ".", "_source", ")", ">=", "1", ":", "event", "[", "'source'", "]", "[", "'ref'", "]", "=", "self", ".", "_source", "[", "0", "]", "if", "len", "(", "self", ".", "_source", ")", ">=", "2", ":", "event", "[", "'source'", "]", "[", "'type'", "]", "=", "self", ".", "_source", "[", "1", "]", "self", ".", "_process_properties", "(", "self", ".", "args", ".", "properties", ")", "if", "self", ".", "_properties", "is", "not", "None", ":", "event", "[", "'properties'", "]", "=", "self", ".", "_properties", "if", "self", ".", "_fingerprint_fields", "is", "not", "None", ":", "event", "[", "'fingerprintFields'", "]", "=", "self", ".", "_fingerprint_fields", "self", ".", "data", "=", "json", ".", "dumps", "(", "event", ",", "sort_keys", "=", "True", ")", "self", ".", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
MeterClient._call_api
Make a call to the meter via JSON RPC
boundary/meter_client.py
def _call_api(self): """ Make a call to the meter via JSON RPC """ # Allocate a socket and connect to the meter sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((self.rpc_host, self.rpc_port)) self.get_json() message = [self.rpc_message.encode('utf-8')] for line in message: sockobj.send(line) data = sockobj.recv(self.MAX_LINE) print(data) self.rpc_data.append(data) sockobj.close()
def _call_api(self): """ Make a call to the meter via JSON RPC """ # Allocate a socket and connect to the meter sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((self.rpc_host, self.rpc_port)) self.get_json() message = [self.rpc_message.encode('utf-8')] for line in message: sockobj.send(line) data = sockobj.recv(self.MAX_LINE) print(data) self.rpc_data.append(data) sockobj.close()
[ "Make", "a", "call", "to", "the", "meter", "via", "JSON", "RPC" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/meter_client.py#L122-L139
[ "def", "_call_api", "(", "self", ")", ":", "# Allocate a socket and connect to the meter", "sockobj", "=", "socket", "(", "AF_INET", ",", "SOCK_STREAM", ")", "sockobj", ".", "connect", "(", "(", "self", ".", "rpc_host", ",", "self", ".", "rpc_port", ")", ")", "self", ".", "get_json", "(", ")", "message", "=", "[", "self", ".", "rpc_message", ".", "encode", "(", "'utf-8'", ")", "]", "for", "line", "in", "message", ":", "sockobj", ".", "send", "(", "line", ")", "data", "=", "sockobj", ".", "recv", "(", "self", ".", "MAX_LINE", ")", "print", "(", "data", ")", "self", ".", "rpc_data", ".", "append", "(", "data", ")", "sockobj", ".", "close", "(", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
HostgroupUpdate.get_arguments
Extracts the specific arguments of this CLI
boundary/hostgroup_update.py
def get_arguments(self): """ Extracts the specific arguments of this CLI """ HostgroupModify.get_arguments(self) if self.args.host_group_id is not None: self.host_group_id = self.args.host_group_id self.path = "v1/hostgroup/" + str(self.host_group_id)
def get_arguments(self): """ Extracts the specific arguments of this CLI """ HostgroupModify.get_arguments(self) if self.args.host_group_id is not None: self.host_group_id = self.args.host_group_id self.path = "v1/hostgroup/" + str(self.host_group_id)
[ "Extracts", "the", "specific", "arguments", "of", "this", "CLI" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/hostgroup_update.py#L38-L47
[ "def", "get_arguments", "(", "self", ")", ":", "HostgroupModify", ".", "get_arguments", "(", "self", ")", "if", "self", ".", "args", ".", "host_group_id", "is", "not", "None", ":", "self", ".", "host_group_id", "=", "self", ".", "args", ".", "host_group_id", "self", ".", "path", "=", "\"v1/hostgroup/\"", "+", "str", "(", "self", ".", "host_group_id", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
Parser.identifier
identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;
pyebnf/_hand_written_parser.py
def identifier(self, text): """identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;""" self._attempting(text) return concatenation([ alternation([ self.alpha_character, "_" ]), zero_or_more( alternation([ self.alpha_character, "_", self.digit ]) ) ], ignore_whitespace=False)(text).compressed(TokenType.identifier)
def identifier(self, text): """identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;""" self._attempting(text) return concatenation([ alternation([ self.alpha_character, "_" ]), zero_or_more( alternation([ self.alpha_character, "_", self.digit ]) ) ], ignore_whitespace=False)(text).compressed(TokenType.identifier)
[ "identifier", "=", "alpha_character", "|", "_", ".", "{", "alpha_character", "|", "_", "|", "digit", "}", ";" ]
treycucco/pyebnf
python
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L76-L91
[ "def", "identifier", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "concatenation", "(", "[", "alternation", "(", "[", "self", ".", "alpha_character", ",", "\"_\"", "]", ")", ",", "zero_or_more", "(", "alternation", "(", "[", "self", ".", "alpha_character", ",", "\"_\"", ",", "self", ".", "digit", "]", ")", ")", "]", ",", "ignore_whitespace", "=", "False", ")", "(", "text", ")", ".", "compressed", "(", "TokenType", ".", "identifier", ")" ]
3634ddabbe5d73508bcc20f4a591f86a46634e1d
test
Parser.expression
expression = number , op_mult , expression | expression_terminal , op_mult , number , [operator , expression] | expression_terminal , op_add , [operator , expression] | expression_terminal , [operator , expression] ;
pyebnf/_hand_written_parser.py
def expression(self, text): """expression = number , op_mult , expression | expression_terminal , op_mult , number , [operator , expression] | expression_terminal , op_add , [operator , expression] | expression_terminal , [operator , expression] ; """ self._attempting(text) return alternation([ # number , op_mult , expression concatenation([ self.number, self.op_mult, self.expression ], ignore_whitespace=True), # expression_terminal , op_mult , number , [operator , expression] concatenation([ self.expression_terminal, self.op_mult, self.number, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True), # expression_terminal , op_add , [operator , expression] concatenation([ self.expression_terminal, self.op_add, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True), # expression_terminal , [operator , expression] concatenation([ self.expression_terminal, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True) ])(text).retyped(TokenType.expression)
def expression(self, text): """expression = number , op_mult , expression | expression_terminal , op_mult , number , [operator , expression] | expression_terminal , op_add , [operator , expression] | expression_terminal , [operator , expression] ; """ self._attempting(text) return alternation([ # number , op_mult , expression concatenation([ self.number, self.op_mult, self.expression ], ignore_whitespace=True), # expression_terminal , op_mult , number , [operator , expression] concatenation([ self.expression_terminal, self.op_mult, self.number, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True), # expression_terminal , op_add , [operator , expression] concatenation([ self.expression_terminal, self.op_add, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True), # expression_terminal , [operator , expression] concatenation([ self.expression_terminal, option( concatenation([ self.operator, self.expression ], ignore_whitespace=True) ) ], ignore_whitespace=True) ])(text).retyped(TokenType.expression)
[ "expression", "=", "number", "op_mult", "expression", "|", "expression_terminal", "op_mult", "number", "[", "operator", "expression", "]", "|", "expression_terminal", "op_add", "[", "operator", "expression", "]", "|", "expression_terminal", "[", "operator", "expression", "]", ";" ]
treycucco/pyebnf
python
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L93-L140
[ "def", "expression", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "alternation", "(", "[", "# number , op_mult , expression", "concatenation", "(", "[", "self", ".", "number", ",", "self", ".", "op_mult", ",", "self", ".", "expression", "]", ",", "ignore_whitespace", "=", "True", ")", ",", "# expression_terminal , op_mult , number , [operator , expression]", "concatenation", "(", "[", "self", ".", "expression_terminal", ",", "self", ".", "op_mult", ",", "self", ".", "number", ",", "option", "(", "concatenation", "(", "[", "self", ".", "operator", ",", "self", ".", "expression", "]", ",", "ignore_whitespace", "=", "True", ")", ")", "]", ",", "ignore_whitespace", "=", "True", ")", ",", "# expression_terminal , op_add , [operator , expression]", "concatenation", "(", "[", "self", ".", "expression_terminal", ",", "self", ".", "op_add", ",", "option", "(", "concatenation", "(", "[", "self", ".", "operator", ",", "self", ".", "expression", "]", ",", "ignore_whitespace", "=", "True", ")", ")", "]", ",", "ignore_whitespace", "=", "True", ")", ",", "# expression_terminal , [operator , expression]", "concatenation", "(", "[", "self", ".", "expression_terminal", ",", "option", "(", "concatenation", "(", "[", "self", ".", "operator", ",", "self", ".", "expression", "]", ",", "ignore_whitespace", "=", "True", ")", ")", "]", ",", "ignore_whitespace", "=", "True", ")", "]", ")", "(", "text", ")", ".", "retyped", "(", "TokenType", ".", "expression", ")" ]
3634ddabbe5d73508bcc20f4a591f86a46634e1d
test
Parser.expression_terminal
expression_terminal = identifier | terminal | option_group | repetition_group | grouping_group | special_handling ;
pyebnf/_hand_written_parser.py
def expression_terminal(self, text): """expression_terminal = identifier | terminal | option_group | repetition_group | grouping_group | special_handling ; """ self._attempting(text) return alternation([ self.identifier, self.terminal, self.option_group, self.repetition_group, self.grouping_group, self.special_handling ])(text)
def expression_terminal(self, text): """expression_terminal = identifier | terminal | option_group | repetition_group | grouping_group | special_handling ; """ self._attempting(text) return alternation([ self.identifier, self.terminal, self.option_group, self.repetition_group, self.grouping_group, self.special_handling ])(text)
[ "expression_terminal", "=", "identifier", "|", "terminal", "|", "option_group", "|", "repetition_group", "|", "grouping_group", "|", "special_handling", ";" ]
treycucco/pyebnf
python
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L142-L158
[ "def", "expression_terminal", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "alternation", "(", "[", "self", ".", "identifier", ",", "self", ".", "terminal", ",", "self", ".", "option_group", ",", "self", ".", "repetition_group", ",", "self", ".", "grouping_group", ",", "self", ".", "special_handling", "]", ")", "(", "text", ")" ]
3634ddabbe5d73508bcc20f4a591f86a46634e1d
test
Parser.option_group
option_group = "[" , expression , "]" ;
pyebnf/_hand_written_parser.py
def option_group(self, text): """option_group = "[" , expression , "]" ;""" self._attempting(text) return concatenation([ "[", self.expression, "]" ], ignore_whitespace=True)(text).retyped(TokenType.option_group)
def option_group(self, text): """option_group = "[" , expression , "]" ;""" self._attempting(text) return concatenation([ "[", self.expression, "]" ], ignore_whitespace=True)(text).retyped(TokenType.option_group)
[ "option_group", "=", "[", "expression", "]", ";" ]
treycucco/pyebnf
python
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L160-L167
[ "def", "option_group", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "concatenation", "(", "[", "\"[\"", ",", "self", ".", "expression", ",", "\"]\"", "]", ",", "ignore_whitespace", "=", "True", ")", "(", "text", ")", ".", "retyped", "(", "TokenType", ".", "option_group", ")" ]
3634ddabbe5d73508bcc20f4a591f86a46634e1d
test
Parser.terminal
terminal = '"' . (printable - '"') + . '"' | "'" . (printable - "'") + . "'" ;
pyebnf/_hand_written_parser.py
def terminal(self, text): """terminal = '"' . (printable - '"') + . '"' | "'" . (printable - "'") + . "'" ; """ self._attempting(text) return alternation([ concatenation([ '"', one_or_more( exclusion(self.printable, '"') ), '"' ], ignore_whitespace=False), concatenation([ "'", one_or_more( exclusion(self.printable,"'") ), "'" ], ignore_whitespace=False) ])(text).compressed(TokenType.terminal)
def terminal(self, text): """terminal = '"' . (printable - '"') + . '"' | "'" . (printable - "'") + . "'" ; """ self._attempting(text) return alternation([ concatenation([ '"', one_or_more( exclusion(self.printable, '"') ), '"' ], ignore_whitespace=False), concatenation([ "'", one_or_more( exclusion(self.printable,"'") ), "'" ], ignore_whitespace=False) ])(text).compressed(TokenType.terminal)
[ "terminal", "=", ".", "(", "printable", "-", ")", "+", ".", "|", ".", "(", "printable", "-", ")", "+", ".", ";" ]
treycucco/pyebnf
python
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L204-L224
[ "def", "terminal", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "alternation", "(", "[", "concatenation", "(", "[", "'\"'", ",", "one_or_more", "(", "exclusion", "(", "self", ".", "printable", ",", "'\"'", ")", ")", ",", "'\"'", "]", ",", "ignore_whitespace", "=", "False", ")", ",", "concatenation", "(", "[", "\"'\"", ",", "one_or_more", "(", "exclusion", "(", "self", ".", "printable", ",", "\"'\"", ")", ")", ",", "\"'\"", "]", ",", "ignore_whitespace", "=", "False", ")", "]", ")", "(", "text", ")", ".", "compressed", "(", "TokenType", ".", "terminal", ")" ]
3634ddabbe5d73508bcc20f4a591f86a46634e1d
test
Parser.operator
operator = "|" | "." | "," | "-";
pyebnf/_hand_written_parser.py
def operator(self, text): """operator = "|" | "." | "," | "-";""" self._attempting(text) return alternation([ "|", ".", ",", "-" ])(text).retyped(TokenType.operator)
def operator(self, text): """operator = "|" | "." | "," | "-";""" self._attempting(text) return alternation([ "|", ".", ",", "-" ])(text).retyped(TokenType.operator)
[ "operator", "=", "|", "|", ".", "|", "|", "-", ";" ]
treycucco/pyebnf
python
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L226-L234
[ "def", "operator", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "alternation", "(", "[", "\"|\"", ",", "\".\"", ",", "\",\"", ",", "\"-\"", "]", ")", "(", "text", ")", ".", "retyped", "(", "TokenType", ".", "operator", ")" ]
3634ddabbe5d73508bcc20f4a591f86a46634e1d
test
Parser.op_mult
op_mult = "*" ;
pyebnf/_hand_written_parser.py
def op_mult(self, text): """op_mult = "*" ;""" self._attempting(text) return terminal("*")(text).retyped(TokenType.op_mult)
def op_mult(self, text): """op_mult = "*" ;""" self._attempting(text) return terminal("*")(text).retyped(TokenType.op_mult)
[ "op_mult", "=", "*", ";" ]
treycucco/pyebnf
python
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L236-L239
[ "def", "op_mult", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "terminal", "(", "\"*\"", ")", "(", "text", ")", ".", "retyped", "(", "TokenType", ".", "op_mult", ")" ]
3634ddabbe5d73508bcc20f4a591f86a46634e1d
test
Parser.op_add
op_add = "+" ;
pyebnf/_hand_written_parser.py
def op_add(self, text): """op_add = "+" ;""" self._attempting(text) return terminal("+")(text).retyped(TokenType.op_add)
def op_add(self, text): """op_add = "+" ;""" self._attempting(text) return terminal("+")(text).retyped(TokenType.op_add)
[ "op_add", "=", "+", ";" ]
treycucco/pyebnf
python
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L241-L244
[ "def", "op_add", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "terminal", "(", "\"+\"", ")", "(", "text", ")", ".", "retyped", "(", "TokenType", ".", "op_add", ")" ]
3634ddabbe5d73508bcc20f4a591f86a46634e1d
test
Model.setp
Set the value (and bounds) of the named parameter. Parameters ---------- name : str The parameter name. clear_derived : bool Flag to clear derived objects in this model value: The value of the parameter, if None, it is not changed bounds: tuple or None The bounds on the parameter, if None, they are not set free : bool or None Flag to say if parameter is fixed or free in fitting, if None, it is not changed errors : tuple or None Uncertainties on the parameter, if None, they are not changed
pymodeler/model.py
def setp(self, name, clear_derived=True, value=None, bounds=None, free=None, errors=None): """ Set the value (and bounds) of the named parameter. Parameters ---------- name : str The parameter name. clear_derived : bool Flag to clear derived objects in this model value: The value of the parameter, if None, it is not changed bounds: tuple or None The bounds on the parameter, if None, they are not set free : bool or None Flag to say if parameter is fixed or free in fitting, if None, it is not changed errors : tuple or None Uncertainties on the parameter, if None, they are not changed """ name = self._mapping.get(name, name) try: self.params[name].set( value=value, bounds=bounds, free=free, errors=errors) except TypeError as msg: print(msg, name) if clear_derived: self.clear_derived() self._cache(name)
def setp(self, name, clear_derived=True, value=None, bounds=None, free=None, errors=None): """ Set the value (and bounds) of the named parameter. Parameters ---------- name : str The parameter name. clear_derived : bool Flag to clear derived objects in this model value: The value of the parameter, if None, it is not changed bounds: tuple or None The bounds on the parameter, if None, they are not set free : bool or None Flag to say if parameter is fixed or free in fitting, if None, it is not changed errors : tuple or None Uncertainties on the parameter, if None, they are not changed """ name = self._mapping.get(name, name) try: self.params[name].set( value=value, bounds=bounds, free=free, errors=errors) except TypeError as msg: print(msg, name) if clear_derived: self.clear_derived() self._cache(name)
[ "Set", "the", "value", "(", "and", "bounds", ")", "of", "the", "named", "parameter", "." ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L222-L256
[ "def", "setp", "(", "self", ",", "name", ",", "clear_derived", "=", "True", ",", "value", "=", "None", ",", "bounds", "=", "None", ",", "free", "=", "None", ",", "errors", "=", "None", ")", ":", "name", "=", "self", ".", "_mapping", ".", "get", "(", "name", ",", "name", ")", "try", ":", "self", ".", "params", "[", "name", "]", ".", "set", "(", "value", "=", "value", ",", "bounds", "=", "bounds", ",", "free", "=", "free", ",", "errors", "=", "errors", ")", "except", "TypeError", "as", "msg", ":", "print", "(", "msg", ",", "name", ")", "if", "clear_derived", ":", "self", ".", "clear_derived", "(", ")", "self", ".", "_cache", "(", "name", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Model.set_attributes
Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.).
pymodeler/model.py
def set_attributes(self, **kwargs): """ Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.). """ self.clear_derived() kwargs = dict(kwargs) for name, value in kwargs.items(): # Raise AttributeError if param not found try: self.getp(name) except KeyError: print ("Warning: %s does not have attribute %s" % (type(self), name)) # Set attributes try: self.setp(name, clear_derived=False, **value) except TypeError: try: self.setp(name, clear_derived=False, *value) except (TypeError, KeyError): try: self.setp(name, clear_derived=False, value=value) except (TypeError, KeyError): self.__setattr__(name, value) # pop this attribued off the list of missing properties self._missing.pop(name, None) # Check to make sure we got all the required properties if self._missing: raise ValueError( "One or more required properties are missing ", self._missing.keys())
def set_attributes(self, **kwargs): """ Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.). """ self.clear_derived() kwargs = dict(kwargs) for name, value in kwargs.items(): # Raise AttributeError if param not found try: self.getp(name) except KeyError: print ("Warning: %s does not have attribute %s" % (type(self), name)) # Set attributes try: self.setp(name, clear_derived=False, **value) except TypeError: try: self.setp(name, clear_derived=False, *value) except (TypeError, KeyError): try: self.setp(name, clear_derived=False, value=value) except (TypeError, KeyError): self.__setattr__(name, value) # pop this attribued off the list of missing properties self._missing.pop(name, None) # Check to make sure we got all the required properties if self._missing: raise ValueError( "One or more required properties are missing ", self._missing.keys())
[ "Set", "a", "group", "of", "attributes", "(", "parameters", "and", "members", ")", ".", "Calls", "setp", "directly", "so", "kwargs", "can", "include", "more", "than", "just", "the", "parameter", "value", "(", "e", ".", "g", ".", "bounds", "free", "etc", ".", ")", "." ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L258-L290
[ "def", "set_attributes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "clear_derived", "(", ")", "kwargs", "=", "dict", "(", "kwargs", ")", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "# Raise AttributeError if param not found", "try", ":", "self", ".", "getp", "(", "name", ")", "except", "KeyError", ":", "print", "(", "\"Warning: %s does not have attribute %s\"", "%", "(", "type", "(", "self", ")", ",", "name", ")", ")", "# Set attributes", "try", ":", "self", ".", "setp", "(", "name", ",", "clear_derived", "=", "False", ",", "*", "*", "value", ")", "except", "TypeError", ":", "try", ":", "self", ".", "setp", "(", "name", ",", "clear_derived", "=", "False", ",", "*", "value", ")", "except", "(", "TypeError", ",", "KeyError", ")", ":", "try", ":", "self", ".", "setp", "(", "name", ",", "clear_derived", "=", "False", ",", "value", "=", "value", ")", "except", "(", "TypeError", ",", "KeyError", ")", ":", "self", ".", "__setattr__", "(", "name", ",", "value", ")", "# pop this attribued off the list of missing properties", "self", ".", "_missing", ".", "pop", "(", "name", ",", "None", ")", "# Check to make sure we got all the required properties", "if", "self", ".", "_missing", ":", "raise", "ValueError", "(", "\"One or more required properties are missing \"", ",", "self", ".", "_missing", ".", "keys", "(", ")", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Model._init_properties
Loop through the list of Properties, extract the derived and required properties and do the appropriate book-keeping
pymodeler/model.py
def _init_properties(self): """ Loop through the list of Properties, extract the derived and required properties and do the appropriate book-keeping """ self._missing = {} for k, p in self.params.items(): if p.required: self._missing[k] = p if isinstance(p, Derived): if p.loader is None: # Default to using _<param_name> p.loader = self.__getattribute__("_%s" % k) elif isinstance(p.loader, str): p.loader = self.__getattribute__(p.loader)
def _init_properties(self): """ Loop through the list of Properties, extract the derived and required properties and do the appropriate book-keeping """ self._missing = {} for k, p in self.params.items(): if p.required: self._missing[k] = p if isinstance(p, Derived): if p.loader is None: # Default to using _<param_name> p.loader = self.__getattribute__("_%s" % k) elif isinstance(p.loader, str): p.loader = self.__getattribute__(p.loader)
[ "Loop", "through", "the", "list", "of", "Properties", "extract", "the", "derived", "and", "required", "properties", "and", "do", "the", "appropriate", "book", "-", "keeping" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L292-L306
[ "def", "_init_properties", "(", "self", ")", ":", "self", ".", "_missing", "=", "{", "}", "for", "k", ",", "p", "in", "self", ".", "params", ".", "items", "(", ")", ":", "if", "p", ".", "required", ":", "self", ".", "_missing", "[", "k", "]", "=", "p", "if", "isinstance", "(", "p", ",", "Derived", ")", ":", "if", "p", ".", "loader", "is", "None", ":", "# Default to using _<param_name>", "p", ".", "loader", "=", "self", ".", "__getattribute__", "(", "\"_%s\"", "%", "k", ")", "elif", "isinstance", "(", "p", ".", "loader", ",", "str", ")", ":", "p", ".", "loader", "=", "self", ".", "__getattribute__", "(", "p", ".", "loader", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Model.get_params
Return a list of Parameter objects Parameters ---------- pname : list or None If a list get the Parameter objects with those names If none, get all the Parameter objects Returns ------- params : list list of Parameters
pymodeler/model.py
def get_params(self, pnames=None): """ Return a list of Parameter objects Parameters ---------- pname : list or None If a list get the Parameter objects with those names If none, get all the Parameter objects Returns ------- params : list list of Parameters """ l = [] if pnames is None: pnames = self.params.keys() for pname in pnames: p = self.params[pname] if isinstance(p, Parameter): l.append(p) return l
def get_params(self, pnames=None): """ Return a list of Parameter objects Parameters ---------- pname : list or None If a list get the Parameter objects with those names If none, get all the Parameter objects Returns ------- params : list list of Parameters """ l = [] if pnames is None: pnames = self.params.keys() for pname in pnames: p = self.params[pname] if isinstance(p, Parameter): l.append(p) return l
[ "Return", "a", "list", "of", "Parameter", "objects" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L308-L333
[ "def", "get_params", "(", "self", ",", "pnames", "=", "None", ")", ":", "l", "=", "[", "]", "if", "pnames", "is", "None", ":", "pnames", "=", "self", ".", "params", ".", "keys", "(", ")", "for", "pname", "in", "pnames", ":", "p", "=", "self", ".", "params", "[", "pname", "]", "if", "isinstance", "(", "p", ",", "Parameter", ")", ":", "l", ".", "append", "(", "p", ")", "return", "l" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Model.param_values
Return an array with the parameter values Parameters ---------- pname : list or None If a list, get the values of the `Parameter` objects with those names If none, get all values of all the `Parameter` objects Returns ------- values : `np.array` Parameter values
pymodeler/model.py
def param_values(self, pnames=None): """ Return an array with the parameter values Parameters ---------- pname : list or None If a list, get the values of the `Parameter` objects with those names If none, get all values of all the `Parameter` objects Returns ------- values : `np.array` Parameter values """ l = self.get_params(pnames) v = [p.value for p in l] return np.array(v)
def param_values(self, pnames=None): """ Return an array with the parameter values Parameters ---------- pname : list or None If a list, get the values of the `Parameter` objects with those names If none, get all values of all the `Parameter` objects Returns ------- values : `np.array` Parameter values """ l = self.get_params(pnames) v = [p.value for p in l] return np.array(v)
[ "Return", "an", "array", "with", "the", "parameter", "values" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L335-L355
[ "def", "param_values", "(", "self", ",", "pnames", "=", "None", ")", ":", "l", "=", "self", ".", "get_params", "(", "pnames", ")", "v", "=", "[", "p", ".", "value", "for", "p", "in", "l", "]", "return", "np", ".", "array", "(", "v", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Model.param_errors
Return an array with the parameter errors Parameters ---------- pname : list of string or none If a list of strings, get the Parameter objects with those names If none, get all the Parameter objects Returns ------- ~numpy.array of parameter errors Note that this is a N x 2 array.
pymodeler/model.py
def param_errors(self, pnames=None): """ Return an array with the parameter errors Parameters ---------- pname : list of string or none If a list of strings, get the Parameter objects with those names If none, get all the Parameter objects Returns ------- ~numpy.array of parameter errors Note that this is a N x 2 array. """ l = self.get_params(pnames) v = [p.errors for p in l] return np.array(v)
def param_errors(self, pnames=None): """ Return an array with the parameter errors Parameters ---------- pname : list of string or none If a list of strings, get the Parameter objects with those names If none, get all the Parameter objects Returns ------- ~numpy.array of parameter errors Note that this is a N x 2 array. """ l = self.get_params(pnames) v = [p.errors for p in l] return np.array(v)
[ "Return", "an", "array", "with", "the", "parameter", "errors" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L357-L375
[ "def", "param_errors", "(", "self", ",", "pnames", "=", "None", ")", ":", "l", "=", "self", ".", "get_params", "(", "pnames", ")", "v", "=", "[", "p", ".", "errors", "for", "p", "in", "l", "]", "return", "np", ".", "array", "(", "v", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
Model.clear_derived
Reset the value of all Derived properties to None This is called by setp (and by extension __setattr__)
pymodeler/model.py
def clear_derived(self): """ Reset the value of all Derived properties to None This is called by setp (and by extension __setattr__) """ for p in self.params.values(): if isinstance(p, Derived): p.clear_value()
def clear_derived(self): """ Reset the value of all Derived properties to None This is called by setp (and by extension __setattr__) """ for p in self.params.values(): if isinstance(p, Derived): p.clear_value()
[ "Reset", "the", "value", "of", "all", "Derived", "properties", "to", "None" ]
kadrlica/pymodeler
python
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L377-L384
[ "def", "clear_derived", "(", "self", ")", ":", "for", "p", "in", "self", ".", "params", ".", "values", "(", ")", ":", "if", "isinstance", "(", "p", ",", "Derived", ")", ":", "p", ".", "clear_value", "(", ")" ]
f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3
test
PluginGetComponents.get_arguments
Extracts the specific arguments of this CLI
boundary/plugin_get_components.py
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.pluginName is not None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName)
def get_arguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.get_arguments(self) if self.args.pluginName is not None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName)
[ "Extracts", "the", "specific", "arguments", "of", "this", "CLI" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/plugin_get_components.py#L31-L39
[ "def", "get_arguments", "(", "self", ")", ":", "ApiCli", ".", "get_arguments", "(", "self", ")", "if", "self", ".", "args", ".", "pluginName", "is", "not", "None", ":", "self", ".", "pluginName", "=", "self", ".", "args", ".", "pluginName", "self", ".", "path", "=", "\"v1/plugins/{0}/components\"", ".", "format", "(", "self", ".", "pluginName", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall.method
Before assigning the value validate that is in one of the HTTP methods we implement
boundary/api_call.py
def method(self, value): """ Before assigning the value validate that is in one of the HTTP methods we implement """ keys = self._methods.keys() if value not in keys: raise AttributeError("Method value not in " + str(keys)) else: self._method = value
def method(self, value): """ Before assigning the value validate that is in one of the HTTP methods we implement """ keys = self._methods.keys() if value not in keys: raise AttributeError("Method value not in " + str(keys)) else: self._method = value
[ "Before", "assigning", "the", "value", "validate", "that", "is", "in", "one", "of", "the", "HTTP", "methods", "we", "implement" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L111-L120
[ "def", "method", "(", "self", ",", "value", ")", ":", "keys", "=", "self", ".", "_methods", ".", "keys", "(", ")", "if", "value", "not", "in", "keys", ":", "raise", "AttributeError", "(", "\"Method value not in \"", "+", "str", "(", "keys", ")", ")", "else", ":", "self", ".", "_method", "=", "value" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall._get_environment
Gets the configuration stored in environment variables
boundary/api_call.py
def _get_environment(self): """ Gets the configuration stored in environment variables """ if 'TSP_EMAIL' in os.environ: self._email = os.environ['TSP_EMAIL'] if 'TSP_API_TOKEN' in os.environ: self._api_token = os.environ['TSP_API_TOKEN'] if 'TSP_API_HOST' in os.environ: self._api_host = os.environ['TSP_API_HOST'] else: self._api_host = 'api.truesight.bmc.com'
def _get_environment(self): """ Gets the configuration stored in environment variables """ if 'TSP_EMAIL' in os.environ: self._email = os.environ['TSP_EMAIL'] if 'TSP_API_TOKEN' in os.environ: self._api_token = os.environ['TSP_API_TOKEN'] if 'TSP_API_HOST' in os.environ: self._api_host = os.environ['TSP_API_HOST'] else: self._api_host = 'api.truesight.bmc.com'
[ "Gets", "the", "configuration", "stored", "in", "environment", "variables" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L146-L157
[ "def", "_get_environment", "(", "self", ")", ":", "if", "'TSP_EMAIL'", "in", "os", ".", "environ", ":", "self", ".", "_email", "=", "os", ".", "environ", "[", "'TSP_EMAIL'", "]", "if", "'TSP_API_TOKEN'", "in", "os", ".", "environ", ":", "self", ".", "_api_token", "=", "os", ".", "environ", "[", "'TSP_API_TOKEN'", "]", "if", "'TSP_API_HOST'", "in", "os", ".", "environ", ":", "self", ".", "_api_host", "=", "os", ".", "environ", "[", "'TSP_API_HOST'", "]", "else", ":", "self", ".", "_api_host", "=", "'api.truesight.bmc.com'" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall._get_url_parameters
Encode URL parameters
boundary/api_call.py
def _get_url_parameters(self): """ Encode URL parameters """ url_parameters = '' if self._url_parameters is not None: url_parameters = '?' + urllib.urlencode(self._url_parameters) return url_parameters
def _get_url_parameters(self): """ Encode URL parameters """ url_parameters = '' if self._url_parameters is not None: url_parameters = '?' + urllib.urlencode(self._url_parameters) return url_parameters
[ "Encode", "URL", "parameters" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L159-L166
[ "def", "_get_url_parameters", "(", "self", ")", ":", "url_parameters", "=", "''", "if", "self", ".", "_url_parameters", "is", "not", "None", ":", "url_parameters", "=", "'?'", "+", "urllib", ".", "urlencode", "(", "self", ".", "_url_parameters", ")", "return", "url_parameters" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall.metric_get
Returns a metric definition identified by name :param enabled: Return only enabled metrics :param custom: Return only custom metrics :return Metrics:
boundary/api_call.py
def metric_get(self, enabled=False, custom=False): """ Returns a metric definition identified by name :param enabled: Return only enabled metrics :param custom: Return only custom metrics :return Metrics: """ self.path = 'v1/metrics?enabled={0}&{1}'.format(enabled, custom) self._call_api() self._handle_results() return self.metrics
def metric_get(self, enabled=False, custom=False): """ Returns a metric definition identified by name :param enabled: Return only enabled metrics :param custom: Return only custom metrics :return Metrics: """ self.path = 'v1/metrics?enabled={0}&{1}'.format(enabled, custom) self._call_api() self._handle_results() return self.metrics
[ "Returns", "a", "metric", "definition", "identified", "by", "name", ":", "param", "enabled", ":", "Return", "only", "enabled", "metrics", ":", "param", "custom", ":", "Return", "only", "custom", "metrics", ":", "return", "Metrics", ":" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L168-L178
[ "def", "metric_get", "(", "self", ",", "enabled", "=", "False", ",", "custom", "=", "False", ")", ":", "self", ".", "path", "=", "'v1/metrics?enabled={0}&{1}'", ".", "format", "(", "enabled", ",", "custom", ")", "self", ".", "_call_api", "(", ")", "self", ".", "_handle_results", "(", ")", "return", "self", ".", "metrics" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall._do_get
HTTP Get Request
boundary/api_call.py
def _do_get(self): """ HTTP Get Request """ return requests.get(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
def _do_get(self): """ HTTP Get Request """ return requests.get(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
[ "HTTP", "Get", "Request" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L186-L190
[ "def", "_do_get", "(", "self", ")", ":", "return", "requests", ".", "get", "(", "self", ".", "_url", ",", "data", "=", "self", ".", "_data", ",", "headers", "=", "self", ".", "_headers", ",", "auth", "=", "(", "self", ".", "_email", ",", "self", ".", "_api_token", ")", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall._do_delete
HTTP Delete Request
boundary/api_call.py
def _do_delete(self): """ HTTP Delete Request """ return requests.delete(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
def _do_delete(self): """ HTTP Delete Request """ return requests.delete(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
[ "HTTP", "Delete", "Request" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L192-L196
[ "def", "_do_delete", "(", "self", ")", ":", "return", "requests", ".", "delete", "(", "self", ".", "_url", ",", "data", "=", "self", ".", "_data", ",", "headers", "=", "self", ".", "_headers", ",", "auth", "=", "(", "self", ".", "_email", ",", "self", ".", "_api_token", ")", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall._do_post
HTTP Post Request
boundary/api_call.py
def _do_post(self): """ HTTP Post Request """ return requests.post(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
def _do_post(self): """ HTTP Post Request """ return requests.post(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
[ "HTTP", "Post", "Request" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L198-L202
[ "def", "_do_post", "(", "self", ")", ":", "return", "requests", ".", "post", "(", "self", ".", "_url", ",", "data", "=", "self", ".", "_data", ",", "headers", "=", "self", ".", "_headers", ",", "auth", "=", "(", "self", ".", "_email", ",", "self", ".", "_api_token", ")", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall._do_put
HTTP Put Request
boundary/api_call.py
def _do_put(self): """ HTTP Put Request """ return requests.put(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
def _do_put(self): """ HTTP Put Request """ return requests.put(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
[ "HTTP", "Put", "Request" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L204-L208
[ "def", "_do_put", "(", "self", ")", ":", "return", "requests", ".", "put", "(", "self", ".", "_url", ",", "data", "=", "self", ".", "_data", ",", "headers", "=", "self", ".", "_headers", ",", "auth", "=", "(", "self", ".", "_email", ",", "self", ".", "_api_token", ")", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
ApiCall._call_api
Make an API call to get the metric definition
boundary/api_call.py
def _call_api(self): """ Make an API call to get the metric definition """ self._url = self.form_url() if self._headers is not None: logging.debug(self._headers) if self._data is not None: logging.debug(self._data) if len(self._get_url_parameters()) > 0: logging.debug(self._get_url_parameters()) result = self._methods[self._method]() if not self.good_response(result.status_code): logging.error(self._url) logging.error(self._method) if self._data is not None: logging.error(self._data) logging.error(result) self._api_result = result
def _call_api(self): """ Make an API call to get the metric definition """ self._url = self.form_url() if self._headers is not None: logging.debug(self._headers) if self._data is not None: logging.debug(self._data) if len(self._get_url_parameters()) > 0: logging.debug(self._get_url_parameters()) result = self._methods[self._method]() if not self.good_response(result.status_code): logging.error(self._url) logging.error(self._method) if self._data is not None: logging.error(self._data) logging.error(result) self._api_result = result
[ "Make", "an", "API", "call", "to", "get", "the", "metric", "definition" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L241-L262
[ "def", "_call_api", "(", "self", ")", ":", "self", ".", "_url", "=", "self", ".", "form_url", "(", ")", "if", "self", ".", "_headers", "is", "not", "None", ":", "logging", ".", "debug", "(", "self", ".", "_headers", ")", "if", "self", ".", "_data", "is", "not", "None", ":", "logging", ".", "debug", "(", "self", ".", "_data", ")", "if", "len", "(", "self", ".", "_get_url_parameters", "(", ")", ")", ">", "0", ":", "logging", ".", "debug", "(", "self", ".", "_get_url_parameters", "(", ")", ")", "result", "=", "self", ".", "_methods", "[", "self", ".", "_method", "]", "(", ")", "if", "not", "self", ".", "good_response", "(", "result", ".", "status_code", ")", ":", "logging", ".", "error", "(", "self", ".", "_url", ")", "logging", ".", "error", "(", "self", ".", "_method", ")", "if", "self", ".", "_data", "is", "not", "None", ":", "logging", ".", "error", "(", "self", ".", "_data", ")", "logging", ".", "error", "(", "result", ")", "self", ".", "_api_result", "=", "result" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
MeasurementPlot.get_arguments
Extracts the specific arguments of this CLI
boundary/measurement_plot.py
def get_arguments(self): """ Extracts the specific arguments of this CLI """ # ApiCli.get_arguments(self) if self.args.file_name is not None: self.file_name = self.args.file_name
def get_arguments(self): """ Extracts the specific arguments of this CLI """ # ApiCli.get_arguments(self) if self.args.file_name is not None: self.file_name = self.args.file_name
[ "Extracts", "the", "specific", "arguments", "of", "this", "CLI" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/measurement_plot.py#L115-L121
[ "def", "get_arguments", "(", "self", ")", ":", "# ApiCli.get_arguments(self)", "if", "self", ".", "args", ".", "file_name", "is", "not", "None", ":", "self", ".", "file_name", "=", "self", ".", "args", ".", "file_name" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
MeasurementPlot.execute
Run the steps to execute the CLI
boundary/measurement_plot.py
def execute(self): """ Run the steps to execute the CLI """ # self._get_environment() self.add_arguments() self._parse_args() self.get_arguments() if self._validate_arguments(): self._plot_data() else: print(self._message)
def execute(self): """ Run the steps to execute the CLI """ # self._get_environment() self.add_arguments() self._parse_args() self.get_arguments() if self._validate_arguments(): self._plot_data() else: print(self._message)
[ "Run", "the", "steps", "to", "execute", "the", "CLI" ]
boundary/pulse-api-cli
python
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/measurement_plot.py#L169-L180
[ "def", "execute", "(", "self", ")", ":", "# self._get_environment()", "self", ".", "add_arguments", "(", ")", "self", ".", "_parse_args", "(", ")", "self", ".", "get_arguments", "(", ")", "if", "self", ".", "_validate_arguments", "(", ")", ":", "self", ".", "_plot_data", "(", ")", "else", ":", "print", "(", "self", ".", "_message", ")" ]
b01ca65b442eed19faac309c9d62bbc3cb2c098f
test
USGSDownload.validate_sceneInfo
Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong.
usgsdownload/usgs.py
def validate_sceneInfo(self): """Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong. """ if self.sceneInfo.prefix not in self.__satellitesMap: raise WrongSceneNameError('USGS Downloader: Prefix of %s (%s) is invalid' % (self.sceneInfo.name, self.sceneInfo.prefix))
def validate_sceneInfo(self): """Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong. """ if self.sceneInfo.prefix not in self.__satellitesMap: raise WrongSceneNameError('USGS Downloader: Prefix of %s (%s) is invalid' % (self.sceneInfo.name, self.sceneInfo.prefix))
[ "Check", "scene", "name", "and", "whether", "remote", "file", "exists", ".", "Raises", "WrongSceneNameError", "if", "the", "scene", "name", "is", "wrong", "." ]
lucaslamounier/USGSDownload
python
https://github.com/lucaslamounier/USGSDownload/blob/0969483ea9f9648aa17b099f36d2e1010488b2a4/usgsdownload/usgs.py#L86-L92
[ "def", "validate_sceneInfo", "(", "self", ")", ":", "if", "self", ".", "sceneInfo", ".", "prefix", "not", "in", "self", ".", "__satellitesMap", ":", "raise", "WrongSceneNameError", "(", "'USGS Downloader: Prefix of %s (%s) is invalid'", "%", "(", "self", ".", "sceneInfo", ".", "name", ",", "self", ".", "sceneInfo", ".", "prefix", ")", ")" ]
0969483ea9f9648aa17b099f36d2e1010488b2a4
test
USGSDownload.verify_type_product
Gets satellite id
usgsdownload/usgs.py
def verify_type_product(self, satellite): """Gets satellite id """ if satellite == 'L5': id_satellite = '3119' stations = ['GLC', 'ASA', 'KIR', 'MOR', 'KHC', 'PAC', 'KIS', 'CHM', 'LGS', 'MGR', 'COA', 'MPS'] elif satellite == 'L7': id_satellite = '3373' stations = ['EDC', 'SGS', 'AGS', 'ASN', 'SG1'] elif satellite == 'L8': id_satellite = '4923' stations = ['LGN'] else: raise ProductInvalidError('Type product invalid. the permitted types are: L5, L7, L8. ') typ_product = dict(id_satelite=id_satellite, stations=stations) return typ_product
def verify_type_product(self, satellite): """Gets satellite id """ if satellite == 'L5': id_satellite = '3119' stations = ['GLC', 'ASA', 'KIR', 'MOR', 'KHC', 'PAC', 'KIS', 'CHM', 'LGS', 'MGR', 'COA', 'MPS'] elif satellite == 'L7': id_satellite = '3373' stations = ['EDC', 'SGS', 'AGS', 'ASN', 'SG1'] elif satellite == 'L8': id_satellite = '4923' stations = ['LGN'] else: raise ProductInvalidError('Type product invalid. the permitted types are: L5, L7, L8. ') typ_product = dict(id_satelite=id_satellite, stations=stations) return typ_product
[ "Gets", "satellite", "id" ]
lucaslamounier/USGSDownload
python
https://github.com/lucaslamounier/USGSDownload/blob/0969483ea9f9648aa17b099f36d2e1010488b2a4/usgsdownload/usgs.py#L98-L112
[ "def", "verify_type_product", "(", "self", ",", "satellite", ")", ":", "if", "satellite", "==", "'L5'", ":", "id_satellite", "=", "'3119'", "stations", "=", "[", "'GLC'", ",", "'ASA'", ",", "'KIR'", ",", "'MOR'", ",", "'KHC'", ",", "'PAC'", ",", "'KIS'", ",", "'CHM'", ",", "'LGS'", ",", "'MGR'", ",", "'COA'", ",", "'MPS'", "]", "elif", "satellite", "==", "'L7'", ":", "id_satellite", "=", "'3373'", "stations", "=", "[", "'EDC'", ",", "'SGS'", ",", "'AGS'", ",", "'ASN'", ",", "'SG1'", "]", "elif", "satellite", "==", "'L8'", ":", "id_satellite", "=", "'4923'", "stations", "=", "[", "'LGN'", "]", "else", ":", "raise", "ProductInvalidError", "(", "'Type product invalid. the permitted types are: L5, L7, L8. '", ")", "typ_product", "=", "dict", "(", "id_satelite", "=", "id_satellite", ",", "stations", "=", "stations", ")", "return", "typ_product" ]
0969483ea9f9648aa17b099f36d2e1010488b2a4