repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase._readline_insert
def _readline_insert(self, char, echo, insptr, line): """Deal properly with inserted chars in a line.""" if not self._readline_do_echo(echo): return # Write out the remainder of the line self.write(char + ''.join(line[insptr:])) # Cursor Left to the current insert point char_count = len(line) - insptr self.write(self.CODES['CSRLEFT'] * char_count)
python
def _readline_insert(self, char, echo, insptr, line): """Deal properly with inserted chars in a line.""" if not self._readline_do_echo(echo): return # Write out the remainder of the line self.write(char + ''.join(line[insptr:])) # Cursor Left to the current insert point char_count = len(line) - insptr self.write(self.CODES['CSRLEFT'] * char_count)
[ "def", "_readline_insert", "(", "self", ",", "char", ",", "echo", ",", "insptr", ",", "line", ")", ":", "if", "not", "self", ".", "_readline_do_echo", "(", "echo", ")", ":", "return", "# Write out the remainder of the line", "self", ".", "write", "(", "char", "+", "''", ".", "join", "(", "line", "[", "insptr", ":", "]", ")", ")", "# Cursor Left to the current insert point", "char_count", "=", "len", "(", "line", ")", "-", "insptr", "self", ".", "write", "(", "self", ".", "CODES", "[", "'CSRLEFT'", "]", "*", "char_count", ")" ]
Deal properly with inserted chars in a line.
[ "Deal", "properly", "with", "inserted", "chars", "in", "a", "line", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L624-L632
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.ansi_to_curses
def ansi_to_curses(self, char): '''Handles reading ANSI escape sequences''' # ANSI sequences are: # ESC [ <key> # If we see ESC, read a char if char != ESC: return char # If we see [, read another char if self.getc(block=True) != ANSI_START_SEQ: self._readline_echo(BELL, True) return theNULL key = self.getc(block=True) # Translate the key to curses try: return ANSI_KEY_TO_CURSES[key] except: self._readline_echo(BELL, True) return theNULL
python
def ansi_to_curses(self, char): '''Handles reading ANSI escape sequences''' # ANSI sequences are: # ESC [ <key> # If we see ESC, read a char if char != ESC: return char # If we see [, read another char if self.getc(block=True) != ANSI_START_SEQ: self._readline_echo(BELL, True) return theNULL key = self.getc(block=True) # Translate the key to curses try: return ANSI_KEY_TO_CURSES[key] except: self._readline_echo(BELL, True) return theNULL
[ "def", "ansi_to_curses", "(", "self", ",", "char", ")", ":", "# ANSI sequences are:", "# ESC [ <key>", "# If we see ESC, read a char", "if", "char", "!=", "ESC", ":", "return", "char", "# If we see [, read another char", "if", "self", ".", "getc", "(", "block", "=", "True", ")", "!=", "ANSI_START_SEQ", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "True", ")", "return", "theNULL", "key", "=", "self", ".", "getc", "(", "block", "=", "True", ")", "# Translate the key to curses", "try", ":", "return", "ANSI_KEY_TO_CURSES", "[", "key", "]", "except", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "True", ")", "return", "theNULL" ]
Handles reading ANSI escape sequences
[ "Handles", "reading", "ANSI", "escape", "sequences" ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L637-L654
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.readline
def readline(self, echo=None, prompt='', use_history=True): """Return a line of text, including the terminating LF If echo is true always echo, if echo is false never echo If echo is None follow the negotiated setting. prompt is the current prompt to write (and rewrite if needed) use_history controls if this current line uses (and adds to) the command history. """ line = [] insptr = 0 ansi = 0 histptr = len(self.history) if self.DOECHO: self.write(prompt) self._current_prompt = prompt else: self._current_prompt = '' self._current_line = '' while True: c = self.getc(block=True) c = self.ansi_to_curses(c) if c == theNULL: continue elif c == curses.KEY_LEFT: if insptr > 0: insptr = insptr - 1 self._readline_echo(self.CODES['CSRLEFT'], echo) else: self._readline_echo(BELL, echo) continue elif c == curses.KEY_RIGHT: if insptr < len(line): insptr = insptr + 1 self._readline_echo(self.CODES['CSRRIGHT'], echo) else: self._readline_echo(BELL, echo) continue elif c == curses.KEY_UP or c == curses.KEY_DOWN: if not use_history: self._readline_echo(BELL, echo) continue if c == curses.KEY_UP: if histptr > 0: histptr = histptr - 1 else: self._readline_echo(BELL, echo) continue elif c == curses.KEY_DOWN: if histptr < len(self.history): histptr = histptr + 1 else: self._readline_echo(BELL, echo) continue line = [] if histptr < len(self.history): line.extend(self.history[histptr]) for char in range(insptr): self._readline_echo(self.CODES['CSRLEFT'], echo) self._readline_echo(self.CODES['DEOL'], echo) self._readline_echo(''.join(line), echo) insptr = len(line) continue elif c == chr(3): self._readline_echo('\n' + curses.ascii.unctrl(c) + ' ABORT\n', echo) return '' elif c == chr(4): if len(line) > 0: self._readline_echo('\n' + curses.ascii.unctrl(c) + ' ABORT (QUIT)\n', echo) return '' self._readline_echo('\n' + curses.ascii.unctrl(c) + ' QUIT\n', echo) return 'QUIT' elif c == chr(10): self._readline_echo(c, echo) result = ''.join(line) if use_history: self.history.append(result) if echo is False: if prompt: self.write( chr(10) ) log.debug('readline: %s(hidden text)', prompt) else: log.debug('readline: %s%r', prompt, result) return result elif c == curses.KEY_BACKSPACE or c == chr(127) or c == chr(8): if insptr > 0: self._readline_echo(self.CODES['CSRLEFT'] + self.CODES['DEL'], echo) insptr = insptr - 1 del line[insptr] else: self._readline_echo(BELL, echo) continue elif c == curses.KEY_DC: if insptr < len(line): self._readline_echo(self.CODES['DEL'], echo) del line[insptr] else: self._readline_echo(BELL, echo) continue else: if ord(c) < 32: c = curses.ascii.unctrl(c) if len(line) > insptr: self._readline_insert(c, echo, insptr, line) else: self._readline_echo(c, echo) line[insptr:insptr] = c insptr = insptr + len(c) if self._readline_do_echo(echo): self._current_line = line
python
def readline(self, echo=None, prompt='', use_history=True): """Return a line of text, including the terminating LF If echo is true always echo, if echo is false never echo If echo is None follow the negotiated setting. prompt is the current prompt to write (and rewrite if needed) use_history controls if this current line uses (and adds to) the command history. """ line = [] insptr = 0 ansi = 0 histptr = len(self.history) if self.DOECHO: self.write(prompt) self._current_prompt = prompt else: self._current_prompt = '' self._current_line = '' while True: c = self.getc(block=True) c = self.ansi_to_curses(c) if c == theNULL: continue elif c == curses.KEY_LEFT: if insptr > 0: insptr = insptr - 1 self._readline_echo(self.CODES['CSRLEFT'], echo) else: self._readline_echo(BELL, echo) continue elif c == curses.KEY_RIGHT: if insptr < len(line): insptr = insptr + 1 self._readline_echo(self.CODES['CSRRIGHT'], echo) else: self._readline_echo(BELL, echo) continue elif c == curses.KEY_UP or c == curses.KEY_DOWN: if not use_history: self._readline_echo(BELL, echo) continue if c == curses.KEY_UP: if histptr > 0: histptr = histptr - 1 else: self._readline_echo(BELL, echo) continue elif c == curses.KEY_DOWN: if histptr < len(self.history): histptr = histptr + 1 else: self._readline_echo(BELL, echo) continue line = [] if histptr < len(self.history): line.extend(self.history[histptr]) for char in range(insptr): self._readline_echo(self.CODES['CSRLEFT'], echo) self._readline_echo(self.CODES['DEOL'], echo) self._readline_echo(''.join(line), echo) insptr = len(line) continue elif c == chr(3): self._readline_echo('\n' + curses.ascii.unctrl(c) + ' ABORT\n', echo) return '' elif c == chr(4): if len(line) > 0: self._readline_echo('\n' + curses.ascii.unctrl(c) + ' ABORT (QUIT)\n', echo) return '' self._readline_echo('\n' + curses.ascii.unctrl(c) + ' QUIT\n', echo) return 'QUIT' elif c == chr(10): self._readline_echo(c, echo) result = ''.join(line) if use_history: self.history.append(result) if echo is False: if prompt: self.write( chr(10) ) log.debug('readline: %s(hidden text)', prompt) else: log.debug('readline: %s%r', prompt, result) return result elif c == curses.KEY_BACKSPACE or c == chr(127) or c == chr(8): if insptr > 0: self._readline_echo(self.CODES['CSRLEFT'] + self.CODES['DEL'], echo) insptr = insptr - 1 del line[insptr] else: self._readline_echo(BELL, echo) continue elif c == curses.KEY_DC: if insptr < len(line): self._readline_echo(self.CODES['DEL'], echo) del line[insptr] else: self._readline_echo(BELL, echo) continue else: if ord(c) < 32: c = curses.ascii.unctrl(c) if len(line) > insptr: self._readline_insert(c, echo, insptr, line) else: self._readline_echo(c, echo) line[insptr:insptr] = c insptr = insptr + len(c) if self._readline_do_echo(echo): self._current_line = line
[ "def", "readline", "(", "self", ",", "echo", "=", "None", ",", "prompt", "=", "''", ",", "use_history", "=", "True", ")", ":", "line", "=", "[", "]", "insptr", "=", "0", "ansi", "=", "0", "histptr", "=", "len", "(", "self", ".", "history", ")", "if", "self", ".", "DOECHO", ":", "self", ".", "write", "(", "prompt", ")", "self", ".", "_current_prompt", "=", "prompt", "else", ":", "self", ".", "_current_prompt", "=", "''", "self", ".", "_current_line", "=", "''", "while", "True", ":", "c", "=", "self", ".", "getc", "(", "block", "=", "True", ")", "c", "=", "self", ".", "ansi_to_curses", "(", "c", ")", "if", "c", "==", "theNULL", ":", "continue", "elif", "c", "==", "curses", ".", "KEY_LEFT", ":", "if", "insptr", ">", "0", ":", "insptr", "=", "insptr", "-", "1", "self", ".", "_readline_echo", "(", "self", ".", "CODES", "[", "'CSRLEFT'", "]", ",", "echo", ")", "else", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "echo", ")", "continue", "elif", "c", "==", "curses", ".", "KEY_RIGHT", ":", "if", "insptr", "<", "len", "(", "line", ")", ":", "insptr", "=", "insptr", "+", "1", "self", ".", "_readline_echo", "(", "self", ".", "CODES", "[", "'CSRRIGHT'", "]", ",", "echo", ")", "else", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "echo", ")", "continue", "elif", "c", "==", "curses", ".", "KEY_UP", "or", "c", "==", "curses", ".", "KEY_DOWN", ":", "if", "not", "use_history", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "echo", ")", "continue", "if", "c", "==", "curses", ".", "KEY_UP", ":", "if", "histptr", ">", "0", ":", "histptr", "=", "histptr", "-", "1", "else", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "echo", ")", "continue", "elif", "c", "==", "curses", ".", "KEY_DOWN", ":", "if", "histptr", "<", "len", "(", "self", ".", "history", ")", ":", "histptr", "=", "histptr", "+", "1", "else", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "echo", ")", "continue", "line", "=", "[", "]", "if", "histptr", "<", "len", "(", "self", ".", "history", ")", ":", "line", ".", "extend", "(", "self", ".", "history", "[", "histptr", "]", ")", "for", "char", "in", "range", "(", "insptr", ")", ":", "self", ".", "_readline_echo", "(", "self", ".", "CODES", "[", "'CSRLEFT'", "]", ",", "echo", ")", "self", ".", "_readline_echo", "(", "self", ".", "CODES", "[", "'DEOL'", "]", ",", "echo", ")", "self", ".", "_readline_echo", "(", "''", ".", "join", "(", "line", ")", ",", "echo", ")", "insptr", "=", "len", "(", "line", ")", "continue", "elif", "c", "==", "chr", "(", "3", ")", ":", "self", ".", "_readline_echo", "(", "'\\n'", "+", "curses", ".", "ascii", ".", "unctrl", "(", "c", ")", "+", "' ABORT\\n'", ",", "echo", ")", "return", "''", "elif", "c", "==", "chr", "(", "4", ")", ":", "if", "len", "(", "line", ")", ">", "0", ":", "self", ".", "_readline_echo", "(", "'\\n'", "+", "curses", ".", "ascii", ".", "unctrl", "(", "c", ")", "+", "' ABORT (QUIT)\\n'", ",", "echo", ")", "return", "''", "self", ".", "_readline_echo", "(", "'\\n'", "+", "curses", ".", "ascii", ".", "unctrl", "(", "c", ")", "+", "' QUIT\\n'", ",", "echo", ")", "return", "'QUIT'", "elif", "c", "==", "chr", "(", "10", ")", ":", "self", ".", "_readline_echo", "(", "c", ",", "echo", ")", "result", "=", "''", ".", "join", "(", "line", ")", "if", "use_history", ":", "self", ".", "history", ".", "append", "(", "result", ")", "if", "echo", "is", "False", ":", "if", "prompt", ":", "self", ".", "write", "(", "chr", "(", "10", ")", ")", "log", ".", "debug", "(", "'readline: %s(hidden text)'", ",", "prompt", ")", "else", ":", "log", ".", "debug", "(", "'readline: %s%r'", ",", "prompt", ",", "result", ")", "return", "result", "elif", "c", "==", "curses", ".", "KEY_BACKSPACE", "or", "c", "==", "chr", "(", "127", ")", "or", "c", "==", "chr", "(", "8", ")", ":", "if", "insptr", ">", "0", ":", "self", ".", "_readline_echo", "(", "self", ".", "CODES", "[", "'CSRLEFT'", "]", "+", "self", ".", "CODES", "[", "'DEL'", "]", ",", "echo", ")", "insptr", "=", "insptr", "-", "1", "del", "line", "[", "insptr", "]", "else", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "echo", ")", "continue", "elif", "c", "==", "curses", ".", "KEY_DC", ":", "if", "insptr", "<", "len", "(", "line", ")", ":", "self", ".", "_readline_echo", "(", "self", ".", "CODES", "[", "'DEL'", "]", ",", "echo", ")", "del", "line", "[", "insptr", "]", "else", ":", "self", ".", "_readline_echo", "(", "BELL", ",", "echo", ")", "continue", "else", ":", "if", "ord", "(", "c", ")", "<", "32", ":", "c", "=", "curses", ".", "ascii", ".", "unctrl", "(", "c", ")", "if", "len", "(", "line", ")", ">", "insptr", ":", "self", ".", "_readline_insert", "(", "c", ",", "echo", ",", "insptr", ",", "line", ")", "else", ":", "self", ".", "_readline_echo", "(", "c", ",", "echo", ")", "line", "[", "insptr", ":", "insptr", "]", "=", "c", "insptr", "=", "insptr", "+", "len", "(", "c", ")", "if", "self", ".", "_readline_do_echo", "(", "echo", ")", ":", "self", ".", "_current_line", "=", "line" ]
Return a line of text, including the terminating LF If echo is true always echo, if echo is false never echo If echo is None follow the negotiated setting. prompt is the current prompt to write (and rewrite if needed) use_history controls if this current line uses (and adds to) the command history.
[ "Return", "a", "line", "of", "text", "including", "the", "terminating", "LF", "If", "echo", "is", "true", "always", "echo", "if", "echo", "is", "false", "never", "echo", "If", "echo", "is", "None", "follow", "the", "negotiated", "setting", ".", "prompt", "is", "the", "current", "prompt", "to", "write", "(", "and", "rewrite", "if", "needed", ")", "use_history", "controls", "if", "this", "current", "line", "uses", "(", "and", "adds", "to", ")", "the", "command", "history", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L656-L768
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.writeline
def writeline(self, text): """Send a packet with line ending.""" log.debug('writing line %r' % text) self.write(text+chr(10))
python
def writeline(self, text): """Send a packet with line ending.""" log.debug('writing line %r' % text) self.write(text+chr(10))
[ "def", "writeline", "(", "self", ",", "text", ")", ":", "log", ".", "debug", "(", "'writing line %r'", "%", "text", ")", "self", ".", "write", "(", "text", "+", "chr", "(", "10", ")", ")" ]
Send a packet with line ending.
[ "Send", "a", "packet", "with", "line", "ending", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L786-L789
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.writemessage
def writemessage(self, text): """Write out an asynchronous message, then reconstruct the prompt and entered text.""" log.debug('writing message %r', text) self.write(chr(10)+text+chr(10)) self.write(self._current_prompt+''.join(self._current_line))
python
def writemessage(self, text): """Write out an asynchronous message, then reconstruct the prompt and entered text.""" log.debug('writing message %r', text) self.write(chr(10)+text+chr(10)) self.write(self._current_prompt+''.join(self._current_line))
[ "def", "writemessage", "(", "self", ",", "text", ")", ":", "log", ".", "debug", "(", "'writing message %r'", ",", "text", ")", "self", ".", "write", "(", "chr", "(", "10", ")", "+", "text", "+", "chr", "(", "10", ")", ")", "self", ".", "write", "(", "self", ".", "_current_prompt", "+", "''", ".", "join", "(", "self", ".", "_current_line", ")", ")" ]
Write out an asynchronous message, then reconstruct the prompt and entered text.
[ "Write", "out", "an", "asynchronous", "message", "then", "reconstruct", "the", "prompt", "and", "entered", "text", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L791-L795
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.write
def write(self, text): """Send a packet to the socket. This function cooks output.""" text = str(text) # eliminate any unicode or other snigglets text = text.replace(IAC, IAC+IAC) text = text.replace(chr(10), chr(13)+chr(10)) self.writecooked(text)
python
def write(self, text): """Send a packet to the socket. This function cooks output.""" text = str(text) # eliminate any unicode or other snigglets text = text.replace(IAC, IAC+IAC) text = text.replace(chr(10), chr(13)+chr(10)) self.writecooked(text)
[ "def", "write", "(", "self", ",", "text", ")", ":", "text", "=", "str", "(", "text", ")", "# eliminate any unicode or other snigglets", "text", "=", "text", ".", "replace", "(", "IAC", ",", "IAC", "+", "IAC", ")", "text", "=", "text", ".", "replace", "(", "chr", "(", "10", ")", ",", "chr", "(", "13", ")", "+", "chr", "(", "10", ")", ")", "self", ".", "writecooked", "(", "text", ")" ]
Send a packet to the socket. This function cooks output.
[ "Send", "a", "packet", "to", "the", "socket", ".", "This", "function", "cooks", "output", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L797-L802
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase._inputcooker_getc
def _inputcooker_getc(self, block=True): """Get one character from the raw queue. Optionally blocking. Raise EOFError on end of stream. SHOULD ONLY BE CALLED FROM THE INPUT COOKER.""" if self.rawq: ret = self.rawq[0] self.rawq = self.rawq[1:] return ret if not block: if not self.inputcooker_socket_ready(): return '' ret = self.sock.recv(20) self.eof = not(ret) self.rawq = self.rawq + ret if self.eof: raise EOFError return self._inputcooker_getc(block)
python
def _inputcooker_getc(self, block=True): """Get one character from the raw queue. Optionally blocking. Raise EOFError on end of stream. SHOULD ONLY BE CALLED FROM THE INPUT COOKER.""" if self.rawq: ret = self.rawq[0] self.rawq = self.rawq[1:] return ret if not block: if not self.inputcooker_socket_ready(): return '' ret = self.sock.recv(20) self.eof = not(ret) self.rawq = self.rawq + ret if self.eof: raise EOFError return self._inputcooker_getc(block)
[ "def", "_inputcooker_getc", "(", "self", ",", "block", "=", "True", ")", ":", "if", "self", ".", "rawq", ":", "ret", "=", "self", ".", "rawq", "[", "0", "]", "self", ".", "rawq", "=", "self", ".", "rawq", "[", "1", ":", "]", "return", "ret", "if", "not", "block", ":", "if", "not", "self", ".", "inputcooker_socket_ready", "(", ")", ":", "return", "''", "ret", "=", "self", ".", "sock", ".", "recv", "(", "20", ")", "self", ".", "eof", "=", "not", "(", "ret", ")", "self", ".", "rawq", "=", "self", ".", "rawq", "+", "ret", "if", "self", ".", "eof", ":", "raise", "EOFError", "return", "self", ".", "_inputcooker_getc", "(", "block", ")" ]
Get one character from the raw queue. Optionally blocking. Raise EOFError on end of stream. SHOULD ONLY BE CALLED FROM THE INPUT COOKER.
[ "Get", "one", "character", "from", "the", "raw", "queue", ".", "Optionally", "blocking", ".", "Raise", "EOFError", "on", "end", "of", "stream", ".", "SHOULD", "ONLY", "BE", "CALLED", "FROM", "THE", "INPUT", "COOKER", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L809-L825
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase._inputcooker_store
def _inputcooker_store(self, char): """Put the cooked data in the correct queue""" if self.sb: self.sbdataq = self.sbdataq + char else: self.inputcooker_store_queue(char)
python
def _inputcooker_store(self, char): """Put the cooked data in the correct queue""" if self.sb: self.sbdataq = self.sbdataq + char else: self.inputcooker_store_queue(char)
[ "def", "_inputcooker_store", "(", "self", ",", "char", ")", ":", "if", "self", ".", "sb", ":", "self", ".", "sbdataq", "=", "self", ".", "sbdataq", "+", "char", "else", ":", "self", ".", "inputcooker_store_queue", "(", "char", ")" ]
Put the cooked data in the correct queue
[ "Put", "the", "cooked", "data", "in", "the", "correct", "queue" ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L839-L844
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.inputcooker
def inputcooker(self): """Input Cooker - Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence. """ try: while True: c = self._inputcooker_getc() if not self.iacseq: if c == IAC: self.iacseq += c continue elif c == chr(13) and not(self.sb): c2 = self._inputcooker_getc(block=False) if c2 == theNULL or c2 == '': c = chr(10) elif c2 == chr(10): c = c2 else: self._inputcooker_ungetc(c2) c = chr(10) elif c in [x[0] for x in self.ESCSEQ.keys()]: 'Looks like the begining of a key sequence' codes = c for keyseq in self.ESCSEQ.keys(): if len(keyseq) == 0: continue while codes == keyseq[:len(codes)] and len(codes) <= keyseq: if codes == keyseq: c = self.ESCSEQ[keyseq] break codes = codes + self._inputcooker_getc() if codes == keyseq: break self._inputcooker_ungetc(codes[1:]) codes = codes[0] self._inputcooker_store(c) elif len(self.iacseq) == 1: 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]' if c in (DO, DONT, WILL, WONT): self.iacseq += c continue self.iacseq = '' if c == IAC: self._inputcooker_store(c) else: if c == SB: # SB ... SE start. self.sb = 1 self.sbdataq = '' elif c == SE: # SB ... SE end. self.sb = 0 # Callback is supposed to look into # the sbdataq self.options_handler(self.sock, c, NOOPT) elif len(self.iacseq) == 2: cmd = self.iacseq[1] self.iacseq = '' if cmd in (DO, DONT, WILL, WONT): self.options_handler(self.sock, cmd, c) except (EOFError, socket.error): pass
python
def inputcooker(self): """Input Cooker - Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence. """ try: while True: c = self._inputcooker_getc() if not self.iacseq: if c == IAC: self.iacseq += c continue elif c == chr(13) and not(self.sb): c2 = self._inputcooker_getc(block=False) if c2 == theNULL or c2 == '': c = chr(10) elif c2 == chr(10): c = c2 else: self._inputcooker_ungetc(c2) c = chr(10) elif c in [x[0] for x in self.ESCSEQ.keys()]: 'Looks like the begining of a key sequence' codes = c for keyseq in self.ESCSEQ.keys(): if len(keyseq) == 0: continue while codes == keyseq[:len(codes)] and len(codes) <= keyseq: if codes == keyseq: c = self.ESCSEQ[keyseq] break codes = codes + self._inputcooker_getc() if codes == keyseq: break self._inputcooker_ungetc(codes[1:]) codes = codes[0] self._inputcooker_store(c) elif len(self.iacseq) == 1: 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]' if c in (DO, DONT, WILL, WONT): self.iacseq += c continue self.iacseq = '' if c == IAC: self._inputcooker_store(c) else: if c == SB: # SB ... SE start. self.sb = 1 self.sbdataq = '' elif c == SE: # SB ... SE end. self.sb = 0 # Callback is supposed to look into # the sbdataq self.options_handler(self.sock, c, NOOPT) elif len(self.iacseq) == 2: cmd = self.iacseq[1] self.iacseq = '' if cmd in (DO, DONT, WILL, WONT): self.options_handler(self.sock, cmd, c) except (EOFError, socket.error): pass
[ "def", "inputcooker", "(", "self", ")", ":", "try", ":", "while", "True", ":", "c", "=", "self", ".", "_inputcooker_getc", "(", ")", "if", "not", "self", ".", "iacseq", ":", "if", "c", "==", "IAC", ":", "self", ".", "iacseq", "+=", "c", "continue", "elif", "c", "==", "chr", "(", "13", ")", "and", "not", "(", "self", ".", "sb", ")", ":", "c2", "=", "self", ".", "_inputcooker_getc", "(", "block", "=", "False", ")", "if", "c2", "==", "theNULL", "or", "c2", "==", "''", ":", "c", "=", "chr", "(", "10", ")", "elif", "c2", "==", "chr", "(", "10", ")", ":", "c", "=", "c2", "else", ":", "self", ".", "_inputcooker_ungetc", "(", "c2", ")", "c", "=", "chr", "(", "10", ")", "elif", "c", "in", "[", "x", "[", "0", "]", "for", "x", "in", "self", ".", "ESCSEQ", ".", "keys", "(", ")", "]", ":", "'Looks like the begining of a key sequence'", "codes", "=", "c", "for", "keyseq", "in", "self", ".", "ESCSEQ", ".", "keys", "(", ")", ":", "if", "len", "(", "keyseq", ")", "==", "0", ":", "continue", "while", "codes", "==", "keyseq", "[", ":", "len", "(", "codes", ")", "]", "and", "len", "(", "codes", ")", "<=", "keyseq", ":", "if", "codes", "==", "keyseq", ":", "c", "=", "self", ".", "ESCSEQ", "[", "keyseq", "]", "break", "codes", "=", "codes", "+", "self", ".", "_inputcooker_getc", "(", ")", "if", "codes", "==", "keyseq", ":", "break", "self", ".", "_inputcooker_ungetc", "(", "codes", "[", "1", ":", "]", ")", "codes", "=", "codes", "[", "0", "]", "self", ".", "_inputcooker_store", "(", "c", ")", "elif", "len", "(", "self", ".", "iacseq", ")", "==", "1", ":", "'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'", "if", "c", "in", "(", "DO", ",", "DONT", ",", "WILL", ",", "WONT", ")", ":", "self", ".", "iacseq", "+=", "c", "continue", "self", ".", "iacseq", "=", "''", "if", "c", "==", "IAC", ":", "self", ".", "_inputcooker_store", "(", "c", ")", "else", ":", "if", "c", "==", "SB", ":", "# SB ... SE start.", "self", ".", "sb", "=", "1", "self", ".", "sbdataq", "=", "''", "elif", "c", "==", "SE", ":", "# SB ... SE end.", "self", ".", "sb", "=", "0", "# Callback is supposed to look into", "# the sbdataq", "self", ".", "options_handler", "(", "self", ".", "sock", ",", "c", ",", "NOOPT", ")", "elif", "len", "(", "self", ".", "iacseq", ")", "==", "2", ":", "cmd", "=", "self", ".", "iacseq", "[", "1", "]", "self", ".", "iacseq", "=", "''", "if", "cmd", "in", "(", "DO", ",", "DONT", ",", "WILL", ",", "WONT", ")", ":", "self", ".", "options_handler", "(", "self", ".", "sock", ",", "cmd", ",", "c", ")", "except", "(", "EOFError", ",", "socket", ".", "error", ")", ":", "pass" ]
Input Cooker - Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence.
[ "Input", "Cooker", "-", "Transfer", "from", "raw", "queue", "to", "cooked", "queue", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L851-L912
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.cmdHELP
def cmdHELP(self, params): """[<command>] Display help Display either brief help on all commands, or detailed help on a single command passed as a parameter. """ if params: cmd = params[0].upper() if self.COMMANDS.has_key(cmd): method = self.COMMANDS[cmd] doc = method.__doc__.split("\n") docp = doc[0].strip() docl = '\n'.join( [l.strip() for l in doc[2:]] ) if not docl.strip(): # If there isn't anything here, use line 1 docl = doc[1].strip() self.writeline( "%s %s\n\n%s" % ( cmd, docp, docl, ) ) return else: self.writeline("Command '%s' not known" % cmd) else: self.writeline("Help on built in commands\n") keys = self.COMMANDS.keys() keys.sort() for cmd in keys: method = self.COMMANDS[cmd] if getattr(method, 'hidden', False): continue if method.__doc__ == None: self.writeline("no help for command %s" % method) return doc = method.__doc__.split("\n") docp = doc[0].strip() docs = doc[1].strip() if len(docp) > 0: docps = "%s - %s" % (docp, docs, ) else: docps = "- %s" % (docs, ) self.writeline( "%s %s" % ( cmd, docps, ) )
python
def cmdHELP(self, params): """[<command>] Display help Display either brief help on all commands, or detailed help on a single command passed as a parameter. """ if params: cmd = params[0].upper() if self.COMMANDS.has_key(cmd): method = self.COMMANDS[cmd] doc = method.__doc__.split("\n") docp = doc[0].strip() docl = '\n'.join( [l.strip() for l in doc[2:]] ) if not docl.strip(): # If there isn't anything here, use line 1 docl = doc[1].strip() self.writeline( "%s %s\n\n%s" % ( cmd, docp, docl, ) ) return else: self.writeline("Command '%s' not known" % cmd) else: self.writeline("Help on built in commands\n") keys = self.COMMANDS.keys() keys.sort() for cmd in keys: method = self.COMMANDS[cmd] if getattr(method, 'hidden', False): continue if method.__doc__ == None: self.writeline("no help for command %s" % method) return doc = method.__doc__.split("\n") docp = doc[0].strip() docs = doc[1].strip() if len(docp) > 0: docps = "%s - %s" % (docp, docs, ) else: docps = "- %s" % (docs, ) self.writeline( "%s %s" % ( cmd, docps, ) )
[ "def", "cmdHELP", "(", "self", ",", "params", ")", ":", "if", "params", ":", "cmd", "=", "params", "[", "0", "]", ".", "upper", "(", ")", "if", "self", ".", "COMMANDS", ".", "has_key", "(", "cmd", ")", ":", "method", "=", "self", ".", "COMMANDS", "[", "cmd", "]", "doc", "=", "method", ".", "__doc__", ".", "split", "(", "\"\\n\"", ")", "docp", "=", "doc", "[", "0", "]", ".", "strip", "(", ")", "docl", "=", "'\\n'", ".", "join", "(", "[", "l", ".", "strip", "(", ")", "for", "l", "in", "doc", "[", "2", ":", "]", "]", ")", "if", "not", "docl", ".", "strip", "(", ")", ":", "# If there isn't anything here, use line 1", "docl", "=", "doc", "[", "1", "]", ".", "strip", "(", ")", "self", ".", "writeline", "(", "\"%s %s\\n\\n%s\"", "%", "(", "cmd", ",", "docp", ",", "docl", ",", ")", ")", "return", "else", ":", "self", ".", "writeline", "(", "\"Command '%s' not known\"", "%", "cmd", ")", "else", ":", "self", ".", "writeline", "(", "\"Help on built in commands\\n\"", ")", "keys", "=", "self", ".", "COMMANDS", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "for", "cmd", "in", "keys", ":", "method", "=", "self", ".", "COMMANDS", "[", "cmd", "]", "if", "getattr", "(", "method", ",", "'hidden'", ",", "False", ")", ":", "continue", "if", "method", ".", "__doc__", "==", "None", ":", "self", ".", "writeline", "(", "\"no help for command %s\"", "%", "method", ")", "return", "doc", "=", "method", ".", "__doc__", ".", "split", "(", "\"\\n\"", ")", "docp", "=", "doc", "[", "0", "]", ".", "strip", "(", ")", "docs", "=", "doc", "[", "1", "]", ".", "strip", "(", ")", "if", "len", "(", "docp", ")", ">", "0", ":", "docps", "=", "\"%s - %s\"", "%", "(", "docp", ",", "docs", ",", ")", "else", ":", "docps", "=", "\"- %s\"", "%", "(", "docs", ",", ")", "self", ".", "writeline", "(", "\"%s %s\"", "%", "(", "cmd", ",", "docps", ",", ")", ")" ]
[<command>] Display help Display either brief help on all commands, or detailed help on a single command passed as a parameter.
[ "[", "<command", ">", "]", "Display", "help", "Display", "either", "brief", "help", "on", "all", "commands", "or", "detailed", "help", "on", "a", "single", "command", "passed", "as", "a", "parameter", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L921-L969
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.cmdHISTORY
def cmdHISTORY(self, params): """ Display the command history """ cnt = 0 self.writeline('Command history\n') for line in self.history: cnt = cnt + 1 self.writeline("%-5d : %s" % (cnt, ''.join(line)))
python
def cmdHISTORY(self, params): """ Display the command history """ cnt = 0 self.writeline('Command history\n') for line in self.history: cnt = cnt + 1 self.writeline("%-5d : %s" % (cnt, ''.join(line)))
[ "def", "cmdHISTORY", "(", "self", ",", "params", ")", ":", "cnt", "=", "0", "self", ".", "writeline", "(", "'Command history\\n'", ")", "for", "line", "in", "self", ".", "history", ":", "cnt", "=", "cnt", "+", "1", "self", ".", "writeline", "(", "\"%-5d : %s\"", "%", "(", "cnt", ",", "''", ".", "join", "(", "line", ")", ")", ")" ]
Display the command history
[ "Display", "the", "command", "history" ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L980-L988
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.handleException
def handleException(self, exc_type, exc_param, exc_tb): "Exception handler (False to abort)" self.writeline(''.join( traceback.format_exception(exc_type, exc_param, exc_tb) )) return True
python
def handleException(self, exc_type, exc_param, exc_tb): "Exception handler (False to abort)" self.writeline(''.join( traceback.format_exception(exc_type, exc_param, exc_tb) )) return True
[ "def", "handleException", "(", "self", ",", "exc_type", ",", "exc_param", ",", "exc_tb", ")", ":", "self", ".", "writeline", "(", "''", ".", "join", "(", "traceback", ".", "format_exception", "(", "exc_type", ",", "exc_param", ",", "exc_tb", ")", ")", ")", "return", "True" ]
Exception handler (False to abort)
[ "Exception", "handler", "(", "False", "to", "abort", ")" ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L992-L995
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.authentication_ok
def authentication_ok(self): '''Checks the authentication and sets the username of the currently connected terminal. Returns True or False''' username = None password = None if self.authCallback: if self.authNeedUser: username = self.readline(prompt=self.PROMPT_USER, use_history=False) if self.authNeedPass: password = self.readline(echo=False, prompt=self.PROMPT_PASS, use_history=False) if self.DOECHO: self.write("\n") try: self.authCallback(username, password) except: self.username = None return False else: # Successful authentication self.username = username return True else: # No authentication desired self.username = None return True
python
def authentication_ok(self): '''Checks the authentication and sets the username of the currently connected terminal. Returns True or False''' username = None password = None if self.authCallback: if self.authNeedUser: username = self.readline(prompt=self.PROMPT_USER, use_history=False) if self.authNeedPass: password = self.readline(echo=False, prompt=self.PROMPT_PASS, use_history=False) if self.DOECHO: self.write("\n") try: self.authCallback(username, password) except: self.username = None return False else: # Successful authentication self.username = username return True else: # No authentication desired self.username = None return True
[ "def", "authentication_ok", "(", "self", ")", ":", "username", "=", "None", "password", "=", "None", "if", "self", ".", "authCallback", ":", "if", "self", ".", "authNeedUser", ":", "username", "=", "self", ".", "readline", "(", "prompt", "=", "self", ".", "PROMPT_USER", ",", "use_history", "=", "False", ")", "if", "self", ".", "authNeedPass", ":", "password", "=", "self", ".", "readline", "(", "echo", "=", "False", ",", "prompt", "=", "self", ".", "PROMPT_PASS", ",", "use_history", "=", "False", ")", "if", "self", ".", "DOECHO", ":", "self", ".", "write", "(", "\"\\n\"", ")", "try", ":", "self", ".", "authCallback", "(", "username", ",", "password", ")", "except", ":", "self", ".", "username", "=", "None", "return", "False", "else", ":", "# Successful authentication", "self", ".", "username", "=", "username", "return", "True", "else", ":", "# No authentication desired", "self", ".", "username", "=", "None", "return", "True" ]
Checks the authentication and sets the username of the currently connected terminal. Returns True or False
[ "Checks", "the", "authentication", "and", "sets", "the", "username", "of", "the", "currently", "connected", "terminal", ".", "Returns", "True", "or", "False" ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L997-L1020
train
ianepperson/telnetsrvlib
telnetsrv/telnetsrvlib.py
TelnetHandlerBase.handle
def handle(self): "The actual service to which the user has connected." if self.TELNET_ISSUE: self.writeline(self.TELNET_ISSUE) if not self.authentication_ok(): return if self.DOECHO: self.writeline(self.WELCOME) self.session_start() while self.RUNSHELL: raw_input = self.readline(prompt=self.PROMPT).strip() self.input = self.input_reader(self, raw_input) self.raw_input = self.input.raw if self.input.cmd: cmd = self.input.cmd.upper() params = self.input.params if self.COMMANDS.has_key(cmd): try: self.COMMANDS[cmd](params) except: log.exception('Error calling %s.' % cmd) (t, p, tb) = sys.exc_info() if self.handleException(t, p, tb): break else: self.writeerror("Unknown command '%s'" % cmd) log.debug("Exiting handler")
python
def handle(self): "The actual service to which the user has connected." if self.TELNET_ISSUE: self.writeline(self.TELNET_ISSUE) if not self.authentication_ok(): return if self.DOECHO: self.writeline(self.WELCOME) self.session_start() while self.RUNSHELL: raw_input = self.readline(prompt=self.PROMPT).strip() self.input = self.input_reader(self, raw_input) self.raw_input = self.input.raw if self.input.cmd: cmd = self.input.cmd.upper() params = self.input.params if self.COMMANDS.has_key(cmd): try: self.COMMANDS[cmd](params) except: log.exception('Error calling %s.' % cmd) (t, p, tb) = sys.exc_info() if self.handleException(t, p, tb): break else: self.writeerror("Unknown command '%s'" % cmd) log.debug("Exiting handler")
[ "def", "handle", "(", "self", ")", ":", "if", "self", ".", "TELNET_ISSUE", ":", "self", ".", "writeline", "(", "self", ".", "TELNET_ISSUE", ")", "if", "not", "self", ".", "authentication_ok", "(", ")", ":", "return", "if", "self", ".", "DOECHO", ":", "self", ".", "writeline", "(", "self", ".", "WELCOME", ")", "self", ".", "session_start", "(", ")", "while", "self", ".", "RUNSHELL", ":", "raw_input", "=", "self", ".", "readline", "(", "prompt", "=", "self", ".", "PROMPT", ")", ".", "strip", "(", ")", "self", ".", "input", "=", "self", ".", "input_reader", "(", "self", ",", "raw_input", ")", "self", ".", "raw_input", "=", "self", ".", "input", ".", "raw", "if", "self", ".", "input", ".", "cmd", ":", "cmd", "=", "self", ".", "input", ".", "cmd", ".", "upper", "(", ")", "params", "=", "self", ".", "input", ".", "params", "if", "self", ".", "COMMANDS", ".", "has_key", "(", "cmd", ")", ":", "try", ":", "self", ".", "COMMANDS", "[", "cmd", "]", "(", "params", ")", "except", ":", "log", ".", "exception", "(", "'Error calling %s.'", "%", "cmd", ")", "(", "t", ",", "p", ",", "tb", ")", "=", "sys", ".", "exc_info", "(", ")", "if", "self", ".", "handleException", "(", "t", ",", "p", ",", "tb", ")", ":", "break", "else", ":", "self", ".", "writeerror", "(", "\"Unknown command '%s'\"", "%", "cmd", ")", "log", ".", "debug", "(", "\"Exiting handler\"", ")" ]
The actual service to which the user has connected.
[ "The", "actual", "service", "to", "which", "the", "user", "has", "connected", "." ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L1023-L1050
train
ianepperson/telnetsrvlib
telnetsrv/green.py
TelnetHandler.setup
def setup(self): '''Called after instantiation''' TelnetHandlerBase.setup(self) # Spawn a greenlet to handle socket input self.greenlet_ic = gevent.spawn(self.inputcooker) # Note that inputcooker exits on EOF # Sleep for 0.5 second to allow options negotiation gevent.sleep(0.5)
python
def setup(self): '''Called after instantiation''' TelnetHandlerBase.setup(self) # Spawn a greenlet to handle socket input self.greenlet_ic = gevent.spawn(self.inputcooker) # Note that inputcooker exits on EOF # Sleep for 0.5 second to allow options negotiation gevent.sleep(0.5)
[ "def", "setup", "(", "self", ")", ":", "TelnetHandlerBase", ".", "setup", "(", "self", ")", "# Spawn a greenlet to handle socket input", "self", ".", "greenlet_ic", "=", "gevent", ".", "spawn", "(", "self", ".", "inputcooker", ")", "# Note that inputcooker exits on EOF", "# Sleep for 0.5 second to allow options negotiation", "gevent", ".", "sleep", "(", "0.5", ")" ]
Called after instantiation
[ "Called", "after", "instantiation" ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/green.py#L16-L24
train
ianepperson/telnetsrvlib
telnetsrv/green.py
TelnetHandler.getc
def getc(self, block=True): """Return one character from the input queue""" try: return self.cookedq.get(block) except gevent.queue.Empty: return ''
python
def getc(self, block=True): """Return one character from the input queue""" try: return self.cookedq.get(block) except gevent.queue.Empty: return ''
[ "def", "getc", "(", "self", ",", "block", "=", "True", ")", ":", "try", ":", "return", "self", ".", "cookedq", ".", "get", "(", "block", ")", "except", "gevent", ".", "queue", ".", "Empty", ":", "return", "''" ]
Return one character from the input queue
[ "Return", "one", "character", "from", "the", "input", "queue" ]
fac52a4a333c2d373d53d295a76a0bbd71e5d682
https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/green.py#L35-L40
train
hbldh/pybankid
bankid/client.py
BankIDClient.authenticate
def authenticate(self, personal_number, **kwargs): """Request an authentication order. The :py:meth:`collect` method is used to query the status of the order. :param personal_number: The Swedish personal number in format YYYYMMDDXXXX. :type personal_number: str :return: The OrderResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server. """ if "requirementAlternatives" in kwargs: warnings.warn( "Requirement Alternatives " "option is not tested.", BankIDWarning ) try: out = self.client.service.Authenticate( personalNumber=personal_number, **kwargs ) except Error as e: raise get_error_class(e, "Could not complete Authenticate order.") return self._dictify(out)
python
def authenticate(self, personal_number, **kwargs): """Request an authentication order. The :py:meth:`collect` method is used to query the status of the order. :param personal_number: The Swedish personal number in format YYYYMMDDXXXX. :type personal_number: str :return: The OrderResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server. """ if "requirementAlternatives" in kwargs: warnings.warn( "Requirement Alternatives " "option is not tested.", BankIDWarning ) try: out = self.client.service.Authenticate( personalNumber=personal_number, **kwargs ) except Error as e: raise get_error_class(e, "Could not complete Authenticate order.") return self._dictify(out)
[ "def", "authenticate", "(", "self", ",", "personal_number", ",", "*", "*", "kwargs", ")", ":", "if", "\"requirementAlternatives\"", "in", "kwargs", ":", "warnings", ".", "warn", "(", "\"Requirement Alternatives \"", "\"option is not tested.\"", ",", "BankIDWarning", ")", "try", ":", "out", "=", "self", ".", "client", ".", "service", ".", "Authenticate", "(", "personalNumber", "=", "personal_number", ",", "*", "*", "kwargs", ")", "except", "Error", "as", "e", ":", "raise", "get_error_class", "(", "e", ",", "\"Could not complete Authenticate order.\"", ")", "return", "self", ".", "_dictify", "(", "out", ")" ]
Request an authentication order. The :py:meth:`collect` method is used to query the status of the order. :param personal_number: The Swedish personal number in format YYYYMMDDXXXX. :type personal_number: str :return: The OrderResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server.
[ "Request", "an", "authentication", "order", ".", "The", ":", "py", ":", "meth", ":", "collect", "method", "is", "used", "to", "query", "the", "status", "of", "the", "order", "." ]
1405f66e41f912cdda15e20aea08cdfa6b60480a
https://github.com/hbldh/pybankid/blob/1405f66e41f912cdda15e20aea08cdfa6b60480a/bankid/client.py#L84-L109
train
hbldh/pybankid
bankid/client.py
BankIDClient.sign
def sign(self, user_visible_data, personal_number=None, **kwargs): """Request an signing order. The :py:meth:`collect` method is used to query the status of the order. :param user_visible_data: The information that the end user is requested to sign. :type user_visible_data: str :param personal_number: The Swedish personal number in format YYYYMMDDXXXX. :type personal_number: str :return: The OrderResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server. """ if "requirementAlternatives" in kwargs: warnings.warn( "Requirement Alternatives option is not tested.", BankIDWarning ) if isinstance(user_visible_data, six.text_type): data = base64.b64encode(user_visible_data.encode("utf-8")).decode("ascii") else: data = base64.b64encode(user_visible_data).decode("ascii") try: out = self.client.service.Sign( userVisibleData=data, personalNumber=personal_number, **kwargs ) except Error as e: raise get_error_class(e, "Could not complete Sign order.") return self._dictify(out)
python
def sign(self, user_visible_data, personal_number=None, **kwargs): """Request an signing order. The :py:meth:`collect` method is used to query the status of the order. :param user_visible_data: The information that the end user is requested to sign. :type user_visible_data: str :param personal_number: The Swedish personal number in format YYYYMMDDXXXX. :type personal_number: str :return: The OrderResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server. """ if "requirementAlternatives" in kwargs: warnings.warn( "Requirement Alternatives option is not tested.", BankIDWarning ) if isinstance(user_visible_data, six.text_type): data = base64.b64encode(user_visible_data.encode("utf-8")).decode("ascii") else: data = base64.b64encode(user_visible_data).decode("ascii") try: out = self.client.service.Sign( userVisibleData=data, personalNumber=personal_number, **kwargs ) except Error as e: raise get_error_class(e, "Could not complete Sign order.") return self._dictify(out)
[ "def", "sign", "(", "self", ",", "user_visible_data", ",", "personal_number", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "\"requirementAlternatives\"", "in", "kwargs", ":", "warnings", ".", "warn", "(", "\"Requirement Alternatives option is not tested.\"", ",", "BankIDWarning", ")", "if", "isinstance", "(", "user_visible_data", ",", "six", ".", "text_type", ")", ":", "data", "=", "base64", ".", "b64encode", "(", "user_visible_data", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "else", ":", "data", "=", "base64", ".", "b64encode", "(", "user_visible_data", ")", ".", "decode", "(", "\"ascii\"", ")", "try", ":", "out", "=", "self", ".", "client", ".", "service", ".", "Sign", "(", "userVisibleData", "=", "data", ",", "personalNumber", "=", "personal_number", ",", "*", "*", "kwargs", ")", "except", "Error", "as", "e", ":", "raise", "get_error_class", "(", "e", ",", "\"Could not complete Sign order.\"", ")", "return", "self", ".", "_dictify", "(", "out", ")" ]
Request an signing order. The :py:meth:`collect` method is used to query the status of the order. :param user_visible_data: The information that the end user is requested to sign. :type user_visible_data: str :param personal_number: The Swedish personal number in format YYYYMMDDXXXX. :type personal_number: str :return: The OrderResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server.
[ "Request", "an", "signing", "order", ".", "The", ":", "py", ":", "meth", ":", "collect", "method", "is", "used", "to", "query", "the", "status", "of", "the", "order", "." ]
1405f66e41f912cdda15e20aea08cdfa6b60480a
https://github.com/hbldh/pybankid/blob/1405f66e41f912cdda15e20aea08cdfa6b60480a/bankid/client.py#L111-L144
train
hbldh/pybankid
bankid/client.py
BankIDClient.collect
def collect(self, order_ref): """Collect the progress status of the order with the specified order reference. :param order_ref: The UUID string specifying which order to collect status from. :type order_ref: str :return: The CollectResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server. """ try: out = self.client.service.Collect(order_ref) except Error as e: raise get_error_class(e, "Could not complete Collect call.") return self._dictify(out)
python
def collect(self, order_ref): """Collect the progress status of the order with the specified order reference. :param order_ref: The UUID string specifying which order to collect status from. :type order_ref: str :return: The CollectResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server. """ try: out = self.client.service.Collect(order_ref) except Error as e: raise get_error_class(e, "Could not complete Collect call.") return self._dictify(out)
[ "def", "collect", "(", "self", ",", "order_ref", ")", ":", "try", ":", "out", "=", "self", ".", "client", ".", "service", ".", "Collect", "(", "order_ref", ")", "except", "Error", "as", "e", ":", "raise", "get_error_class", "(", "e", ",", "\"Could not complete Collect call.\"", ")", "return", "self", ".", "_dictify", "(", "out", ")" ]
Collect the progress status of the order with the specified order reference. :param order_ref: The UUID string specifying which order to collect status from. :type order_ref: str :return: The CollectResponse parsed to a dictionary. :rtype: dict :raises BankIDError: raises a subclass of this error when error has been returned from server.
[ "Collect", "the", "progress", "status", "of", "the", "order", "with", "the", "specified", "order", "reference", "." ]
1405f66e41f912cdda15e20aea08cdfa6b60480a
https://github.com/hbldh/pybankid/blob/1405f66e41f912cdda15e20aea08cdfa6b60480a/bankid/client.py#L146-L164
train
hbldh/pybankid
bankid/client.py
BankIDClient._dictify
def _dictify(self, doc): """Transforms the replies to a regular Python dict with strings and datetimes. Tested with BankID version 2.5 return data. :param doc: The response as interpreted by :py:mod:`zeep`. :returns: The response parsed to a dict. :rtype: dict """ return { k: (self._dictify(doc[k]) if hasattr(doc[k], "_xsd_type") else doc[k]) for k in doc }
python
def _dictify(self, doc): """Transforms the replies to a regular Python dict with strings and datetimes. Tested with BankID version 2.5 return data. :param doc: The response as interpreted by :py:mod:`zeep`. :returns: The response parsed to a dict. :rtype: dict """ return { k: (self._dictify(doc[k]) if hasattr(doc[k], "_xsd_type") else doc[k]) for k in doc }
[ "def", "_dictify", "(", "self", ",", "doc", ")", ":", "return", "{", "k", ":", "(", "self", ".", "_dictify", "(", "doc", "[", "k", "]", ")", "if", "hasattr", "(", "doc", "[", "k", "]", ",", "\"_xsd_type\"", ")", "else", "doc", "[", "k", "]", ")", "for", "k", "in", "doc", "}" ]
Transforms the replies to a regular Python dict with strings and datetimes. Tested with BankID version 2.5 return data. :param doc: The response as interpreted by :py:mod:`zeep`. :returns: The response parsed to a dict. :rtype: dict
[ "Transforms", "the", "replies", "to", "a", "regular", "Python", "dict", "with", "strings", "and", "datetimes", "." ]
1405f66e41f912cdda15e20aea08cdfa6b60480a
https://github.com/hbldh/pybankid/blob/1405f66e41f912cdda15e20aea08cdfa6b60480a/bankid/client.py#L181-L195
train
springload/wagtaildraftail
wagtaildraftail/widgets.py
DraftailTextArea.intercept_image_formats
def intercept_image_formats(self, options): """ Load all image formats if needed. """ if 'entityTypes' in options: for entity in options['entityTypes']: if entity['type'] == ENTITY_TYPES.IMAGE and 'imageFormats' in entity: if entity['imageFormats'] == '__all__': entity['imageFormats'] = get_all_image_formats() return options
python
def intercept_image_formats(self, options): """ Load all image formats if needed. """ if 'entityTypes' in options: for entity in options['entityTypes']: if entity['type'] == ENTITY_TYPES.IMAGE and 'imageFormats' in entity: if entity['imageFormats'] == '__all__': entity['imageFormats'] = get_all_image_formats() return options
[ "def", "intercept_image_formats", "(", "self", ",", "options", ")", ":", "if", "'entityTypes'", "in", "options", ":", "for", "entity", "in", "options", "[", "'entityTypes'", "]", ":", "if", "entity", "[", "'type'", "]", "==", "ENTITY_TYPES", ".", "IMAGE", "and", "'imageFormats'", "in", "entity", ":", "if", "entity", "[", "'imageFormats'", "]", "==", "'__all__'", ":", "entity", "[", "'imageFormats'", "]", "=", "get_all_image_formats", "(", ")", "return", "options" ]
Load all image formats if needed.
[ "Load", "all", "image", "formats", "if", "needed", "." ]
87f1ae3ade493c00daff021394051aa656136c10
https://github.com/springload/wagtaildraftail/blob/87f1ae3ade493c00daff021394051aa656136c10/wagtaildraftail/widgets.py#L75-L85
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = decimal.Decimal(self._timestamp) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = decimal.Decimal(self._timestamp) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_timestamp", "is", "not", "None", ":", "self", ".", "_normalized_timestamp", "=", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L51-L64
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTime.CopyFromDateTimeString
def CopyFromDateTimeString(self, time_string): """Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) self._timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self.is_local_time = False
python
def CopyFromDateTimeString(self, time_string): """Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) self._timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self.is_local_time = False
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date_time_values", ".", "get", "(", "'month'", ",", "0", ")", "day_of_month", "=", "date_time_values", ".", "get", "(", "'day_of_month'", ",", "0", ")", "hours", "=", "date_time_values", ".", "get", "(", "'hours'", ",", "0", ")", "minutes", "=", "date_time_values", ".", "get", "(", "'minutes'", ",", "0", ")", "seconds", "=", "date_time_values", ".", "get", "(", "'seconds'", ",", "0", ")", "self", ".", "_timestamp", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "self", ".", "is_local_time", "=", "False" ]
Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC.
[ "Copies", "a", "POSIX", "timestamp", "from", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L66-L90
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTime.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None if the timestamp is missing. """ if self._timestamp is None: return None number_of_days, hours, minutes, seconds = self._GetTimeValues( self._timestamp) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format( year, month, day_of_month, hours, minutes, seconds)
python
def CopyToDateTimeString(self): """Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None if the timestamp is missing. """ if self._timestamp is None: return None number_of_days, hours, minutes, seconds = self._GetTimeValues( self._timestamp) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format( year, month, day_of_month, hours, minutes, seconds)
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "self", ".", "_timestamp", "is", "None", ":", "return", "None", "number_of_days", ",", "hours", ",", "minutes", ",", "seconds", "=", "self", ".", "_GetTimeValues", "(", "self", ".", "_timestamp", ")", "year", ",", "month", ",", "day_of_month", "=", "self", ".", "_GetDateValuesWithEpoch", "(", "number_of_days", ",", "self", ".", "_EPOCH", ")", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'", ".", "format", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")" ]
Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None if the timestamp is missing.
[ "Copies", "the", "POSIX", "timestamp", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L92-L109
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTimeInMilliseconds._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.MILLISECONDS_PER_SECOND) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.MILLISECONDS_PER_SECOND) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_timestamp", "is", "not", "None", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "/", "definitions", ".", "MILLISECONDS_PER_SECOND", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L138-L153
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTimeInMilliseconds.CopyFromDateTimeString
def CopyFromDateTimeString(self, time_string): """Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', 0) timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) timestamp *= definitions.MILLISECONDS_PER_SECOND if microseconds: milliseconds, _ = divmod( microseconds, definitions.MILLISECONDS_PER_SECOND) timestamp += milliseconds self._timestamp = timestamp self.is_local_time = False
python
def CopyFromDateTimeString(self, time_string): """Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', 0) timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) timestamp *= definitions.MILLISECONDS_PER_SECOND if microseconds: milliseconds, _ = divmod( microseconds, definitions.MILLISECONDS_PER_SECOND) timestamp += milliseconds self._timestamp = timestamp self.is_local_time = False
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date_time_values", ".", "get", "(", "'month'", ",", "0", ")", "day_of_month", "=", "date_time_values", ".", "get", "(", "'day_of_month'", ",", "0", ")", "hours", "=", "date_time_values", ".", "get", "(", "'hours'", ",", "0", ")", "minutes", "=", "date_time_values", ".", "get", "(", "'minutes'", ",", "0", ")", "seconds", "=", "date_time_values", ".", "get", "(", "'seconds'", ",", "0", ")", "microseconds", "=", "date_time_values", ".", "get", "(", "'microseconds'", ",", "0", ")", "timestamp", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "timestamp", "*=", "definitions", ".", "MILLISECONDS_PER_SECOND", "if", "microseconds", ":", "milliseconds", ",", "_", "=", "divmod", "(", "microseconds", ",", "definitions", ".", "MILLISECONDS_PER_SECOND", ")", "timestamp", "+=", "milliseconds", "self", ".", "_timestamp", "=", "timestamp", "self", ".", "is_local_time", "=", "False" ]
Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC.
[ "Copies", "a", "POSIX", "timestamp", "from", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L155-L187
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTimeInMicroseconds._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.MICROSECONDS_PER_SECOND) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.MICROSECONDS_PER_SECOND) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_timestamp", "is", "not", "None", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "/", "definitions", ".", "MICROSECONDS_PER_SECOND", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L236-L251
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTimeInNanoseconds._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.NANOSECONDS_PER_SECOND) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.NANOSECONDS_PER_SECOND) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_timestamp", "is", "not", "None", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "/", "definitions", ".", "NANOSECONDS_PER_SECOND", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L330-L345
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTimeInNanoseconds._CopyFromDateTimeString
def _CopyFromDateTimeString(self, time_string): """Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', None) timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) timestamp *= definitions.NANOSECONDS_PER_SECOND if microseconds: nanoseconds = microseconds * definitions.MILLISECONDS_PER_SECOND timestamp += nanoseconds self._normalized_timestamp = None self._timestamp = timestamp
python
def _CopyFromDateTimeString(self, time_string): """Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', None) timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) timestamp *= definitions.NANOSECONDS_PER_SECOND if microseconds: nanoseconds = microseconds * definitions.MILLISECONDS_PER_SECOND timestamp += nanoseconds self._normalized_timestamp = None self._timestamp = timestamp
[ "def", "_CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date_time_values", ".", "get", "(", "'month'", ",", "0", ")", "day_of_month", "=", "date_time_values", ".", "get", "(", "'day_of_month'", ",", "0", ")", "hours", "=", "date_time_values", ".", "get", "(", "'hours'", ",", "0", ")", "minutes", "=", "date_time_values", ".", "get", "(", "'minutes'", ",", "0", ")", "seconds", "=", "date_time_values", ".", "get", "(", "'seconds'", ",", "0", ")", "microseconds", "=", "date_time_values", ".", "get", "(", "'microseconds'", ",", "None", ")", "timestamp", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "timestamp", "*=", "definitions", ".", "NANOSECONDS_PER_SECOND", "if", "microseconds", ":", "nanoseconds", "=", "microseconds", "*", "definitions", ".", "MILLISECONDS_PER_SECOND", "timestamp", "+=", "nanoseconds", "self", ".", "_normalized_timestamp", "=", "None", "self", ".", "_timestamp", "=", "timestamp" ]
Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC.
[ "Copies", "a", "POSIX", "timestamp", "from", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L347-L378
train
log2timeline/dfdatetime
dfdatetime/posix_time.py
PosixTimeInNanoseconds._CopyToDateTimeString
def _CopyToDateTimeString(self): """Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or None if the timestamp is missing or invalid. """ if self._timestamp is None: return None timestamp, nanoseconds = divmod( self._timestamp, definitions.NANOSECONDS_PER_SECOND) number_of_days, hours, minutes, seconds = self._GetTimeValues(timestamp) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:09d}'.format( year, month, day_of_month, hours, minutes, seconds, nanoseconds)
python
def _CopyToDateTimeString(self): """Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or None if the timestamp is missing or invalid. """ if self._timestamp is None: return None timestamp, nanoseconds = divmod( self._timestamp, definitions.NANOSECONDS_PER_SECOND) number_of_days, hours, minutes, seconds = self._GetTimeValues(timestamp) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:09d}'.format( year, month, day_of_month, hours, minutes, seconds, nanoseconds)
[ "def", "_CopyToDateTimeString", "(", "self", ")", ":", "if", "self", ".", "_timestamp", "is", "None", ":", "return", "None", "timestamp", ",", "nanoseconds", "=", "divmod", "(", "self", ".", "_timestamp", ",", "definitions", ".", "NANOSECONDS_PER_SECOND", ")", "number_of_days", ",", "hours", ",", "minutes", ",", "seconds", "=", "self", ".", "_GetTimeValues", "(", "timestamp", ")", "year", ",", "month", ",", "day_of_month", "=", "self", ".", "_GetDateValuesWithEpoch", "(", "number_of_days", ",", "self", ".", "_EPOCH", ")", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:09d}'", ".", "format", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ",", "nanoseconds", ")" ]
Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or None if the timestamp is missing or invalid.
[ "Copies", "the", "POSIX", "timestamp", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/posix_time.py#L394-L412
train
log2timeline/dfdatetime
dfdatetime/delphi_date_time.py
DelphiDateTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = ( decimal.Decimal(self._timestamp) - self._DELPHI_TO_POSIX_BASE) self._normalized_timestamp *= definitions.SECONDS_PER_DAY return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._timestamp is not None: self._normalized_timestamp = ( decimal.Decimal(self._timestamp) - self._DELPHI_TO_POSIX_BASE) self._normalized_timestamp *= definitions.SECONDS_PER_DAY return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_timestamp", "is", "not", "None", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "-", "self", ".", "_DELPHI_TO_POSIX_BASE", ")", "self", ".", "_normalized_timestamp", "*=", "definitions", ".", "SECONDS_PER_DAY", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/delphi_date_time.py#L56-L71
train
log2timeline/dfdatetime
dfdatetime/delphi_date_time.py
DelphiDateTime.CopyFromDateTimeString
def CopyFromDateTimeString(self, time_string): """Copies a Delphi TDateTime timestamp from a string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the time string is invalid or not supported. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', None) if year > 9999: raise ValueError('Unsupported year value: {0:d}.'.format(year)) timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) timestamp = float(timestamp) / definitions.SECONDS_PER_DAY timestamp += self._DELPHI_TO_POSIX_BASE if microseconds is not None: timestamp += float(microseconds) / definitions.MICROSECONDS_PER_DAY self._normalized_timestamp = None self._timestamp = timestamp self.is_local_time = False
python
def CopyFromDateTimeString(self, time_string): """Copies a Delphi TDateTime timestamp from a string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the time string is invalid or not supported. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', None) if year > 9999: raise ValueError('Unsupported year value: {0:d}.'.format(year)) timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) timestamp = float(timestamp) / definitions.SECONDS_PER_DAY timestamp += self._DELPHI_TO_POSIX_BASE if microseconds is not None: timestamp += float(microseconds) / definitions.MICROSECONDS_PER_DAY self._normalized_timestamp = None self._timestamp = timestamp self.is_local_time = False
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date_time_values", ".", "get", "(", "'month'", ",", "0", ")", "day_of_month", "=", "date_time_values", ".", "get", "(", "'day_of_month'", ",", "0", ")", "hours", "=", "date_time_values", ".", "get", "(", "'hours'", ",", "0", ")", "minutes", "=", "date_time_values", ".", "get", "(", "'minutes'", ",", "0", ")", "seconds", "=", "date_time_values", ".", "get", "(", "'seconds'", ",", "0", ")", "microseconds", "=", "date_time_values", ".", "get", "(", "'microseconds'", ",", "None", ")", "if", "year", ">", "9999", ":", "raise", "ValueError", "(", "'Unsupported year value: {0:d}.'", ".", "format", "(", "year", ")", ")", "timestamp", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "timestamp", "=", "float", "(", "timestamp", ")", "/", "definitions", ".", "SECONDS_PER_DAY", "timestamp", "+=", "self", ".", "_DELPHI_TO_POSIX_BASE", "if", "microseconds", "is", "not", "None", ":", "timestamp", "+=", "float", "(", "microseconds", ")", "/", "definitions", ".", "MICROSECONDS_PER_DAY", "self", ".", "_normalized_timestamp", "=", "None", "self", ".", "_timestamp", "=", "timestamp", "self", ".", "is_local_time", "=", "False" ]
Copies a Delphi TDateTime timestamp from a string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the time string is invalid or not supported.
[ "Copies", "a", "Delphi", "TDateTime", "timestamp", "from", "a", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/delphi_date_time.py#L73-L111
train
log2timeline/dfdatetime
dfdatetime/webkit_time.py
WebKitTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: float: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= self._INT64_MIN and self._timestamp <= self._INT64_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.MICROSECONDS_PER_SECOND) self._normalized_timestamp -= self._WEBKIT_TO_POSIX_BASE return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: float: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= self._INT64_MIN and self._timestamp <= self._INT64_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.MICROSECONDS_PER_SECOND) self._normalized_timestamp -= self._WEBKIT_TO_POSIX_BASE return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "(", "self", ".", "_timestamp", "is", "not", "None", "and", "self", ".", "_timestamp", ">=", "self", ".", "_INT64_MIN", "and", "self", ".", "_timestamp", "<=", "self", ".", "_INT64_MAX", ")", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "/", "definitions", ".", "MICROSECONDS_PER_SECOND", ")", "self", ".", "_normalized_timestamp", "-=", "self", ".", "_WEBKIT_TO_POSIX_BASE", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: float: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/webkit_time.py#L50-L66
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._AdjustForTimeZoneOffset
def _AdjustForTimeZoneOffset( self, year, month, day_of_month, hours, minutes, time_zone_offset): """Adjusts the date and time values for a time zone offset. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. hours (int): hours. minutes (int): minutes. time_zone_offset (int): time zone offset in number of minutes from UTC. Returns: tuple[int, int, int, int, int, int]: time zone correct year, month, day_of_month, hours and minutes values. """ hours_from_utc, minutes_from_utc = divmod(time_zone_offset, 60) minutes += minutes_from_utc # Since divmod makes sure the sign of minutes_from_utc is positive # we only need to check the upper bound here, because hours_from_utc # remains signed it is corrected accordingly. if minutes >= 60: minutes -= 60 hours += 1 hours += hours_from_utc if hours < 0: hours += 24 day_of_month -= 1 elif hours >= 24: hours -= 24 day_of_month += 1 days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1: month -= 1 if month < 1: month = 12 year -= 1 day_of_month += self._GetDaysPerMonth(year, month) elif day_of_month > days_per_month: month += 1 if month > 12: month = 1 year += 1 day_of_month -= days_per_month return year, month, day_of_month, hours, minutes
python
def _AdjustForTimeZoneOffset( self, year, month, day_of_month, hours, minutes, time_zone_offset): """Adjusts the date and time values for a time zone offset. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. hours (int): hours. minutes (int): minutes. time_zone_offset (int): time zone offset in number of minutes from UTC. Returns: tuple[int, int, int, int, int, int]: time zone correct year, month, day_of_month, hours and minutes values. """ hours_from_utc, minutes_from_utc = divmod(time_zone_offset, 60) minutes += minutes_from_utc # Since divmod makes sure the sign of minutes_from_utc is positive # we only need to check the upper bound here, because hours_from_utc # remains signed it is corrected accordingly. if minutes >= 60: minutes -= 60 hours += 1 hours += hours_from_utc if hours < 0: hours += 24 day_of_month -= 1 elif hours >= 24: hours -= 24 day_of_month += 1 days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1: month -= 1 if month < 1: month = 12 year -= 1 day_of_month += self._GetDaysPerMonth(year, month) elif day_of_month > days_per_month: month += 1 if month > 12: month = 1 year += 1 day_of_month -= days_per_month return year, month, day_of_month, hours, minutes
[ "def", "_AdjustForTimeZoneOffset", "(", "self", ",", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "time_zone_offset", ")", ":", "hours_from_utc", ",", "minutes_from_utc", "=", "divmod", "(", "time_zone_offset", ",", "60", ")", "minutes", "+=", "minutes_from_utc", "# Since divmod makes sure the sign of minutes_from_utc is positive", "# we only need to check the upper bound here, because hours_from_utc", "# remains signed it is corrected accordingly.", "if", "minutes", ">=", "60", ":", "minutes", "-=", "60", "hours", "+=", "1", "hours", "+=", "hours_from_utc", "if", "hours", "<", "0", ":", "hours", "+=", "24", "day_of_month", "-=", "1", "elif", "hours", ">=", "24", ":", "hours", "-=", "24", "day_of_month", "+=", "1", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "if", "day_of_month", "<", "1", ":", "month", "-=", "1", "if", "month", "<", "1", ":", "month", "=", "12", "year", "-=", "1", "day_of_month", "+=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "elif", "day_of_month", ">", "days_per_month", ":", "month", "+=", "1", "if", "month", ">", "12", ":", "month", "=", "1", "year", "+=", "1", "day_of_month", "-=", "days_per_month", "return", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes" ]
Adjusts the date and time values for a time zone offset. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. hours (int): hours. minutes (int): minutes. time_zone_offset (int): time zone offset in number of minutes from UTC. Returns: tuple[int, int, int, int, int, int]: time zone correct year, month, day_of_month, hours and minutes values.
[ "Adjusts", "the", "date", "and", "time", "values", "for", "a", "time", "zone", "offset", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L235-L288
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._CopyDateFromString
def _CopyDateFromString(self, date_string): """Copies a date from a string. Args: date_string (str): date value formatted as: YYYY-MM-DD Returns: tuple[int, int, int]: year, month, day of month. Raises: ValueError: if the date string is invalid or not supported. """ date_string_length = len(date_string) # The date string should at least contain 'YYYY-MM-DD'. if date_string_length < 10: raise ValueError('Date string too short.') if date_string[4] != '-' or date_string[7] != '-': raise ValueError('Invalid date string.') try: year = int(date_string[0:4], 10) except ValueError: raise ValueError('Unable to parse year.') try: month = int(date_string[5:7], 10) except ValueError: raise ValueError('Unable to parse month.') try: day_of_month = int(date_string[8:10], 10) except ValueError: raise ValueError('Unable to parse day of month.') days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') return year, month, day_of_month
python
def _CopyDateFromString(self, date_string): """Copies a date from a string. Args: date_string (str): date value formatted as: YYYY-MM-DD Returns: tuple[int, int, int]: year, month, day of month. Raises: ValueError: if the date string is invalid or not supported. """ date_string_length = len(date_string) # The date string should at least contain 'YYYY-MM-DD'. if date_string_length < 10: raise ValueError('Date string too short.') if date_string[4] != '-' or date_string[7] != '-': raise ValueError('Invalid date string.') try: year = int(date_string[0:4], 10) except ValueError: raise ValueError('Unable to parse year.') try: month = int(date_string[5:7], 10) except ValueError: raise ValueError('Unable to parse month.') try: day_of_month = int(date_string[8:10], 10) except ValueError: raise ValueError('Unable to parse day of month.') days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') return year, month, day_of_month
[ "def", "_CopyDateFromString", "(", "self", ",", "date_string", ")", ":", "date_string_length", "=", "len", "(", "date_string", ")", "# The date string should at least contain 'YYYY-MM-DD'.", "if", "date_string_length", "<", "10", ":", "raise", "ValueError", "(", "'Date string too short.'", ")", "if", "date_string", "[", "4", "]", "!=", "'-'", "or", "date_string", "[", "7", "]", "!=", "'-'", ":", "raise", "ValueError", "(", "'Invalid date string.'", ")", "try", ":", "year", "=", "int", "(", "date_string", "[", "0", ":", "4", "]", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse year.'", ")", "try", ":", "month", "=", "int", "(", "date_string", "[", "5", ":", "7", "]", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse month.'", ")", "try", ":", "day_of_month", "=", "int", "(", "date_string", "[", "8", ":", "10", "]", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse day of month.'", ")", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "if", "day_of_month", "<", "1", "or", "day_of_month", ">", "days_per_month", ":", "raise", "ValueError", "(", "'Day of month value out of bounds.'", ")", "return", "year", ",", "month", ",", "day_of_month" ]
Copies a date from a string. Args: date_string (str): date value formatted as: YYYY-MM-DD Returns: tuple[int, int, int]: year, month, day of month. Raises: ValueError: if the date string is invalid or not supported.
[ "Copies", "a", "date", "from", "a", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L290-L330
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._CopyTimeFromString
def _CopyTimeFromString(self, time_string): """Copies a time from a string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The seconds fraction and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported. """ time_string_length = len(time_string) # The time string should at least contain 'hh:mm:ss'. if time_string_length < 8: raise ValueError('Time string too short.') if time_string[2] != ':' or time_string[5] != ':': raise ValueError('Invalid time string.') try: hours = int(time_string[0:2], 10) except ValueError: raise ValueError('Unable to parse hours.') if hours not in range(0, 24): raise ValueError('Hours value: {0:d} out of bounds.'.format(hours)) try: minutes = int(time_string[3:5], 10) except ValueError: raise ValueError('Unable to parse minutes.') if minutes not in range(0, 60): raise ValueError('Minutes value: {0:d} out of bounds.'.format(minutes)) try: seconds = int(time_string[6:8], 10) except ValueError: raise ValueError('Unable to parse day of seconds.') # TODO: support a leap second? if seconds not in range(0, 60): raise ValueError('Seconds value: {0:d} out of bounds.'.format(seconds)) microseconds = None time_zone_offset = None time_zone_string_index = 8 while time_zone_string_index < time_string_length: if time_string[time_zone_string_index] in ('+', '-'): break time_zone_string_index += 1 # The calculations that follow rely on the time zone string index # to point beyond the string in case no time zone offset was defined. if time_zone_string_index == time_string_length - 1: time_zone_string_index += 1 if time_string_length > 8 and time_string[8] == '.': time_fraction_length = time_zone_string_index - 9 if time_fraction_length not in (3, 6): raise ValueError('Invalid time string.') try: time_fraction = time_string[9:time_zone_string_index] time_fraction = int(time_fraction, 10) except ValueError: raise ValueError('Unable to parse time fraction.') if time_fraction_length == 3: time_fraction *= 1000 microseconds = time_fraction if time_zone_string_index < time_string_length: if (time_string_length - time_zone_string_index != 6 or time_string[time_zone_string_index + 3] != ':'): raise ValueError('Invalid time string.') try: hours_from_utc = int(time_string[ time_zone_string_index + 1:time_zone_string_index + 3]) except ValueError: raise ValueError('Unable to parse time zone hours offset.') if hours_from_utc not in range(0, 15): raise ValueError('Time zone hours offset value out of bounds.') try: minutes_from_utc = int(time_string[ time_zone_string_index + 4:time_zone_string_index + 6]) except ValueError: raise ValueError('Unable to parse time zone minutes offset.') if minutes_from_utc not in range(0, 60): raise ValueError('Time zone minutes offset value out of bounds.') # pylint: disable=invalid-unary-operand-type time_zone_offset = (hours_from_utc * 60) + minutes_from_utc # Note that when the sign of the time zone offset is negative # the difference needs to be added. We do so by flipping the sign. if time_string[time_zone_string_index] != '-': time_zone_offset = -time_zone_offset return hours, minutes, seconds, microseconds, time_zone_offset
python
def _CopyTimeFromString(self, time_string): """Copies a time from a string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The seconds fraction and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported. """ time_string_length = len(time_string) # The time string should at least contain 'hh:mm:ss'. if time_string_length < 8: raise ValueError('Time string too short.') if time_string[2] != ':' or time_string[5] != ':': raise ValueError('Invalid time string.') try: hours = int(time_string[0:2], 10) except ValueError: raise ValueError('Unable to parse hours.') if hours not in range(0, 24): raise ValueError('Hours value: {0:d} out of bounds.'.format(hours)) try: minutes = int(time_string[3:5], 10) except ValueError: raise ValueError('Unable to parse minutes.') if minutes not in range(0, 60): raise ValueError('Minutes value: {0:d} out of bounds.'.format(minutes)) try: seconds = int(time_string[6:8], 10) except ValueError: raise ValueError('Unable to parse day of seconds.') # TODO: support a leap second? if seconds not in range(0, 60): raise ValueError('Seconds value: {0:d} out of bounds.'.format(seconds)) microseconds = None time_zone_offset = None time_zone_string_index = 8 while time_zone_string_index < time_string_length: if time_string[time_zone_string_index] in ('+', '-'): break time_zone_string_index += 1 # The calculations that follow rely on the time zone string index # to point beyond the string in case no time zone offset was defined. if time_zone_string_index == time_string_length - 1: time_zone_string_index += 1 if time_string_length > 8 and time_string[8] == '.': time_fraction_length = time_zone_string_index - 9 if time_fraction_length not in (3, 6): raise ValueError('Invalid time string.') try: time_fraction = time_string[9:time_zone_string_index] time_fraction = int(time_fraction, 10) except ValueError: raise ValueError('Unable to parse time fraction.') if time_fraction_length == 3: time_fraction *= 1000 microseconds = time_fraction if time_zone_string_index < time_string_length: if (time_string_length - time_zone_string_index != 6 or time_string[time_zone_string_index + 3] != ':'): raise ValueError('Invalid time string.') try: hours_from_utc = int(time_string[ time_zone_string_index + 1:time_zone_string_index + 3]) except ValueError: raise ValueError('Unable to parse time zone hours offset.') if hours_from_utc not in range(0, 15): raise ValueError('Time zone hours offset value out of bounds.') try: minutes_from_utc = int(time_string[ time_zone_string_index + 4:time_zone_string_index + 6]) except ValueError: raise ValueError('Unable to parse time zone minutes offset.') if minutes_from_utc not in range(0, 60): raise ValueError('Time zone minutes offset value out of bounds.') # pylint: disable=invalid-unary-operand-type time_zone_offset = (hours_from_utc * 60) + minutes_from_utc # Note that when the sign of the time zone offset is negative # the difference needs to be added. We do so by flipping the sign. if time_string[time_zone_string_index] != '-': time_zone_offset = -time_zone_offset return hours, minutes, seconds, microseconds, time_zone_offset
[ "def", "_CopyTimeFromString", "(", "self", ",", "time_string", ")", ":", "time_string_length", "=", "len", "(", "time_string", ")", "# The time string should at least contain 'hh:mm:ss'.", "if", "time_string_length", "<", "8", ":", "raise", "ValueError", "(", "'Time string too short.'", ")", "if", "time_string", "[", "2", "]", "!=", "':'", "or", "time_string", "[", "5", "]", "!=", "':'", ":", "raise", "ValueError", "(", "'Invalid time string.'", ")", "try", ":", "hours", "=", "int", "(", "time_string", "[", "0", ":", "2", "]", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse hours.'", ")", "if", "hours", "not", "in", "range", "(", "0", ",", "24", ")", ":", "raise", "ValueError", "(", "'Hours value: {0:d} out of bounds.'", ".", "format", "(", "hours", ")", ")", "try", ":", "minutes", "=", "int", "(", "time_string", "[", "3", ":", "5", "]", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse minutes.'", ")", "if", "minutes", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Minutes value: {0:d} out of bounds.'", ".", "format", "(", "minutes", ")", ")", "try", ":", "seconds", "=", "int", "(", "time_string", "[", "6", ":", "8", "]", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse day of seconds.'", ")", "# TODO: support a leap second?", "if", "seconds", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Seconds value: {0:d} out of bounds.'", ".", "format", "(", "seconds", ")", ")", "microseconds", "=", "None", "time_zone_offset", "=", "None", "time_zone_string_index", "=", "8", "while", "time_zone_string_index", "<", "time_string_length", ":", "if", "time_string", "[", "time_zone_string_index", "]", "in", "(", "'+'", ",", "'-'", ")", ":", "break", "time_zone_string_index", "+=", "1", "# The calculations that follow rely on the time zone string index", "# to point beyond the string in case no time zone offset was defined.", "if", "time_zone_string_index", "==", "time_string_length", "-", "1", ":", "time_zone_string_index", "+=", "1", "if", "time_string_length", ">", "8", "and", "time_string", "[", "8", "]", "==", "'.'", ":", "time_fraction_length", "=", "time_zone_string_index", "-", "9", "if", "time_fraction_length", "not", "in", "(", "3", ",", "6", ")", ":", "raise", "ValueError", "(", "'Invalid time string.'", ")", "try", ":", "time_fraction", "=", "time_string", "[", "9", ":", "time_zone_string_index", "]", "time_fraction", "=", "int", "(", "time_fraction", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse time fraction.'", ")", "if", "time_fraction_length", "==", "3", ":", "time_fraction", "*=", "1000", "microseconds", "=", "time_fraction", "if", "time_zone_string_index", "<", "time_string_length", ":", "if", "(", "time_string_length", "-", "time_zone_string_index", "!=", "6", "or", "time_string", "[", "time_zone_string_index", "+", "3", "]", "!=", "':'", ")", ":", "raise", "ValueError", "(", "'Invalid time string.'", ")", "try", ":", "hours_from_utc", "=", "int", "(", "time_string", "[", "time_zone_string_index", "+", "1", ":", "time_zone_string_index", "+", "3", "]", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse time zone hours offset.'", ")", "if", "hours_from_utc", "not", "in", "range", "(", "0", ",", "15", ")", ":", "raise", "ValueError", "(", "'Time zone hours offset value out of bounds.'", ")", "try", ":", "minutes_from_utc", "=", "int", "(", "time_string", "[", "time_zone_string_index", "+", "4", ":", "time_zone_string_index", "+", "6", "]", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse time zone minutes offset.'", ")", "if", "minutes_from_utc", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Time zone minutes offset value out of bounds.'", ")", "# pylint: disable=invalid-unary-operand-type", "time_zone_offset", "=", "(", "hours_from_utc", "*", "60", ")", "+", "minutes_from_utc", "# Note that when the sign of the time zone offset is negative", "# the difference needs to be added. We do so by flipping the sign.", "if", "time_string", "[", "time_zone_string_index", "]", "!=", "'-'", ":", "time_zone_offset", "=", "-", "time_zone_offset", "return", "hours", ",", "minutes", ",", "seconds", ",", "microseconds", ",", "time_zone_offset" ]
Copies a time from a string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The seconds fraction and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported.
[ "Copies", "a", "time", "from", "a", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L389-L503
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._GetDateValues
def _GetDateValues( self, number_of_days, epoch_year, epoch_month, epoch_day_of_month): """Determines date values. Args: number_of_days (int): number of days since epoch. epoch_year (int): year that is the start of the epoch e.g. 1970. epoch_month (int): month that is the start of the epoch, where 1 represents January. epoch_day_of_month (int): day of month that is the start of the epoch, where 1 represents the first day. Returns: tuple[int, int, int]: year, month, day of month. Raises: ValueError: if the epoch year, month or day of month values are out of bounds. """ if epoch_year < 0: raise ValueError('Epoch year value: {0:d} out of bounds.'.format( epoch_year)) if epoch_month not in range(1, 13): raise ValueError('Epoch month value: {0:d} out of bounds.'.format( epoch_month)) epoch_days_per_month = self._GetDaysPerMonth(epoch_year, epoch_month) if epoch_day_of_month < 1 or epoch_day_of_month > epoch_days_per_month: raise ValueError('Epoch day of month value: {0:d} out of bounds.'.format( epoch_day_of_month)) before_epoch = number_of_days < 0 year = epoch_year month = epoch_month if before_epoch: month -= 1 if month <= 0: month = 12 year -= 1 number_of_days += epoch_day_of_month if before_epoch: number_of_days *= -1 # Align with the start of the year. while month > 1: days_per_month = self._GetDaysPerMonth(year, month) if number_of_days < days_per_month: break if before_epoch: month -= 1 else: month += 1 if month > 12: month = 1 year += 1 number_of_days -= days_per_month # Align with the start of the next century. _, remainder = divmod(year, 100) for _ in range(remainder, 100): days_in_year = self._GetNumberOfDaysInYear(year) if number_of_days < days_in_year: break if before_epoch: year -= 1 else: year += 1 number_of_days -= days_in_year days_in_century = self._GetNumberOfDaysInCentury(year) while number_of_days > days_in_century: if before_epoch: year -= 100 else: year += 100 number_of_days -= days_in_century days_in_century = self._GetNumberOfDaysInCentury(year) days_in_year = self._GetNumberOfDaysInYear(year) while number_of_days > days_in_year: if before_epoch: year -= 1 else: year += 1 number_of_days -= days_in_year days_in_year = self._GetNumberOfDaysInYear(year) days_per_month = self._GetDaysPerMonth(year, month) while number_of_days > days_per_month: if before_epoch: month -= 1 else: month += 1 if month <= 0: month = 12 year -= 1 elif month > 12: month = 1 year += 1 number_of_days -= days_per_month days_per_month = self._GetDaysPerMonth(year, month) if before_epoch: days_per_month = self._GetDaysPerMonth(year, month) number_of_days = days_per_month - number_of_days elif number_of_days == 0: number_of_days = 31 month = 12 year -= 1 return year, month, number_of_days
python
def _GetDateValues( self, number_of_days, epoch_year, epoch_month, epoch_day_of_month): """Determines date values. Args: number_of_days (int): number of days since epoch. epoch_year (int): year that is the start of the epoch e.g. 1970. epoch_month (int): month that is the start of the epoch, where 1 represents January. epoch_day_of_month (int): day of month that is the start of the epoch, where 1 represents the first day. Returns: tuple[int, int, int]: year, month, day of month. Raises: ValueError: if the epoch year, month or day of month values are out of bounds. """ if epoch_year < 0: raise ValueError('Epoch year value: {0:d} out of bounds.'.format( epoch_year)) if epoch_month not in range(1, 13): raise ValueError('Epoch month value: {0:d} out of bounds.'.format( epoch_month)) epoch_days_per_month = self._GetDaysPerMonth(epoch_year, epoch_month) if epoch_day_of_month < 1 or epoch_day_of_month > epoch_days_per_month: raise ValueError('Epoch day of month value: {0:d} out of bounds.'.format( epoch_day_of_month)) before_epoch = number_of_days < 0 year = epoch_year month = epoch_month if before_epoch: month -= 1 if month <= 0: month = 12 year -= 1 number_of_days += epoch_day_of_month if before_epoch: number_of_days *= -1 # Align with the start of the year. while month > 1: days_per_month = self._GetDaysPerMonth(year, month) if number_of_days < days_per_month: break if before_epoch: month -= 1 else: month += 1 if month > 12: month = 1 year += 1 number_of_days -= days_per_month # Align with the start of the next century. _, remainder = divmod(year, 100) for _ in range(remainder, 100): days_in_year = self._GetNumberOfDaysInYear(year) if number_of_days < days_in_year: break if before_epoch: year -= 1 else: year += 1 number_of_days -= days_in_year days_in_century = self._GetNumberOfDaysInCentury(year) while number_of_days > days_in_century: if before_epoch: year -= 100 else: year += 100 number_of_days -= days_in_century days_in_century = self._GetNumberOfDaysInCentury(year) days_in_year = self._GetNumberOfDaysInYear(year) while number_of_days > days_in_year: if before_epoch: year -= 1 else: year += 1 number_of_days -= days_in_year days_in_year = self._GetNumberOfDaysInYear(year) days_per_month = self._GetDaysPerMonth(year, month) while number_of_days > days_per_month: if before_epoch: month -= 1 else: month += 1 if month <= 0: month = 12 year -= 1 elif month > 12: month = 1 year += 1 number_of_days -= days_per_month days_per_month = self._GetDaysPerMonth(year, month) if before_epoch: days_per_month = self._GetDaysPerMonth(year, month) number_of_days = days_per_month - number_of_days elif number_of_days == 0: number_of_days = 31 month = 12 year -= 1 return year, month, number_of_days
[ "def", "_GetDateValues", "(", "self", ",", "number_of_days", ",", "epoch_year", ",", "epoch_month", ",", "epoch_day_of_month", ")", ":", "if", "epoch_year", "<", "0", ":", "raise", "ValueError", "(", "'Epoch year value: {0:d} out of bounds.'", ".", "format", "(", "epoch_year", ")", ")", "if", "epoch_month", "not", "in", "range", "(", "1", ",", "13", ")", ":", "raise", "ValueError", "(", "'Epoch month value: {0:d} out of bounds.'", ".", "format", "(", "epoch_month", ")", ")", "epoch_days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "epoch_year", ",", "epoch_month", ")", "if", "epoch_day_of_month", "<", "1", "or", "epoch_day_of_month", ">", "epoch_days_per_month", ":", "raise", "ValueError", "(", "'Epoch day of month value: {0:d} out of bounds.'", ".", "format", "(", "epoch_day_of_month", ")", ")", "before_epoch", "=", "number_of_days", "<", "0", "year", "=", "epoch_year", "month", "=", "epoch_month", "if", "before_epoch", ":", "month", "-=", "1", "if", "month", "<=", "0", ":", "month", "=", "12", "year", "-=", "1", "number_of_days", "+=", "epoch_day_of_month", "if", "before_epoch", ":", "number_of_days", "*=", "-", "1", "# Align with the start of the year.", "while", "month", ">", "1", ":", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "if", "number_of_days", "<", "days_per_month", ":", "break", "if", "before_epoch", ":", "month", "-=", "1", "else", ":", "month", "+=", "1", "if", "month", ">", "12", ":", "month", "=", "1", "year", "+=", "1", "number_of_days", "-=", "days_per_month", "# Align with the start of the next century.", "_", ",", "remainder", "=", "divmod", "(", "year", ",", "100", ")", "for", "_", "in", "range", "(", "remainder", ",", "100", ")", ":", "days_in_year", "=", "self", ".", "_GetNumberOfDaysInYear", "(", "year", ")", "if", "number_of_days", "<", "days_in_year", ":", "break", "if", "before_epoch", ":", "year", "-=", "1", "else", ":", "year", "+=", "1", "number_of_days", "-=", "days_in_year", "days_in_century", "=", "self", ".", "_GetNumberOfDaysInCentury", "(", "year", ")", "while", "number_of_days", ">", "days_in_century", ":", "if", "before_epoch", ":", "year", "-=", "100", "else", ":", "year", "+=", "100", "number_of_days", "-=", "days_in_century", "days_in_century", "=", "self", ".", "_GetNumberOfDaysInCentury", "(", "year", ")", "days_in_year", "=", "self", ".", "_GetNumberOfDaysInYear", "(", "year", ")", "while", "number_of_days", ">", "days_in_year", ":", "if", "before_epoch", ":", "year", "-=", "1", "else", ":", "year", "+=", "1", "number_of_days", "-=", "days_in_year", "days_in_year", "=", "self", ".", "_GetNumberOfDaysInYear", "(", "year", ")", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "while", "number_of_days", ">", "days_per_month", ":", "if", "before_epoch", ":", "month", "-=", "1", "else", ":", "month", "+=", "1", "if", "month", "<=", "0", ":", "month", "=", "12", "year", "-=", "1", "elif", "month", ">", "12", ":", "month", "=", "1", "year", "+=", "1", "number_of_days", "-=", "days_per_month", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "if", "before_epoch", ":", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "number_of_days", "=", "days_per_month", "-", "number_of_days", "elif", "number_of_days", "==", "0", ":", "number_of_days", "=", "31", "month", "=", "12", "year", "-=", "1", "return", "year", ",", "month", ",", "number_of_days" ]
Determines date values. Args: number_of_days (int): number of days since epoch. epoch_year (int): year that is the start of the epoch e.g. 1970. epoch_month (int): month that is the start of the epoch, where 1 represents January. epoch_day_of_month (int): day of month that is the start of the epoch, where 1 represents the first day. Returns: tuple[int, int, int]: year, month, day of month. Raises: ValueError: if the epoch year, month or day of month values are out of bounds.
[ "Determines", "date", "values", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L505-L628
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._GetDateValuesWithEpoch
def _GetDateValuesWithEpoch(self, number_of_days, date_time_epoch): """Determines date values. Args: number_of_days (int): number of days since epoch. date_time_epoch (DateTimeEpoch): date and time of the epoch. Returns: tuple[int, int, int]: year, month, day of month. """ return self._GetDateValues( number_of_days, date_time_epoch.year, date_time_epoch.month, date_time_epoch.day_of_month)
python
def _GetDateValuesWithEpoch(self, number_of_days, date_time_epoch): """Determines date values. Args: number_of_days (int): number of days since epoch. date_time_epoch (DateTimeEpoch): date and time of the epoch. Returns: tuple[int, int, int]: year, month, day of month. """ return self._GetDateValues( number_of_days, date_time_epoch.year, date_time_epoch.month, date_time_epoch.day_of_month)
[ "def", "_GetDateValuesWithEpoch", "(", "self", ",", "number_of_days", ",", "date_time_epoch", ")", ":", "return", "self", ".", "_GetDateValues", "(", "number_of_days", ",", "date_time_epoch", ".", "year", ",", "date_time_epoch", ".", "month", ",", "date_time_epoch", ".", "day_of_month", ")" ]
Determines date values. Args: number_of_days (int): number of days since epoch. date_time_epoch (DateTimeEpoch): date and time of the epoch. Returns: tuple[int, int, int]: year, month, day of month.
[ "Determines", "date", "values", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L630-L642
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._GetDayOfYear
def _GetDayOfYear(self, year, month, day_of_month): """Retrieves the day of the year for a specific day of a month in a year. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. Returns: int: day of year. Raises: ValueError: if the month or day of month value is out of bounds. """ if month not in range(1, 13): raise ValueError('Month value out of bounds.') days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') day_of_year = day_of_month for past_month in range(1, month): day_of_year += self._GetDaysPerMonth(year, past_month) return day_of_year
python
def _GetDayOfYear(self, year, month, day_of_month): """Retrieves the day of the year for a specific day of a month in a year. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. Returns: int: day of year. Raises: ValueError: if the month or day of month value is out of bounds. """ if month not in range(1, 13): raise ValueError('Month value out of bounds.') days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') day_of_year = day_of_month for past_month in range(1, month): day_of_year += self._GetDaysPerMonth(year, past_month) return day_of_year
[ "def", "_GetDayOfYear", "(", "self", ",", "year", ",", "month", ",", "day_of_month", ")", ":", "if", "month", "not", "in", "range", "(", "1", ",", "13", ")", ":", "raise", "ValueError", "(", "'Month value out of bounds.'", ")", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "if", "day_of_month", "<", "1", "or", "day_of_month", ">", "days_per_month", ":", "raise", "ValueError", "(", "'Day of month value out of bounds.'", ")", "day_of_year", "=", "day_of_month", "for", "past_month", "in", "range", "(", "1", ",", "month", ")", ":", "day_of_year", "+=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "past_month", ")", "return", "day_of_year" ]
Retrieves the day of the year for a specific day of a month in a year. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. Returns: int: day of year. Raises: ValueError: if the month or day of month value is out of bounds.
[ "Retrieves", "the", "day", "of", "the", "year", "for", "a", "specific", "day", "of", "a", "month", "in", "a", "year", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L644-L669
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._GetDaysPerMonth
def _GetDaysPerMonth(self, year, month): """Retrieves the number of days in a month of a specific year. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. Returns: int: number of days in the month. Raises: ValueError: if the month value is out of bounds. """ if month not in range(1, 13): raise ValueError('Month value out of bounds.') days_per_month = self._DAYS_PER_MONTH[month - 1] if month == 2 and self._IsLeapYear(year): days_per_month += 1 return days_per_month
python
def _GetDaysPerMonth(self, year, month): """Retrieves the number of days in a month of a specific year. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. Returns: int: number of days in the month. Raises: ValueError: if the month value is out of bounds. """ if month not in range(1, 13): raise ValueError('Month value out of bounds.') days_per_month = self._DAYS_PER_MONTH[month - 1] if month == 2 and self._IsLeapYear(year): days_per_month += 1 return days_per_month
[ "def", "_GetDaysPerMonth", "(", "self", ",", "year", ",", "month", ")", ":", "if", "month", "not", "in", "range", "(", "1", ",", "13", ")", ":", "raise", "ValueError", "(", "'Month value out of bounds.'", ")", "days_per_month", "=", "self", ".", "_DAYS_PER_MONTH", "[", "month", "-", "1", "]", "if", "month", "==", "2", "and", "self", ".", "_IsLeapYear", "(", "year", ")", ":", "days_per_month", "+=", "1", "return", "days_per_month" ]
Retrieves the number of days in a month of a specific year. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. Returns: int: number of days in the month. Raises: ValueError: if the month value is out of bounds.
[ "Retrieves", "the", "number", "of", "days", "in", "a", "month", "of", "a", "specific", "year", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L671-L691
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._GetNumberOfDaysInCentury
def _GetNumberOfDaysInCentury(self, year): """Retrieves the number of days in a century. Args: year (int): year in the century e.g. 1970. Returns: int: number of (remaining) days in the century. Raises: ValueError: if the year value is out of bounds. """ if year < 0: raise ValueError('Year value out of bounds.') year, _ = divmod(year, 100) if self._IsLeapYear(year): return 36525 return 36524
python
def _GetNumberOfDaysInCentury(self, year): """Retrieves the number of days in a century. Args: year (int): year in the century e.g. 1970. Returns: int: number of (remaining) days in the century. Raises: ValueError: if the year value is out of bounds. """ if year < 0: raise ValueError('Year value out of bounds.') year, _ = divmod(year, 100) if self._IsLeapYear(year): return 36525 return 36524
[ "def", "_GetNumberOfDaysInCentury", "(", "self", ",", "year", ")", ":", "if", "year", "<", "0", ":", "raise", "ValueError", "(", "'Year value out of bounds.'", ")", "year", ",", "_", "=", "divmod", "(", "year", ",", "100", ")", "if", "self", ".", "_IsLeapYear", "(", "year", ")", ":", "return", "36525", "return", "36524" ]
Retrieves the number of days in a century. Args: year (int): year in the century e.g. 1970. Returns: int: number of (remaining) days in the century. Raises: ValueError: if the year value is out of bounds.
[ "Retrieves", "the", "number", "of", "days", "in", "a", "century", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L704-L723
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._GetNumberOfSecondsFromElements
def _GetNumberOfSecondsFromElements( self, year, month, day_of_month, hours, minutes, seconds): """Retrieves the number of seconds from the date and time elements. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. hours (int): hours. minutes (int): minutes. seconds (int): seconds. Returns: int: number of seconds since January 1, 1970 00:00:00 or None if year, month or day of month are not set. Raises: ValueError: if the time elements are invalid. """ if not year or not month or not day_of_month: return None # calendar.timegm does not sanity check the time elements. if hours is None: hours = 0 elif hours not in range(0, 24): raise ValueError('Hours value: {0!s} out of bounds.'.format(hours)) if minutes is None: minutes = 0 elif minutes not in range(0, 60): raise ValueError('Minutes value: {0!s} out of bounds.'.format(minutes)) # TODO: support a leap second? if seconds is None: seconds = 0 elif seconds not in range(0, 60): raise ValueError('Seconds value: {0!s} out of bounds.'.format(seconds)) # Note that calendar.timegm() does not raise when date is: 2013-02-29. days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') # calendar.timegm requires the time tuple to contain at least # 6 integer values. time_elements_tuple = (year, month, day_of_month, hours, minutes, seconds) number_of_seconds = calendar.timegm(time_elements_tuple) return int(number_of_seconds)
python
def _GetNumberOfSecondsFromElements( self, year, month, day_of_month, hours, minutes, seconds): """Retrieves the number of seconds from the date and time elements. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. hours (int): hours. minutes (int): minutes. seconds (int): seconds. Returns: int: number of seconds since January 1, 1970 00:00:00 or None if year, month or day of month are not set. Raises: ValueError: if the time elements are invalid. """ if not year or not month or not day_of_month: return None # calendar.timegm does not sanity check the time elements. if hours is None: hours = 0 elif hours not in range(0, 24): raise ValueError('Hours value: {0!s} out of bounds.'.format(hours)) if minutes is None: minutes = 0 elif minutes not in range(0, 60): raise ValueError('Minutes value: {0!s} out of bounds.'.format(minutes)) # TODO: support a leap second? if seconds is None: seconds = 0 elif seconds not in range(0, 60): raise ValueError('Seconds value: {0!s} out of bounds.'.format(seconds)) # Note that calendar.timegm() does not raise when date is: 2013-02-29. days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') # calendar.timegm requires the time tuple to contain at least # 6 integer values. time_elements_tuple = (year, month, day_of_month, hours, minutes, seconds) number_of_seconds = calendar.timegm(time_elements_tuple) return int(number_of_seconds)
[ "def", "_GetNumberOfSecondsFromElements", "(", "self", ",", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", ":", "if", "not", "year", "or", "not", "month", "or", "not", "day_of_month", ":", "return", "None", "# calendar.timegm does not sanity check the time elements.", "if", "hours", "is", "None", ":", "hours", "=", "0", "elif", "hours", "not", "in", "range", "(", "0", ",", "24", ")", ":", "raise", "ValueError", "(", "'Hours value: {0!s} out of bounds.'", ".", "format", "(", "hours", ")", ")", "if", "minutes", "is", "None", ":", "minutes", "=", "0", "elif", "minutes", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Minutes value: {0!s} out of bounds.'", ".", "format", "(", "minutes", ")", ")", "# TODO: support a leap second?", "if", "seconds", "is", "None", ":", "seconds", "=", "0", "elif", "seconds", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Seconds value: {0!s} out of bounds.'", ".", "format", "(", "seconds", ")", ")", "# Note that calendar.timegm() does not raise when date is: 2013-02-29.", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "if", "day_of_month", "<", "1", "or", "day_of_month", ">", "days_per_month", ":", "raise", "ValueError", "(", "'Day of month value out of bounds.'", ")", "# calendar.timegm requires the time tuple to contain at least", "# 6 integer values.", "time_elements_tuple", "=", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "number_of_seconds", "=", "calendar", ".", "timegm", "(", "time_elements_tuple", ")", "return", "int", "(", "number_of_seconds", ")" ]
Retrieves the number of seconds from the date and time elements. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. hours (int): hours. minutes (int): minutes. seconds (int): seconds. Returns: int: number of seconds since January 1, 1970 00:00:00 or None if year, month or day of month are not set. Raises: ValueError: if the time elements are invalid.
[ "Retrieves", "the", "number", "of", "seconds", "from", "the", "date", "and", "time", "elements", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L738-L788
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues._GetTimeValues
def _GetTimeValues(self, number_of_seconds): """Determines time values. Args: number_of_seconds (int|decimal.Decimal): number of seconds. Returns: tuple[int, int, int, int]: days, hours, minutes, seconds. """ number_of_seconds = int(number_of_seconds) number_of_minutes, seconds = divmod(number_of_seconds, 60) number_of_hours, minutes = divmod(number_of_minutes, 60) number_of_days, hours = divmod(number_of_hours, 24) return number_of_days, hours, minutes, seconds
python
def _GetTimeValues(self, number_of_seconds): """Determines time values. Args: number_of_seconds (int|decimal.Decimal): number of seconds. Returns: tuple[int, int, int, int]: days, hours, minutes, seconds. """ number_of_seconds = int(number_of_seconds) number_of_minutes, seconds = divmod(number_of_seconds, 60) number_of_hours, minutes = divmod(number_of_minutes, 60) number_of_days, hours = divmod(number_of_hours, 24) return number_of_days, hours, minutes, seconds
[ "def", "_GetTimeValues", "(", "self", ",", "number_of_seconds", ")", ":", "number_of_seconds", "=", "int", "(", "number_of_seconds", ")", "number_of_minutes", ",", "seconds", "=", "divmod", "(", "number_of_seconds", ",", "60", ")", "number_of_hours", ",", "minutes", "=", "divmod", "(", "number_of_minutes", ",", "60", ")", "number_of_days", ",", "hours", "=", "divmod", "(", "number_of_hours", ",", "24", ")", "return", "number_of_days", ",", "hours", ",", "minutes", ",", "seconds" ]
Determines time values. Args: number_of_seconds (int|decimal.Decimal): number of seconds. Returns: tuple[int, int, int, int]: days, hours, minutes, seconds.
[ "Determines", "time", "values", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L790-L803
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues.CopyToStatTimeTuple
def CopyToStatTimeTuple(self): """Copies the date time value to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None if self._precision in ( definitions.PRECISION_1_NANOSECOND, definitions.PRECISION_100_NANOSECONDS, definitions.PRECISION_1_MICROSECOND, definitions.PRECISION_1_MILLISECOND, definitions.PRECISION_100_MILLISECONDS): remainder = int((normalized_timestamp % 1) * self._100NS_PER_SECOND) return int(normalized_timestamp), remainder return int(normalized_timestamp), None
python
def CopyToStatTimeTuple(self): """Copies the date time value to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None if self._precision in ( definitions.PRECISION_1_NANOSECOND, definitions.PRECISION_100_NANOSECONDS, definitions.PRECISION_1_MICROSECOND, definitions.PRECISION_1_MILLISECOND, definitions.PRECISION_100_MILLISECONDS): remainder = int((normalized_timestamp % 1) * self._100NS_PER_SECOND) return int(normalized_timestamp), remainder return int(normalized_timestamp), None
[ "def", "CopyToStatTimeTuple", "(", "self", ")", ":", "normalized_timestamp", "=", "self", ".", "_GetNormalizedTimestamp", "(", ")", "if", "normalized_timestamp", "is", "None", ":", "return", "None", ",", "None", "if", "self", ".", "_precision", "in", "(", "definitions", ".", "PRECISION_1_NANOSECOND", ",", "definitions", ".", "PRECISION_100_NANOSECONDS", ",", "definitions", ".", "PRECISION_1_MICROSECOND", ",", "definitions", ".", "PRECISION_1_MILLISECOND", ",", "definitions", ".", "PRECISION_100_MILLISECONDS", ")", ":", "remainder", "=", "int", "(", "(", "normalized_timestamp", "%", "1", ")", "*", "self", ".", "_100NS_PER_SECOND", ")", "return", "int", "(", "normalized_timestamp", ")", ",", "remainder", "return", "int", "(", "normalized_timestamp", ")", ",", "None" ]
Copies the date time value to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error.
[ "Copies", "the", "date", "time", "value", "to", "a", "stat", "timestamp", "tuple", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L865-L886
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues.CopyToDateTimeStringISO8601
def CopyToDateTimeStringISO8601(self): """Copies the date time value to an ISO 8601 date and time string. Returns: str: date and time value formatted as an ISO 8601 date and time string or None if the timestamp cannot be copied to a date and time string. """ date_time_string = self.CopyToDateTimeString() if date_time_string: date_time_string = date_time_string.replace(' ', 'T') date_time_string = '{0:s}Z'.format(date_time_string) return date_time_string
python
def CopyToDateTimeStringISO8601(self): """Copies the date time value to an ISO 8601 date and time string. Returns: str: date and time value formatted as an ISO 8601 date and time string or None if the timestamp cannot be copied to a date and time string. """ date_time_string = self.CopyToDateTimeString() if date_time_string: date_time_string = date_time_string.replace(' ', 'T') date_time_string = '{0:s}Z'.format(date_time_string) return date_time_string
[ "def", "CopyToDateTimeStringISO8601", "(", "self", ")", ":", "date_time_string", "=", "self", ".", "CopyToDateTimeString", "(", ")", "if", "date_time_string", ":", "date_time_string", "=", "date_time_string", ".", "replace", "(", "' '", ",", "'T'", ")", "date_time_string", "=", "'{0:s}Z'", ".", "format", "(", "date_time_string", ")", "return", "date_time_string" ]
Copies the date time value to an ISO 8601 date and time string. Returns: str: date and time value formatted as an ISO 8601 date and time string or None if the timestamp cannot be copied to a date and time string.
[ "Copies", "the", "date", "time", "value", "to", "an", "ISO", "8601", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L897-L908
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues.GetDate
def GetDate(self): """Retrieves the date represented by the date and time values. Returns: tuple[int, int, int]: year, month, day of month or (None, None, None) if the date and time values do not represent a date. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None, None number_of_days, _, _, _ = self._GetTimeValues(normalized_timestamp) try: return self._GetDateValuesWithEpoch( number_of_days, self._EPOCH_NORMALIZED_TIME) except ValueError: return None, None, None
python
def GetDate(self): """Retrieves the date represented by the date and time values. Returns: tuple[int, int, int]: year, month, day of month or (None, None, None) if the date and time values do not represent a date. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None, None number_of_days, _, _, _ = self._GetTimeValues(normalized_timestamp) try: return self._GetDateValuesWithEpoch( number_of_days, self._EPOCH_NORMALIZED_TIME) except ValueError: return None, None, None
[ "def", "GetDate", "(", "self", ")", ":", "normalized_timestamp", "=", "self", ".", "_GetNormalizedTimestamp", "(", ")", "if", "normalized_timestamp", "is", "None", ":", "return", "None", ",", "None", ",", "None", "number_of_days", ",", "_", ",", "_", ",", "_", "=", "self", ".", "_GetTimeValues", "(", "normalized_timestamp", ")", "try", ":", "return", "self", ".", "_GetDateValuesWithEpoch", "(", "number_of_days", ",", "self", ".", "_EPOCH_NORMALIZED_TIME", ")", "except", "ValueError", ":", "return", "None", ",", "None", ",", "None" ]
Retrieves the date represented by the date and time values. Returns: tuple[int, int, int]: year, month, day of month or (None, None, None) if the date and time values do not represent a date.
[ "Retrieves", "the", "date", "represented", "by", "the", "date", "and", "time", "values", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L910-L928
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues.GetPlasoTimestamp
def GetPlasoTimestamp(self): """Retrieves a timestamp that is compatible with plaso. Returns: int: a POSIX timestamp in microseconds or None if no timestamp is available. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None normalized_timestamp *= definitions.MICROSECONDS_PER_SECOND normalized_timestamp = normalized_timestamp.quantize( 1, rounding=decimal.ROUND_HALF_UP) return int(normalized_timestamp)
python
def GetPlasoTimestamp(self): """Retrieves a timestamp that is compatible with plaso. Returns: int: a POSIX timestamp in microseconds or None if no timestamp is available. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None normalized_timestamp *= definitions.MICROSECONDS_PER_SECOND normalized_timestamp = normalized_timestamp.quantize( 1, rounding=decimal.ROUND_HALF_UP) return int(normalized_timestamp)
[ "def", "GetPlasoTimestamp", "(", "self", ")", ":", "normalized_timestamp", "=", "self", ".", "_GetNormalizedTimestamp", "(", ")", "if", "normalized_timestamp", "is", "None", ":", "return", "None", "normalized_timestamp", "*=", "definitions", ".", "MICROSECONDS_PER_SECOND", "normalized_timestamp", "=", "normalized_timestamp", ".", "quantize", "(", "1", ",", "rounding", "=", "decimal", ".", "ROUND_HALF_UP", ")", "return", "int", "(", "normalized_timestamp", ")" ]
Retrieves a timestamp that is compatible with plaso. Returns: int: a POSIX timestamp in microseconds or None if no timestamp is available.
[ "Retrieves", "a", "timestamp", "that", "is", "compatible", "with", "plaso", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L931-L945
train
log2timeline/dfdatetime
dfdatetime/interface.py
DateTimeValues.GetTimeOfDay
def GetTimeOfDay(self): """Retrieves the time of day represented by the date and time values. Returns: tuple[int, int, int]: hours, minutes, seconds or (None, None, None) if the date and time values do not represent a time of day. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None, None _, hours, minutes, seconds = self._GetTimeValues(normalized_timestamp) return hours, minutes, seconds
python
def GetTimeOfDay(self): """Retrieves the time of day represented by the date and time values. Returns: tuple[int, int, int]: hours, minutes, seconds or (None, None, None) if the date and time values do not represent a time of day. """ normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None, None _, hours, minutes, seconds = self._GetTimeValues(normalized_timestamp) return hours, minutes, seconds
[ "def", "GetTimeOfDay", "(", "self", ")", ":", "normalized_timestamp", "=", "self", ".", "_GetNormalizedTimestamp", "(", ")", "if", "normalized_timestamp", "is", "None", ":", "return", "None", ",", "None", ",", "None", "_", ",", "hours", ",", "minutes", ",", "seconds", "=", "self", ".", "_GetTimeValues", "(", "normalized_timestamp", ")", "return", "hours", ",", "minutes", ",", "seconds" ]
Retrieves the time of day represented by the date and time values. Returns: tuple[int, int, int]: hours, minutes, seconds or (None, None, None) if the date and time values do not represent a time of day.
[ "Retrieves", "the", "time", "of", "day", "represented", "by", "the", "date", "and", "time", "values", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L947-L959
train
log2timeline/dfdatetime
dfdatetime/hfs_time.py
HFSTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= 0 and self._timestamp <= self._UINT32_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) - self._HFS_TO_POSIX_BASE) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= 0 and self._timestamp <= self._UINT32_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) - self._HFS_TO_POSIX_BASE) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "(", "self", ".", "_timestamp", "is", "not", "None", "and", "self", ".", "_timestamp", ">=", "0", "and", "self", ".", "_timestamp", "<=", "self", ".", "_UINT32_MAX", ")", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "-", "self", ".", "_HFS_TO_POSIX_BASE", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/hfs_time.py#L50-L65
train
log2timeline/dfdatetime
dfdatetime/fake_time.py
FakeTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._number_of_seconds is not None: self._normalized_timestamp = ( decimal.Decimal(self._microseconds) / definitions.MICROSECONDS_PER_SECOND) self._normalized_timestamp += decimal.Decimal(self._number_of_seconds) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._number_of_seconds is not None: self._normalized_timestamp = ( decimal.Decimal(self._microseconds) / definitions.MICROSECONDS_PER_SECOND) self._normalized_timestamp += decimal.Decimal(self._number_of_seconds) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_number_of_seconds", "is", "not", "None", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_microseconds", ")", "/", "definitions", ".", "MICROSECONDS_PER_SECOND", ")", "self", ".", "_normalized_timestamp", "+=", "decimal", ".", "Decimal", "(", "self", ".", "_number_of_seconds", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/fake_time.py#L37-L53
train
log2timeline/dfdatetime
dfdatetime/fake_time.py
FakeTime.CopyFromDateTimeString
def CopyFromDateTimeString(self, time_string): """Copies a fake timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self._microseconds = date_time_values.get('microseconds', None) self.is_local_time = False
python
def CopyFromDateTimeString(self, time_string): """Copies a fake timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self._microseconds = date_time_values.get('microseconds', None) self.is_local_time = False
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date_time_values", ".", "get", "(", "'month'", ",", "0", ")", "day_of_month", "=", "date_time_values", ".", "get", "(", "'day_of_month'", ",", "0", ")", "hours", "=", "date_time_values", ".", "get", "(", "'hours'", ",", "0", ")", "minutes", "=", "date_time_values", ".", "get", "(", "'minutes'", ",", "0", ")", "seconds", "=", "date_time_values", ".", "get", "(", "'seconds'", ",", "0", ")", "self", ".", "_normalized_timestamp", "=", "None", "self", ".", "_number_of_seconds", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "self", ".", "_microseconds", "=", "date_time_values", ".", "get", "(", "'microseconds'", ",", "None", ")", "self", ".", "is_local_time", "=", "False" ]
Copies a fake timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC.
[ "Copies", "a", "fake", "timestamp", "from", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/fake_time.py#L55-L81
train
log2timeline/dfdatetime
dfdatetime/rfc2579_date_time.py
RFC2579DateTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._number_of_seconds is not None: self._normalized_timestamp = ( decimal.Decimal(self.deciseconds) / definitions.DECISECONDS_PER_SECOND) self._normalized_timestamp += decimal.Decimal(self._number_of_seconds) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._number_of_seconds is not None: self._normalized_timestamp = ( decimal.Decimal(self.deciseconds) / definitions.DECISECONDS_PER_SECOND) self._normalized_timestamp += decimal.Decimal(self._number_of_seconds) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_number_of_seconds", "is", "not", "None", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "deciseconds", ")", "/", "definitions", ".", "DECISECONDS_PER_SECOND", ")", "self", ".", "_normalized_timestamp", "+=", "decimal", ".", "Decimal", "(", "self", ".", "_number_of_seconds", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/rfc2579_date_time.py#L131-L147
train
log2timeline/dfdatetime
dfdatetime/rfc2579_date_time.py
RFC2579DateTime.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the RFC2579 date-time to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#" or None if the number of seconds is missing. """ if self._number_of_seconds is None: return None return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:01d}'.format( self.year, self.month, self.day_of_month, self.hours, self.minutes, self.seconds, self.deciseconds)
python
def CopyToDateTimeString(self): """Copies the RFC2579 date-time to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#" or None if the number of seconds is missing. """ if self._number_of_seconds is None: return None return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:01d}'.format( self.year, self.month, self.day_of_month, self.hours, self.minutes, self.seconds, self.deciseconds)
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "self", ".", "_number_of_seconds", "is", "None", ":", "return", "None", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:01d}'", ".", "format", "(", "self", ".", "year", ",", "self", ".", "month", ",", "self", ".", "day_of_month", ",", "self", ".", "hours", ",", "self", ".", "minutes", ",", "self", ".", "seconds", ",", "self", ".", "deciseconds", ")" ]
Copies the RFC2579 date-time to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#" or None if the number of seconds is missing.
[ "Copies", "the", "RFC2579", "date", "-", "time", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/rfc2579_date_time.py#L194-L206
train
RyanBalfanz/django-smsish
smsish/sms/backends/twilio.py
SMSBackend.open
def open(self): """ Ensures we have a connection to the SMS gateway. Returns whether or not a new connection was required (True or False). """ if self.connection: # Nothing to do if the connection is already open. return False self.connection = self._get_twilio_client() return True
python
def open(self): """ Ensures we have a connection to the SMS gateway. Returns whether or not a new connection was required (True or False). """ if self.connection: # Nothing to do if the connection is already open. return False self.connection = self._get_twilio_client() return True
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "connection", ":", "# Nothing to do if the connection is already open.", "return", "False", "self", ".", "connection", "=", "self", ".", "_get_twilio_client", "(", ")", "return", "True" ]
Ensures we have a connection to the SMS gateway. Returns whether or not a new connection was required (True or False).
[ "Ensures", "we", "have", "a", "connection", "to", "the", "SMS", "gateway", ".", "Returns", "whether", "or", "not", "a", "new", "connection", "was", "required", "(", "True", "or", "False", ")", "." ]
4d450e3d217cea9e373f16c5e4f0beb3218bd5c9
https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/backends/twilio.py#L12-L21
train
RyanBalfanz/django-smsish
smsish/sms/backends/twilio.py
SMSBackend._send
def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False from_email = email_message.from_email recipients = email_message.recipients() try: self.connection.messages.create( to=recipients, from_=from_email, body=email_message.body ) except Exception: if not self.fail_silently: raise return False return True
python
def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False from_email = email_message.from_email recipients = email_message.recipients() try: self.connection.messages.create( to=recipients, from_=from_email, body=email_message.body ) except Exception: if not self.fail_silently: raise return False return True
[ "def", "_send", "(", "self", ",", "email_message", ")", ":", "if", "not", "email_message", ".", "recipients", "(", ")", ":", "return", "False", "from_email", "=", "email_message", ".", "from_email", "recipients", "=", "email_message", ".", "recipients", "(", ")", "try", ":", "self", ".", "connection", ".", "messages", ".", "create", "(", "to", "=", "recipients", ",", "from_", "=", "from_email", ",", "body", "=", "email_message", ".", "body", ")", "except", "Exception", ":", "if", "not", "self", ".", "fail_silently", ":", "raise", "return", "False", "return", "True" ]
A helper method that does the actual sending.
[ "A", "helper", "method", "that", "does", "the", "actual", "sending", "." ]
4d450e3d217cea9e373f16c5e4f0beb3218bd5c9
https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/backends/twilio.py#L47-L63
train
log2timeline/dfdatetime
dfdatetime/fat_date_time.py
FATDateTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._number_of_seconds is not None and self._number_of_seconds >= 0: self._normalized_timestamp = ( decimal.Decimal(self._number_of_seconds) + self._FAT_DATE_TO_POSIX_BASE) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._number_of_seconds is not None and self._number_of_seconds >= 0: self._normalized_timestamp = ( decimal.Decimal(self._number_of_seconds) + self._FAT_DATE_TO_POSIX_BASE) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_number_of_seconds", "is", "not", "None", "and", "self", ".", "_number_of_seconds", ">=", "0", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_number_of_seconds", ")", "+", "self", ".", "_FAT_DATE_TO_POSIX_BASE", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/fat_date_time.py#L61-L76
train
log2timeline/dfdatetime
dfdatetime/fat_date_time.py
FATDateTime._GetNumberOfSeconds
def _GetNumberOfSeconds(self, fat_date_time): """Retrieves the number of seconds from a FAT date time. Args: fat_date_time (int): FAT date time. Returns: int: number of seconds since January 1, 1980 00:00:00. Raises: ValueError: if the month, day of month, hours, minutes or seconds value is out of bounds. """ day_of_month = (fat_date_time & 0x1f) month = ((fat_date_time >> 5) & 0x0f) year = (fat_date_time >> 9) & 0x7f days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') number_of_days = self._GetDayOfYear(1980 + year, month, day_of_month) number_of_days -= 1 for past_year in range(0, year): number_of_days += self._GetNumberOfDaysInYear(past_year) fat_date_time >>= 16 seconds = (fat_date_time & 0x1f) * 2 minutes = (fat_date_time >> 5) & 0x3f hours = (fat_date_time >> 11) & 0x1f if hours not in range(0, 24): raise ValueError('Hours value out of bounds.') if minutes not in range(0, 60): raise ValueError('Minutes value out of bounds.') if seconds not in range(0, 60): raise ValueError('Seconds value out of bounds.') number_of_seconds = (((hours * 60) + minutes) * 60) + seconds number_of_seconds += number_of_days * definitions.SECONDS_PER_DAY return number_of_seconds
python
def _GetNumberOfSeconds(self, fat_date_time): """Retrieves the number of seconds from a FAT date time. Args: fat_date_time (int): FAT date time. Returns: int: number of seconds since January 1, 1980 00:00:00. Raises: ValueError: if the month, day of month, hours, minutes or seconds value is out of bounds. """ day_of_month = (fat_date_time & 0x1f) month = ((fat_date_time >> 5) & 0x0f) year = (fat_date_time >> 9) & 0x7f days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') number_of_days = self._GetDayOfYear(1980 + year, month, day_of_month) number_of_days -= 1 for past_year in range(0, year): number_of_days += self._GetNumberOfDaysInYear(past_year) fat_date_time >>= 16 seconds = (fat_date_time & 0x1f) * 2 minutes = (fat_date_time >> 5) & 0x3f hours = (fat_date_time >> 11) & 0x1f if hours not in range(0, 24): raise ValueError('Hours value out of bounds.') if minutes not in range(0, 60): raise ValueError('Minutes value out of bounds.') if seconds not in range(0, 60): raise ValueError('Seconds value out of bounds.') number_of_seconds = (((hours * 60) + minutes) * 60) + seconds number_of_seconds += number_of_days * definitions.SECONDS_PER_DAY return number_of_seconds
[ "def", "_GetNumberOfSeconds", "(", "self", ",", "fat_date_time", ")", ":", "day_of_month", "=", "(", "fat_date_time", "&", "0x1f", ")", "month", "=", "(", "(", "fat_date_time", ">>", "5", ")", "&", "0x0f", ")", "year", "=", "(", "fat_date_time", ">>", "9", ")", "&", "0x7f", "days_per_month", "=", "self", ".", "_GetDaysPerMonth", "(", "year", ",", "month", ")", "if", "day_of_month", "<", "1", "or", "day_of_month", ">", "days_per_month", ":", "raise", "ValueError", "(", "'Day of month value out of bounds.'", ")", "number_of_days", "=", "self", ".", "_GetDayOfYear", "(", "1980", "+", "year", ",", "month", ",", "day_of_month", ")", "number_of_days", "-=", "1", "for", "past_year", "in", "range", "(", "0", ",", "year", ")", ":", "number_of_days", "+=", "self", ".", "_GetNumberOfDaysInYear", "(", "past_year", ")", "fat_date_time", ">>=", "16", "seconds", "=", "(", "fat_date_time", "&", "0x1f", ")", "*", "2", "minutes", "=", "(", "fat_date_time", ">>", "5", ")", "&", "0x3f", "hours", "=", "(", "fat_date_time", ">>", "11", ")", "&", "0x1f", "if", "hours", "not", "in", "range", "(", "0", ",", "24", ")", ":", "raise", "ValueError", "(", "'Hours value out of bounds.'", ")", "if", "minutes", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Minutes value out of bounds.'", ")", "if", "seconds", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Seconds value out of bounds.'", ")", "number_of_seconds", "=", "(", "(", "(", "hours", "*", "60", ")", "+", "minutes", ")", "*", "60", ")", "+", "seconds", "number_of_seconds", "+=", "number_of_days", "*", "definitions", ".", "SECONDS_PER_DAY", "return", "number_of_seconds" ]
Retrieves the number of seconds from a FAT date time. Args: fat_date_time (int): FAT date time. Returns: int: number of seconds since January 1, 1980 00:00:00. Raises: ValueError: if the month, day of month, hours, minutes or seconds value is out of bounds.
[ "Retrieves", "the", "number", "of", "seconds", "from", "a", "FAT", "date", "time", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/fat_date_time.py#L78-L121
train
RyanBalfanz/django-smsish
smsish/sms/__init__.py
get_sms_connection
def get_sms_connection(backend=None, fail_silently=False, **kwds): """Load an sms backend and return an instance of it. If backend is None (default) settings.SMS_BACKEND is used. Both fail_silently and other keyword arguments are used in the constructor of the backend. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L28 """ klass = import_string(backend or settings.SMS_BACKEND) return klass(fail_silently=fail_silently, **kwds)
python
def get_sms_connection(backend=None, fail_silently=False, **kwds): """Load an sms backend and return an instance of it. If backend is None (default) settings.SMS_BACKEND is used. Both fail_silently and other keyword arguments are used in the constructor of the backend. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L28 """ klass = import_string(backend or settings.SMS_BACKEND) return klass(fail_silently=fail_silently, **kwds)
[ "def", "get_sms_connection", "(", "backend", "=", "None", ",", "fail_silently", "=", "False", ",", "*", "*", "kwds", ")", ":", "klass", "=", "import_string", "(", "backend", "or", "settings", ".", "SMS_BACKEND", ")", "return", "klass", "(", "fail_silently", "=", "fail_silently", ",", "*", "*", "kwds", ")" ]
Load an sms backend and return an instance of it. If backend is None (default) settings.SMS_BACKEND is used. Both fail_silently and other keyword arguments are used in the constructor of the backend. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L28
[ "Load", "an", "sms", "backend", "and", "return", "an", "instance", "of", "it", "." ]
4d450e3d217cea9e373f16c5e4f0beb3218bd5c9
https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/__init__.py#L20-L31
train
RyanBalfanz/django-smsish
smsish/sms/__init__.py
send_sms
def send_sms(message, from_number, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L40 """ connection = connection or get_sms_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) mail = SMSMessage(message, from_number, recipient_list, connection=connection) return mail.send()
python
def send_sms(message, from_number, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L40 """ connection = connection or get_sms_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) mail = SMSMessage(message, from_number, recipient_list, connection=connection) return mail.send()
[ "def", "send_sms", "(", "message", ",", "from_number", ",", "recipient_list", ",", "fail_silently", "=", "False", ",", "auth_user", "=", "None", ",", "auth_password", "=", "None", ",", "connection", "=", "None", ")", ":", "connection", "=", "connection", "or", "get_sms_connection", "(", "username", "=", "auth_user", ",", "password", "=", "auth_password", ",", "fail_silently", "=", "fail_silently", ")", "mail", "=", "SMSMessage", "(", "message", ",", "from_number", ",", "recipient_list", ",", "connection", "=", "connection", ")", "return", "mail", ".", "send", "(", ")" ]
Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L40
[ "Easy", "wrapper", "for", "sending", "a", "single", "message", "to", "a", "recipient", "list", ".", "All", "members", "of", "the", "recipient", "list", "will", "see", "the", "other", "recipients", "in", "the", "To", "field", "." ]
4d450e3d217cea9e373f16c5e4f0beb3218bd5c9
https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/__init__.py#L34-L50
train
RyanBalfanz/django-smsish
smsish/sms/__init__.py
send_mass_sms
def send_mass_sms(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Given a datatuple of (subject, message, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L64 """ import smsish.sms.backends.rq if isinstance(connection, smsish.sms.backends.rq.SMSBackend): raise NotImplementedError connection = connection or get_sms_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) messages = [SMSMessage(message, from_number, recipient, connection=connection) for message, from_number, recipient in datatuple] return connection.send_messages(messages)
python
def send_mass_sms(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Given a datatuple of (subject, message, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L64 """ import smsish.sms.backends.rq if isinstance(connection, smsish.sms.backends.rq.SMSBackend): raise NotImplementedError connection = connection or get_sms_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) messages = [SMSMessage(message, from_number, recipient, connection=connection) for message, from_number, recipient in datatuple] return connection.send_messages(messages)
[ "def", "send_mass_sms", "(", "datatuple", ",", "fail_silently", "=", "False", ",", "auth_user", "=", "None", ",", "auth_password", "=", "None", ",", "connection", "=", "None", ")", ":", "import", "smsish", ".", "sms", ".", "backends", ".", "rq", "if", "isinstance", "(", "connection", ",", "smsish", ".", "sms", ".", "backends", ".", "rq", ".", "SMSBackend", ")", ":", "raise", "NotImplementedError", "connection", "=", "connection", "or", "get_sms_connection", "(", "username", "=", "auth_user", ",", "password", "=", "auth_password", ",", "fail_silently", "=", "fail_silently", ")", "messages", "=", "[", "SMSMessage", "(", "message", ",", "from_number", ",", "recipient", ",", "connection", "=", "connection", ")", "for", "message", ",", "from_number", ",", "recipient", "in", "datatuple", "]", "return", "connection", ".", "send_messages", "(", "messages", ")" ]
Given a datatuple of (subject, message, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L64
[ "Given", "a", "datatuple", "of", "(", "subject", "message", "from_email", "recipient_list", ")", "sends", "each", "message", "to", "each", "recipient", "list", ".", "Returns", "the", "number", "of", "emails", "sent", "." ]
4d450e3d217cea9e373f16c5e4f0beb3218bd5c9
https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/__init__.py#L53-L73
train
log2timeline/dfdatetime
dfdatetime/filetime.py
Filetime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= 0 and self._timestamp <= self._UINT64_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / self._100NS_PER_SECOND) self._normalized_timestamp -= self._FILETIME_TO_POSIX_BASE return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= 0 and self._timestamp <= self._UINT64_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / self._100NS_PER_SECOND) self._normalized_timestamp -= self._FILETIME_TO_POSIX_BASE return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "(", "self", ".", "_timestamp", "is", "not", "None", "and", "self", ".", "_timestamp", ">=", "0", "and", "self", ".", "_timestamp", "<=", "self", ".", "_UINT64_MAX", ")", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "/", "self", ".", "_100NS_PER_SECOND", ")", "self", ".", "_normalized_timestamp", "-=", "self", ".", "_FILETIME_TO_POSIX_BASE", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/filetime.py#L53-L69
train
log2timeline/dfdatetime
dfdatetime/filetime.py
Filetime.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the FILETIME timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#######" or None if the timestamp is missing or invalid. """ if (self._timestamp is None or self._timestamp < 0 or self._timestamp > self._UINT64_MAX): return None timestamp, remainder = divmod(self._timestamp, self._100NS_PER_SECOND) number_of_days, hours, minutes, seconds = self._GetTimeValues(timestamp) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:07d}'.format( year, month, day_of_month, hours, minutes, seconds, remainder)
python
def CopyToDateTimeString(self): """Copies the FILETIME timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#######" or None if the timestamp is missing or invalid. """ if (self._timestamp is None or self._timestamp < 0 or self._timestamp > self._UINT64_MAX): return None timestamp, remainder = divmod(self._timestamp, self._100NS_PER_SECOND) number_of_days, hours, minutes, seconds = self._GetTimeValues(timestamp) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:07d}'.format( year, month, day_of_month, hours, minutes, seconds, remainder)
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "(", "self", ".", "_timestamp", "is", "None", "or", "self", ".", "_timestamp", "<", "0", "or", "self", ".", "_timestamp", ">", "self", ".", "_UINT64_MAX", ")", ":", "return", "None", "timestamp", ",", "remainder", "=", "divmod", "(", "self", ".", "_timestamp", ",", "self", ".", "_100NS_PER_SECOND", ")", "number_of_days", ",", "hours", ",", "minutes", ",", "seconds", "=", "self", ".", "_GetTimeValues", "(", "timestamp", ")", "year", ",", "month", ",", "day_of_month", "=", "self", ".", "_GetDateValuesWithEpoch", "(", "number_of_days", ",", "self", ".", "_EPOCH", ")", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:07d}'", ".", "format", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ",", "remainder", ")" ]
Copies the FILETIME timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#######" or None if the timestamp is missing or invalid.
[ "Copies", "the", "FILETIME", "timestamp", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/filetime.py#L109-L127
train
log2timeline/dfdatetime
dfdatetime/uuid_time.py
UUIDTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= 0 and self._timestamp <= self._UINT60_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / self._100NS_PER_SECOND) self._normalized_timestamp -= self._UUID_TO_POSIX_BASE return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= 0 and self._timestamp <= self._UINT60_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / self._100NS_PER_SECOND) self._normalized_timestamp -= self._UUID_TO_POSIX_BASE return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "(", "self", ".", "_timestamp", "is", "not", "None", "and", "self", ".", "_timestamp", ">=", "0", "and", "self", ".", "_timestamp", "<=", "self", ".", "_UINT60_MAX", ")", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "/", "self", ".", "_100NS_PER_SECOND", ")", "self", ".", "_normalized_timestamp", "-=", "self", ".", "_UUID_TO_POSIX_BASE", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/uuid_time.py#L58-L74
train
log2timeline/dfdatetime
dfdatetime/precisions.py
SecondsPrecisionHelper.CopyToDateTimeString
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second): """Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss Raises: ValueError: if the fraction of second is out of bounds. """ if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError('Fraction of second value: {0:f} out of bounds.'.format( fraction_of_second)) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format( time_elements_tuple[0], time_elements_tuple[1], time_elements_tuple[2], time_elements_tuple[3], time_elements_tuple[4], time_elements_tuple[5])
python
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second): """Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss Raises: ValueError: if the fraction of second is out of bounds. """ if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError('Fraction of second value: {0:f} out of bounds.'.format( fraction_of_second)) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format( time_elements_tuple[0], time_elements_tuple[1], time_elements_tuple[2], time_elements_tuple[3], time_elements_tuple[4], time_elements_tuple[5])
[ "def", "CopyToDateTimeString", "(", "cls", ",", "time_elements_tuple", ",", "fraction_of_second", ")", ":", "if", "fraction_of_second", "<", "0.0", "or", "fraction_of_second", ">=", "1.0", ":", "raise", "ValueError", "(", "'Fraction of second value: {0:f} out of bounds.'", ".", "format", "(", "fraction_of_second", ")", ")", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'", ".", "format", "(", "time_elements_tuple", "[", "0", "]", ",", "time_elements_tuple", "[", "1", "]", ",", "time_elements_tuple", "[", "2", "]", ",", "time_elements_tuple", "[", "3", "]", ",", "time_elements_tuple", "[", "4", "]", ",", "time_elements_tuple", "[", "5", "]", ")" ]
Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss Raises: ValueError: if the fraction of second is out of bounds.
[ "Copies", "the", "time", "elements", "and", "fraction", "of", "second", "to", "a", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/precisions.py#L78-L101
train
log2timeline/dfdatetime
dfdatetime/precisions.py
MillisecondsPrecisionHelper.CopyMicrosecondsToFractionOfSecond
def CopyMicrosecondsToFractionOfSecond(cls, microseconds): """Copies the number of microseconds to a fraction of second value. Args: microseconds (int): number of microseconds. Returns: decimal.Decimal: fraction of second, which must be a value between 0.0 and 1.0. Raises: ValueError: if the number of microseconds is out of bounds. """ if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND: raise ValueError( 'Number of microseconds value: {0:d} out of bounds.'.format( microseconds)) milliseconds, _ = divmod( microseconds, definitions.MICROSECONDS_PER_MILLISECOND) return decimal.Decimal(milliseconds) / definitions.MILLISECONDS_PER_SECOND
python
def CopyMicrosecondsToFractionOfSecond(cls, microseconds): """Copies the number of microseconds to a fraction of second value. Args: microseconds (int): number of microseconds. Returns: decimal.Decimal: fraction of second, which must be a value between 0.0 and 1.0. Raises: ValueError: if the number of microseconds is out of bounds. """ if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND: raise ValueError( 'Number of microseconds value: {0:d} out of bounds.'.format( microseconds)) milliseconds, _ = divmod( microseconds, definitions.MICROSECONDS_PER_MILLISECOND) return decimal.Decimal(milliseconds) / definitions.MILLISECONDS_PER_SECOND
[ "def", "CopyMicrosecondsToFractionOfSecond", "(", "cls", ",", "microseconds", ")", ":", "if", "microseconds", "<", "0", "or", "microseconds", ">=", "definitions", ".", "MICROSECONDS_PER_SECOND", ":", "raise", "ValueError", "(", "'Number of microseconds value: {0:d} out of bounds.'", ".", "format", "(", "microseconds", ")", ")", "milliseconds", ",", "_", "=", "divmod", "(", "microseconds", ",", "definitions", ".", "MICROSECONDS_PER_MILLISECOND", ")", "return", "decimal", ".", "Decimal", "(", "milliseconds", ")", "/", "definitions", ".", "MILLISECONDS_PER_SECOND" ]
Copies the number of microseconds to a fraction of second value. Args: microseconds (int): number of microseconds. Returns: decimal.Decimal: fraction of second, which must be a value between 0.0 and 1.0. Raises: ValueError: if the number of microseconds is out of bounds.
[ "Copies", "the", "number", "of", "microseconds", "to", "a", "fraction", "of", "second", "value", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/precisions.py#L108-L128
train
log2timeline/dfdatetime
dfdatetime/precisions.py
MillisecondsPrecisionHelper.CopyToDateTimeString
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second): """Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.### Raises: ValueError: if the fraction of second is out of bounds. """ if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError('Fraction of second value: {0:f} out of bounds.'.format( fraction_of_second)) milliseconds = int(fraction_of_second * definitions.MILLISECONDS_PER_SECOND) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:03d}'.format( time_elements_tuple[0], time_elements_tuple[1], time_elements_tuple[2], time_elements_tuple[3], time_elements_tuple[4], time_elements_tuple[5], milliseconds)
python
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second): """Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.### Raises: ValueError: if the fraction of second is out of bounds. """ if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError('Fraction of second value: {0:f} out of bounds.'.format( fraction_of_second)) milliseconds = int(fraction_of_second * definitions.MILLISECONDS_PER_SECOND) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:03d}'.format( time_elements_tuple[0], time_elements_tuple[1], time_elements_tuple[2], time_elements_tuple[3], time_elements_tuple[4], time_elements_tuple[5], milliseconds)
[ "def", "CopyToDateTimeString", "(", "cls", ",", "time_elements_tuple", ",", "fraction_of_second", ")", ":", "if", "fraction_of_second", "<", "0.0", "or", "fraction_of_second", ">=", "1.0", ":", "raise", "ValueError", "(", "'Fraction of second value: {0:f} out of bounds.'", ".", "format", "(", "fraction_of_second", ")", ")", "milliseconds", "=", "int", "(", "fraction_of_second", "*", "definitions", ".", "MILLISECONDS_PER_SECOND", ")", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:03d}'", ".", "format", "(", "time_elements_tuple", "[", "0", "]", ",", "time_elements_tuple", "[", "1", "]", ",", "time_elements_tuple", "[", "2", "]", ",", "time_elements_tuple", "[", "3", "]", ",", "time_elements_tuple", "[", "4", "]", ",", "time_elements_tuple", "[", "5", "]", ",", "milliseconds", ")" ]
Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.### Raises: ValueError: if the fraction of second is out of bounds.
[ "Copies", "the", "time", "elements", "and", "fraction", "of", "second", "to", "a", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/precisions.py#L131-L157
train
log2timeline/dfdatetime
dfdatetime/precisions.py
MicrosecondsPrecisionHelper.CopyMicrosecondsToFractionOfSecond
def CopyMicrosecondsToFractionOfSecond(cls, microseconds): """Copies the number of microseconds to a fraction of second value. Args: microseconds (int): number of microseconds. Returns: decimal.Decimal: fraction of second, which must be a value between 0.0 and 1.0. Raises: ValueError: if the number of microseconds is out of bounds. """ if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND: raise ValueError( 'Number of microseconds value: {0:d} out of bounds.'.format( microseconds)) return decimal.Decimal(microseconds) / definitions.MICROSECONDS_PER_SECOND
python
def CopyMicrosecondsToFractionOfSecond(cls, microseconds): """Copies the number of microseconds to a fraction of second value. Args: microseconds (int): number of microseconds. Returns: decimal.Decimal: fraction of second, which must be a value between 0.0 and 1.0. Raises: ValueError: if the number of microseconds is out of bounds. """ if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND: raise ValueError( 'Number of microseconds value: {0:d} out of bounds.'.format( microseconds)) return decimal.Decimal(microseconds) / definitions.MICROSECONDS_PER_SECOND
[ "def", "CopyMicrosecondsToFractionOfSecond", "(", "cls", ",", "microseconds", ")", ":", "if", "microseconds", "<", "0", "or", "microseconds", ">=", "definitions", ".", "MICROSECONDS_PER_SECOND", ":", "raise", "ValueError", "(", "'Number of microseconds value: {0:d} out of bounds.'", ".", "format", "(", "microseconds", ")", ")", "return", "decimal", ".", "Decimal", "(", "microseconds", ")", "/", "definitions", ".", "MICROSECONDS_PER_SECOND" ]
Copies the number of microseconds to a fraction of second value. Args: microseconds (int): number of microseconds. Returns: decimal.Decimal: fraction of second, which must be a value between 0.0 and 1.0. Raises: ValueError: if the number of microseconds is out of bounds.
[ "Copies", "the", "number", "of", "microseconds", "to", "a", "fraction", "of", "second", "value", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/precisions.py#L164-L182
train
log2timeline/dfdatetime
dfdatetime/precisions.py
MicrosecondsPrecisionHelper.CopyToDateTimeString
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second): """Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.###### Raises: ValueError: if the fraction of second is out of bounds. """ if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError('Fraction of second value: {0:f} out of bounds.'.format( fraction_of_second)) microseconds = int(fraction_of_second * definitions.MICROSECONDS_PER_SECOND) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'.format( time_elements_tuple[0], time_elements_tuple[1], time_elements_tuple[2], time_elements_tuple[3], time_elements_tuple[4], time_elements_tuple[5], microseconds)
python
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second): """Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.###### Raises: ValueError: if the fraction of second is out of bounds. """ if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError('Fraction of second value: {0:f} out of bounds.'.format( fraction_of_second)) microseconds = int(fraction_of_second * definitions.MICROSECONDS_PER_SECOND) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'.format( time_elements_tuple[0], time_elements_tuple[1], time_elements_tuple[2], time_elements_tuple[3], time_elements_tuple[4], time_elements_tuple[5], microseconds)
[ "def", "CopyToDateTimeString", "(", "cls", ",", "time_elements_tuple", ",", "fraction_of_second", ")", ":", "if", "fraction_of_second", "<", "0.0", "or", "fraction_of_second", ">=", "1.0", ":", "raise", "ValueError", "(", "'Fraction of second value: {0:f} out of bounds.'", ".", "format", "(", "fraction_of_second", ")", ")", "microseconds", "=", "int", "(", "fraction_of_second", "*", "definitions", ".", "MICROSECONDS_PER_SECOND", ")", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'", ".", "format", "(", "time_elements_tuple", "[", "0", "]", ",", "time_elements_tuple", "[", "1", "]", ",", "time_elements_tuple", "[", "2", "]", ",", "time_elements_tuple", "[", "3", "]", ",", "time_elements_tuple", "[", "4", "]", ",", "time_elements_tuple", "[", "5", "]", ",", "microseconds", ")" ]
Copies the time elements and fraction of second to a string. Args: time_elements_tuple (tuple[int, int, int, int, int, int]): time elements, contains year, month, day of month, hours, minutes and seconds. fraction_of_second (decimal.Decimal): fraction of second, which must be a value between 0.0 and 1.0. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.###### Raises: ValueError: if the fraction of second is out of bounds.
[ "Copies", "the", "time", "elements", "and", "fraction", "of", "second", "to", "a", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/precisions.py#L185-L211
train
log2timeline/dfdatetime
dfdatetime/precisions.py
PrecisionHelperFactory.CreatePrecisionHelper
def CreatePrecisionHelper(cls, precision): """Creates a precision helper. Args: precision (str): precision of the date and time value, which should be one of the PRECISION_VALUES in definitions. Returns: class: date time precision helper class. Raises: ValueError: if the precision value is unsupported. """ precision_helper_class = cls._PRECISION_CLASSES.get(precision, None) if not precision_helper_class: raise ValueError('Unsupported precision: {0!s}'.format(precision)) return precision_helper_class
python
def CreatePrecisionHelper(cls, precision): """Creates a precision helper. Args: precision (str): precision of the date and time value, which should be one of the PRECISION_VALUES in definitions. Returns: class: date time precision helper class. Raises: ValueError: if the precision value is unsupported. """ precision_helper_class = cls._PRECISION_CLASSES.get(precision, None) if not precision_helper_class: raise ValueError('Unsupported precision: {0!s}'.format(precision)) return precision_helper_class
[ "def", "CreatePrecisionHelper", "(", "cls", ",", "precision", ")", ":", "precision_helper_class", "=", "cls", ".", "_PRECISION_CLASSES", ".", "get", "(", "precision", ",", "None", ")", "if", "not", "precision_helper_class", ":", "raise", "ValueError", "(", "'Unsupported precision: {0!s}'", ".", "format", "(", "precision", ")", ")", "return", "precision_helper_class" ]
Creates a precision helper. Args: precision (str): precision of the date and time value, which should be one of the PRECISION_VALUES in definitions. Returns: class: date time precision helper class. Raises: ValueError: if the precision value is unsupported.
[ "Creates", "a", "precision", "helper", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/precisions.py#L224-L241
train
log2timeline/dfdatetime
dfdatetime/apfs_time.py
APFSTime.CopyFromDateTimeString
def CopyFromDateTimeString(self, time_string): """Copies a APFS timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the date and time value is not supported. """ super(APFSTime, self)._CopyFromDateTimeString(time_string) if (self._timestamp is None or self._timestamp < self._INT64_MIN or self._timestamp > self._INT64_MAX): raise ValueError('Date time value not supported.')
python
def CopyFromDateTimeString(self, time_string): """Copies a APFS timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the date and time value is not supported. """ super(APFSTime, self)._CopyFromDateTimeString(time_string) if (self._timestamp is None or self._timestamp < self._INT64_MIN or self._timestamp > self._INT64_MAX): raise ValueError('Date time value not supported.')
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "super", "(", "APFSTime", ",", "self", ")", ".", "_CopyFromDateTimeString", "(", "time_string", ")", "if", "(", "self", ".", "_timestamp", "is", "None", "or", "self", ".", "_timestamp", "<", "self", ".", "_INT64_MIN", "or", "self", ".", "_timestamp", ">", "self", ".", "_INT64_MAX", ")", ":", "raise", "ValueError", "(", "'Date time value not supported.'", ")" ]
Copies a APFS timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the date and time value is not supported.
[ "Copies", "a", "APFS", "timestamp", "from", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/apfs_time.py#L40-L59
train
log2timeline/dfdatetime
dfdatetime/apfs_time.py
APFSTime.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the APFS timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or None if the timestamp is missing or invalid. """ if (self._timestamp is None or self._timestamp < self._INT64_MIN or self._timestamp > self._INT64_MAX): return None return super(APFSTime, self)._CopyToDateTimeString()
python
def CopyToDateTimeString(self): """Copies the APFS timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or None if the timestamp is missing or invalid. """ if (self._timestamp is None or self._timestamp < self._INT64_MIN or self._timestamp > self._INT64_MAX): return None return super(APFSTime, self)._CopyToDateTimeString()
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "(", "self", ".", "_timestamp", "is", "None", "or", "self", ".", "_timestamp", "<", "self", ".", "_INT64_MIN", "or", "self", ".", "_timestamp", ">", "self", ".", "_INT64_MAX", ")", ":", "return", "None", "return", "super", "(", "APFSTime", ",", "self", ")", ".", "_CopyToDateTimeString", "(", ")" ]
Copies the APFS timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or None if the timestamp is missing or invalid.
[ "Copies", "the", "APFS", "timestamp", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/apfs_time.py#L61-L72
train
log2timeline/dfdatetime
dfdatetime/cocoa_time.py
CocoaTime.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the Cocoa timestamp to a date and time string. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.###### or None if the timestamp cannot be copied to a date and time string. """ if self._timestamp is None: return None number_of_days, hours, minutes, seconds = self._GetTimeValues( int(self._timestamp)) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) microseconds = int( (self._timestamp % 1) * definitions.MICROSECONDS_PER_SECOND) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'.format( year, month, day_of_month, hours, minutes, seconds, microseconds)
python
def CopyToDateTimeString(self): """Copies the Cocoa timestamp to a date and time string. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.###### or None if the timestamp cannot be copied to a date and time string. """ if self._timestamp is None: return None number_of_days, hours, minutes, seconds = self._GetTimeValues( int(self._timestamp)) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) microseconds = int( (self._timestamp % 1) * definitions.MICROSECONDS_PER_SECOND) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'.format( year, month, day_of_month, hours, minutes, seconds, microseconds)
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "self", ".", "_timestamp", "is", "None", ":", "return", "None", "number_of_days", ",", "hours", ",", "minutes", ",", "seconds", "=", "self", ".", "_GetTimeValues", "(", "int", "(", "self", ".", "_timestamp", ")", ")", "year", ",", "month", ",", "day_of_month", "=", "self", ".", "_GetDateValuesWithEpoch", "(", "number_of_days", ",", "self", ".", "_EPOCH", ")", "microseconds", "=", "int", "(", "(", "self", ".", "_timestamp", "%", "1", ")", "*", "definitions", ".", "MICROSECONDS_PER_SECOND", ")", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'", ".", "format", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ",", "microseconds", ")" ]
Copies the Cocoa timestamp to a date and time string. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.###### or None if the timestamp cannot be copied to a date and time string.
[ "Copies", "the", "Cocoa", "timestamp", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/cocoa_time.py#L106-L126
train
RyanBalfanz/django-smsish
smsish/sms/backends/rq.py
send_sms_message
def send_sms_message(sms_message, backend=None, fail_silently=False): """ Send an SMSMessage instance using a connection given by the specified `backend`. """ with get_sms_connection(backend=backend, fail_silently=fail_silently) as connection: result = connection.send_messages([sms_message]) return result
python
def send_sms_message(sms_message, backend=None, fail_silently=False): """ Send an SMSMessage instance using a connection given by the specified `backend`. """ with get_sms_connection(backend=backend, fail_silently=fail_silently) as connection: result = connection.send_messages([sms_message]) return result
[ "def", "send_sms_message", "(", "sms_message", ",", "backend", "=", "None", ",", "fail_silently", "=", "False", ")", ":", "with", "get_sms_connection", "(", "backend", "=", "backend", ",", "fail_silently", "=", "fail_silently", ")", "as", "connection", ":", "result", "=", "connection", ".", "send_messages", "(", "[", "sms_message", "]", ")", "return", "result" ]
Send an SMSMessage instance using a connection given by the specified `backend`.
[ "Send", "an", "SMSMessage", "instance", "using", "a", "connection", "given", "by", "the", "specified", "backend", "." ]
4d450e3d217cea9e373f16c5e4f0beb3218bd5c9
https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/backends/rq.py#L45-L51
train
RyanBalfanz/django-smsish
smsish/sms/backends/rq.py
SMSBackend.send_messages
def send_messages(self, sms_messages): """ Receives a list of SMSMessage instances and returns a list of RQ `Job` instances. """ results = [] for message in sms_messages: try: assert message.connection is None except AssertionError: if not self.fail_silently: raise backend = self.backend fail_silently = self.fail_silently result = django_rq.enqueue(self._send, message, backend=backend, fail_silently=fail_silently) results.append(result) return results
python
def send_messages(self, sms_messages): """ Receives a list of SMSMessage instances and returns a list of RQ `Job` instances. """ results = [] for message in sms_messages: try: assert message.connection is None except AssertionError: if not self.fail_silently: raise backend = self.backend fail_silently = self.fail_silently result = django_rq.enqueue(self._send, message, backend=backend, fail_silently=fail_silently) results.append(result) return results
[ "def", "send_messages", "(", "self", ",", "sms_messages", ")", ":", "results", "=", "[", "]", "for", "message", "in", "sms_messages", ":", "try", ":", "assert", "message", ".", "connection", "is", "None", "except", "AssertionError", ":", "if", "not", "self", ".", "fail_silently", ":", "raise", "backend", "=", "self", ".", "backend", "fail_silently", "=", "self", ".", "fail_silently", "result", "=", "django_rq", ".", "enqueue", "(", "self", ".", "_send", ",", "message", ",", "backend", "=", "backend", ",", "fail_silently", "=", "fail_silently", ")", "results", ".", "append", "(", "result", ")", "return", "results" ]
Receives a list of SMSMessage instances and returns a list of RQ `Job` instances.
[ "Receives", "a", "list", "of", "SMSMessage", "instances", "and", "returns", "a", "list", "of", "RQ", "Job", "instances", "." ]
4d450e3d217cea9e373f16c5e4f0beb3218bd5c9
https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/backends/rq.py#L24-L39
train
log2timeline/dfdatetime
dfdatetime/java_time.py
JavaTime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= self._INT64_MIN and self._timestamp <= self._INT64_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.MILLISECONDS_PER_SECOND) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if (self._timestamp is not None and self._timestamp >= self._INT64_MIN and self._timestamp <= self._INT64_MAX): self._normalized_timestamp = ( decimal.Decimal(self._timestamp) / definitions.MILLISECONDS_PER_SECOND) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "(", "self", ".", "_timestamp", "is", "not", "None", "and", "self", ".", "_timestamp", ">=", "self", ".", "_INT64_MIN", "and", "self", ".", "_timestamp", "<=", "self", ".", "_INT64_MAX", ")", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "_timestamp", ")", "/", "definitions", ".", "MILLISECONDS_PER_SECOND", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/java_time.py#L26-L42
train
log2timeline/dfdatetime
dfdatetime/java_time.py
JavaTime.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.######" or None if the timestamp is missing. """ if (self._timestamp is None or self._timestamp < self._INT64_MIN or self._timestamp > self._INT64_MAX): return None return super(JavaTime, self).CopyToDateTimeString()
python
def CopyToDateTimeString(self): """Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.######" or None if the timestamp is missing. """ if (self._timestamp is None or self._timestamp < self._INT64_MIN or self._timestamp > self._INT64_MAX): return None return super(JavaTime, self).CopyToDateTimeString()
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "(", "self", ".", "_timestamp", "is", "None", "or", "self", ".", "_timestamp", "<", "self", ".", "_INT64_MIN", "or", "self", ".", "_timestamp", ">", "self", ".", "_INT64_MAX", ")", ":", "return", "None", "return", "super", "(", "JavaTime", ",", "self", ")", ".", "CopyToDateTimeString", "(", ")" ]
Copies the POSIX timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.######" or None if the timestamp is missing.
[ "Copies", "the", "POSIX", "timestamp", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/java_time.py#L44-L55
train
springload/wagtaildraftail
wagtaildraftail/decorators.py
Image
def Image(props): """ Inspired by: - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/rich_text.py - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/shortcuts.py - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/formats.py """ image_model = get_image_model() alignment = props.get('alignment', 'left') alt_text = props.get('altText', '') try: image = image_model.objects.get(id=props['id']) except image_model.DoesNotExist: return DOM.create_element('img', {'alt': alt_text}) image_format = get_image_format(alignment) rendition = get_rendition_or_not_found(image, image_format.filter_spec) return DOM.create_element('img', dict(rendition.attrs_dict, **{ 'class': image_format.classnames, 'src': rendition.url, 'alt': alt_text, }))
python
def Image(props): """ Inspired by: - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/rich_text.py - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/shortcuts.py - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/formats.py """ image_model = get_image_model() alignment = props.get('alignment', 'left') alt_text = props.get('altText', '') try: image = image_model.objects.get(id=props['id']) except image_model.DoesNotExist: return DOM.create_element('img', {'alt': alt_text}) image_format = get_image_format(alignment) rendition = get_rendition_or_not_found(image, image_format.filter_spec) return DOM.create_element('img', dict(rendition.attrs_dict, **{ 'class': image_format.classnames, 'src': rendition.url, 'alt': alt_text, }))
[ "def", "Image", "(", "props", ")", ":", "image_model", "=", "get_image_model", "(", ")", "alignment", "=", "props", ".", "get", "(", "'alignment'", ",", "'left'", ")", "alt_text", "=", "props", ".", "get", "(", "'altText'", ",", "''", ")", "try", ":", "image", "=", "image_model", ".", "objects", ".", "get", "(", "id", "=", "props", "[", "'id'", "]", ")", "except", "image_model", ".", "DoesNotExist", ":", "return", "DOM", ".", "create_element", "(", "'img'", ",", "{", "'alt'", ":", "alt_text", "}", ")", "image_format", "=", "get_image_format", "(", "alignment", ")", "rendition", "=", "get_rendition_or_not_found", "(", "image", ",", "image_format", ".", "filter_spec", ")", "return", "DOM", ".", "create_element", "(", "'img'", ",", "dict", "(", "rendition", ".", "attrs_dict", ",", "*", "*", "{", "'class'", ":", "image_format", ".", "classnames", ",", "'src'", ":", "rendition", ".", "url", ",", "'alt'", ":", "alt_text", ",", "}", ")", ")" ]
Inspired by: - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/rich_text.py - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/shortcuts.py - https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailimages/formats.py
[ "Inspired", "by", ":", "-", "https", ":", "//", "github", ".", "com", "/", "torchbox", "/", "wagtail", "/", "blob", "/", "master", "/", "wagtail", "/", "wagtailimages", "/", "rich_text", ".", "py", "-", "https", ":", "//", "github", ".", "com", "/", "torchbox", "/", "wagtail", "/", "blob", "/", "master", "/", "wagtail", "/", "wagtailimages", "/", "shortcuts", ".", "py", "-", "https", ":", "//", "github", ".", "com", "/", "torchbox", "/", "wagtail", "/", "blob", "/", "master", "/", "wagtail", "/", "wagtailimages", "/", "formats", ".", "py" ]
87f1ae3ade493c00daff021394051aa656136c10
https://github.com/springload/wagtaildraftail/blob/87f1ae3ade493c00daff021394051aa656136c10/wagtaildraftail/decorators.py#L53-L76
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElements._CopyDateTimeFromStringISO8601
def _CopyDateTimeFromStringISO8601(self, time_string): """Copies a date and time from an ISO 8601 date and time string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The fraction of second and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported. """ if not time_string: raise ValueError('Invalid time string.') time_string_length = len(time_string) year, month, day_of_month = self._CopyDateFromString(time_string) if time_string_length <= 10: return { 'year': year, 'month': month, 'day_of_month': day_of_month} # If a time of day is specified the time string it should at least # contain 'YYYY-MM-DDThh'. if time_string[10] != 'T': raise ValueError( 'Invalid time string - missing as date and time separator.') hours, minutes, seconds, microseconds, time_zone_offset = ( self._CopyTimeFromStringISO8601(time_string[11:])) if time_zone_offset: year, month, day_of_month, hours, minutes = self._AdjustForTimeZoneOffset( year, month, day_of_month, hours, minutes, time_zone_offset) date_time_values = { 'year': year, 'month': month, 'day_of_month': day_of_month, 'hours': hours, 'minutes': minutes, 'seconds': seconds} if microseconds is not None: date_time_values['microseconds'] = microseconds return date_time_values
python
def _CopyDateTimeFromStringISO8601(self, time_string): """Copies a date and time from an ISO 8601 date and time string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The fraction of second and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported. """ if not time_string: raise ValueError('Invalid time string.') time_string_length = len(time_string) year, month, day_of_month = self._CopyDateFromString(time_string) if time_string_length <= 10: return { 'year': year, 'month': month, 'day_of_month': day_of_month} # If a time of day is specified the time string it should at least # contain 'YYYY-MM-DDThh'. if time_string[10] != 'T': raise ValueError( 'Invalid time string - missing as date and time separator.') hours, minutes, seconds, microseconds, time_zone_offset = ( self._CopyTimeFromStringISO8601(time_string[11:])) if time_zone_offset: year, month, day_of_month, hours, minutes = self._AdjustForTimeZoneOffset( year, month, day_of_month, hours, minutes, time_zone_offset) date_time_values = { 'year': year, 'month': month, 'day_of_month': day_of_month, 'hours': hours, 'minutes': minutes, 'seconds': seconds} if microseconds is not None: date_time_values['microseconds'] = microseconds return date_time_values
[ "def", "_CopyDateTimeFromStringISO8601", "(", "self", ",", "time_string", ")", ":", "if", "not", "time_string", ":", "raise", "ValueError", "(", "'Invalid time string.'", ")", "time_string_length", "=", "len", "(", "time_string", ")", "year", ",", "month", ",", "day_of_month", "=", "self", ".", "_CopyDateFromString", "(", "time_string", ")", "if", "time_string_length", "<=", "10", ":", "return", "{", "'year'", ":", "year", ",", "'month'", ":", "month", ",", "'day_of_month'", ":", "day_of_month", "}", "# If a time of day is specified the time string it should at least", "# contain 'YYYY-MM-DDThh'.", "if", "time_string", "[", "10", "]", "!=", "'T'", ":", "raise", "ValueError", "(", "'Invalid time string - missing as date and time separator.'", ")", "hours", ",", "minutes", ",", "seconds", ",", "microseconds", ",", "time_zone_offset", "=", "(", "self", ".", "_CopyTimeFromStringISO8601", "(", "time_string", "[", "11", ":", "]", ")", ")", "if", "time_zone_offset", ":", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", "=", "self", ".", "_AdjustForTimeZoneOffset", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "time_zone_offset", ")", "date_time_values", "=", "{", "'year'", ":", "year", ",", "'month'", ":", "month", ",", "'day_of_month'", ":", "day_of_month", ",", "'hours'", ":", "hours", ",", "'minutes'", ":", "minutes", ",", "'seconds'", ":", "seconds", "}", "if", "microseconds", "is", "not", "None", ":", "date_time_values", "[", "'microseconds'", "]", "=", "microseconds", "return", "date_time_values" ]
Copies a date and time from an ISO 8601 date and time string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The fraction of second and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported.
[ "Copies", "a", "date", "and", "time", "from", "an", "ISO", "8601", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L63-L117
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElements._CopyFromDateTimeValues
def _CopyFromDateTimeValues(self, date_time_values): """Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds. """ year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self._time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds) self.is_local_time = False
python
def _CopyFromDateTimeValues(self, date_time_values): """Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds. """ year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self._time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds) self.is_local_time = False
[ "def", "_CopyFromDateTimeValues", "(", "self", ",", "date_time_values", ")", ":", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date_time_values", ".", "get", "(", "'month'", ",", "0", ")", "day_of_month", "=", "date_time_values", ".", "get", "(", "'day_of_month'", ",", "0", ")", "hours", "=", "date_time_values", ".", "get", "(", "'hours'", ",", "0", ")", "minutes", "=", "date_time_values", ".", "get", "(", "'minutes'", ",", "0", ")", "seconds", "=", "date_time_values", ".", "get", "(", "'seconds'", ",", "0", ")", "self", ".", "_normalized_timestamp", "=", "None", "self", ".", "_number_of_seconds", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "self", ".", "_time_elements_tuple", "=", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "self", ".", "is_local_time", "=", "False" ]
Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds.
[ "Copies", "time", "elements", "from", "date", "and", "time", "values", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L119-L139
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElements._CopyTimeFromStringISO8601
def _CopyTimeFromStringISO8601(self, time_string): """Copies a time from an ISO 8601 date and time string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The faction of second and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported. """ if time_string.endswith('Z'): time_string = time_string[:-1] time_string_length = len(time_string) # The time string should at least contain 'hh'. if time_string_length < 2: raise ValueError('Time string too short.') try: hours = int(time_string[0:2], 10) except ValueError: raise ValueError('Unable to parse hours.') if hours not in range(0, 24): raise ValueError('Hours value: {0:d} out of bounds.'.format(hours)) minutes = None seconds = None microseconds = None time_zone_offset = None time_string_index = 2 # Minutes are either specified as 'hhmm', 'hh:mm' or as a fractional part # 'hh[.,]###'. if (time_string_index + 1 < time_string_length and time_string[time_string_index] not in ('.', ',')): if time_string[time_string_index] == ':': time_string_index += 1 if time_string_index + 2 > time_string_length: raise ValueError('Time string too short.') try: minutes = time_string[time_string_index:time_string_index + 2] minutes = int(minutes, 10) except ValueError: raise ValueError('Unable to parse minutes.') time_string_index += 2 # Seconds are either specified as 'hhmmss', 'hh:mm:ss' or as a fractional # part 'hh:mm[.,]###' or 'hhmm[.,]###'. if (time_string_index + 1 < time_string_length and time_string[time_string_index] not in ('.', ',')): if time_string[time_string_index] == ':': time_string_index += 1 if time_string_index + 2 > time_string_length: raise ValueError('Time string too short.') try: seconds = time_string[time_string_index:time_string_index + 2] seconds = int(seconds, 10) except ValueError: raise ValueError('Unable to parse day of seconds.') time_string_index += 2 time_zone_string_index = time_string_index while time_zone_string_index < time_string_length: if time_string[time_zone_string_index] in ('+', '-'): break time_zone_string_index += 1 # The calculations that follow rely on the time zone string index # to point beyond the string in case no time zone offset was defined. if time_zone_string_index == time_string_length - 1: time_zone_string_index += 1 if (time_string_length > time_string_index and time_string[time_string_index] in ('.', ',')): time_string_index += 1 time_fraction_length = time_zone_string_index - time_string_index try: time_fraction = time_string[time_string_index:time_zone_string_index] time_fraction = int(time_fraction, 10) time_fraction = ( decimal.Decimal(time_fraction) / decimal.Decimal(10 ** time_fraction_length)) except ValueError: raise ValueError('Unable to parse time fraction.') if minutes is None: time_fraction *= 60 minutes = int(time_fraction) time_fraction -= minutes if seconds is None: time_fraction *= 60 seconds = int(time_fraction) time_fraction -= seconds time_fraction *= definitions.MICROSECONDS_PER_SECOND microseconds = int(time_fraction) if minutes is not None and minutes not in range(0, 60): raise ValueError('Minutes value: {0:d} out of bounds.'.format(minutes)) # TODO: support a leap second? if seconds is not None and seconds not in range(0, 60): raise ValueError('Seconds value: {0:d} out of bounds.'.format(seconds)) if time_zone_string_index < time_string_length: if (time_string_length - time_zone_string_index != 6 or time_string[time_zone_string_index + 3] != ':'): raise ValueError('Invalid time string.') try: hours_from_utc = int(time_string[ time_zone_string_index + 1:time_zone_string_index + 3]) except ValueError: raise ValueError('Unable to parse time zone hours offset.') if hours_from_utc not in range(0, 15): raise ValueError('Time zone hours offset value out of bounds.') try: minutes_from_utc = int(time_string[ time_zone_string_index + 4:time_zone_string_index + 6]) except ValueError: raise ValueError('Unable to parse time zone minutes offset.') if minutes_from_utc not in range(0, 60): raise ValueError('Time zone minutes offset value out of bounds.') # pylint: disable=invalid-unary-operand-type time_zone_offset = (hours_from_utc * 60) + minutes_from_utc # Note that when the sign of the time zone offset is negative # the difference needs to be added. We do so by flipping the sign. if time_string[time_zone_string_index] != '-': time_zone_offset = -time_zone_offset return hours, minutes, seconds, microseconds, time_zone_offset
python
def _CopyTimeFromStringISO8601(self, time_string): """Copies a time from an ISO 8601 date and time string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The faction of second and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported. """ if time_string.endswith('Z'): time_string = time_string[:-1] time_string_length = len(time_string) # The time string should at least contain 'hh'. if time_string_length < 2: raise ValueError('Time string too short.') try: hours = int(time_string[0:2], 10) except ValueError: raise ValueError('Unable to parse hours.') if hours not in range(0, 24): raise ValueError('Hours value: {0:d} out of bounds.'.format(hours)) minutes = None seconds = None microseconds = None time_zone_offset = None time_string_index = 2 # Minutes are either specified as 'hhmm', 'hh:mm' or as a fractional part # 'hh[.,]###'. if (time_string_index + 1 < time_string_length and time_string[time_string_index] not in ('.', ',')): if time_string[time_string_index] == ':': time_string_index += 1 if time_string_index + 2 > time_string_length: raise ValueError('Time string too short.') try: minutes = time_string[time_string_index:time_string_index + 2] minutes = int(minutes, 10) except ValueError: raise ValueError('Unable to parse minutes.') time_string_index += 2 # Seconds are either specified as 'hhmmss', 'hh:mm:ss' or as a fractional # part 'hh:mm[.,]###' or 'hhmm[.,]###'. if (time_string_index + 1 < time_string_length and time_string[time_string_index] not in ('.', ',')): if time_string[time_string_index] == ':': time_string_index += 1 if time_string_index + 2 > time_string_length: raise ValueError('Time string too short.') try: seconds = time_string[time_string_index:time_string_index + 2] seconds = int(seconds, 10) except ValueError: raise ValueError('Unable to parse day of seconds.') time_string_index += 2 time_zone_string_index = time_string_index while time_zone_string_index < time_string_length: if time_string[time_zone_string_index] in ('+', '-'): break time_zone_string_index += 1 # The calculations that follow rely on the time zone string index # to point beyond the string in case no time zone offset was defined. if time_zone_string_index == time_string_length - 1: time_zone_string_index += 1 if (time_string_length > time_string_index and time_string[time_string_index] in ('.', ',')): time_string_index += 1 time_fraction_length = time_zone_string_index - time_string_index try: time_fraction = time_string[time_string_index:time_zone_string_index] time_fraction = int(time_fraction, 10) time_fraction = ( decimal.Decimal(time_fraction) / decimal.Decimal(10 ** time_fraction_length)) except ValueError: raise ValueError('Unable to parse time fraction.') if minutes is None: time_fraction *= 60 minutes = int(time_fraction) time_fraction -= minutes if seconds is None: time_fraction *= 60 seconds = int(time_fraction) time_fraction -= seconds time_fraction *= definitions.MICROSECONDS_PER_SECOND microseconds = int(time_fraction) if minutes is not None and minutes not in range(0, 60): raise ValueError('Minutes value: {0:d} out of bounds.'.format(minutes)) # TODO: support a leap second? if seconds is not None and seconds not in range(0, 60): raise ValueError('Seconds value: {0:d} out of bounds.'.format(seconds)) if time_zone_string_index < time_string_length: if (time_string_length - time_zone_string_index != 6 or time_string[time_zone_string_index + 3] != ':'): raise ValueError('Invalid time string.') try: hours_from_utc = int(time_string[ time_zone_string_index + 1:time_zone_string_index + 3]) except ValueError: raise ValueError('Unable to parse time zone hours offset.') if hours_from_utc not in range(0, 15): raise ValueError('Time zone hours offset value out of bounds.') try: minutes_from_utc = int(time_string[ time_zone_string_index + 4:time_zone_string_index + 6]) except ValueError: raise ValueError('Unable to parse time zone minutes offset.') if minutes_from_utc not in range(0, 60): raise ValueError('Time zone minutes offset value out of bounds.') # pylint: disable=invalid-unary-operand-type time_zone_offset = (hours_from_utc * 60) + minutes_from_utc # Note that when the sign of the time zone offset is negative # the difference needs to be added. We do so by flipping the sign. if time_string[time_zone_string_index] != '-': time_zone_offset = -time_zone_offset return hours, minutes, seconds, microseconds, time_zone_offset
[ "def", "_CopyTimeFromStringISO8601", "(", "self", ",", "time_string", ")", ":", "if", "time_string", ".", "endswith", "(", "'Z'", ")", ":", "time_string", "=", "time_string", "[", ":", "-", "1", "]", "time_string_length", "=", "len", "(", "time_string", ")", "# The time string should at least contain 'hh'.", "if", "time_string_length", "<", "2", ":", "raise", "ValueError", "(", "'Time string too short.'", ")", "try", ":", "hours", "=", "int", "(", "time_string", "[", "0", ":", "2", "]", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse hours.'", ")", "if", "hours", "not", "in", "range", "(", "0", ",", "24", ")", ":", "raise", "ValueError", "(", "'Hours value: {0:d} out of bounds.'", ".", "format", "(", "hours", ")", ")", "minutes", "=", "None", "seconds", "=", "None", "microseconds", "=", "None", "time_zone_offset", "=", "None", "time_string_index", "=", "2", "# Minutes are either specified as 'hhmm', 'hh:mm' or as a fractional part", "# 'hh[.,]###'.", "if", "(", "time_string_index", "+", "1", "<", "time_string_length", "and", "time_string", "[", "time_string_index", "]", "not", "in", "(", "'.'", ",", "','", ")", ")", ":", "if", "time_string", "[", "time_string_index", "]", "==", "':'", ":", "time_string_index", "+=", "1", "if", "time_string_index", "+", "2", ">", "time_string_length", ":", "raise", "ValueError", "(", "'Time string too short.'", ")", "try", ":", "minutes", "=", "time_string", "[", "time_string_index", ":", "time_string_index", "+", "2", "]", "minutes", "=", "int", "(", "minutes", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse minutes.'", ")", "time_string_index", "+=", "2", "# Seconds are either specified as 'hhmmss', 'hh:mm:ss' or as a fractional", "# part 'hh:mm[.,]###' or 'hhmm[.,]###'.", "if", "(", "time_string_index", "+", "1", "<", "time_string_length", "and", "time_string", "[", "time_string_index", "]", "not", "in", "(", "'.'", ",", "','", ")", ")", ":", "if", "time_string", "[", "time_string_index", "]", "==", "':'", ":", "time_string_index", "+=", "1", "if", "time_string_index", "+", "2", ">", "time_string_length", ":", "raise", "ValueError", "(", "'Time string too short.'", ")", "try", ":", "seconds", "=", "time_string", "[", "time_string_index", ":", "time_string_index", "+", "2", "]", "seconds", "=", "int", "(", "seconds", ",", "10", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse day of seconds.'", ")", "time_string_index", "+=", "2", "time_zone_string_index", "=", "time_string_index", "while", "time_zone_string_index", "<", "time_string_length", ":", "if", "time_string", "[", "time_zone_string_index", "]", "in", "(", "'+'", ",", "'-'", ")", ":", "break", "time_zone_string_index", "+=", "1", "# The calculations that follow rely on the time zone string index", "# to point beyond the string in case no time zone offset was defined.", "if", "time_zone_string_index", "==", "time_string_length", "-", "1", ":", "time_zone_string_index", "+=", "1", "if", "(", "time_string_length", ">", "time_string_index", "and", "time_string", "[", "time_string_index", "]", "in", "(", "'.'", ",", "','", ")", ")", ":", "time_string_index", "+=", "1", "time_fraction_length", "=", "time_zone_string_index", "-", "time_string_index", "try", ":", "time_fraction", "=", "time_string", "[", "time_string_index", ":", "time_zone_string_index", "]", "time_fraction", "=", "int", "(", "time_fraction", ",", "10", ")", "time_fraction", "=", "(", "decimal", ".", "Decimal", "(", "time_fraction", ")", "/", "decimal", ".", "Decimal", "(", "10", "**", "time_fraction_length", ")", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse time fraction.'", ")", "if", "minutes", "is", "None", ":", "time_fraction", "*=", "60", "minutes", "=", "int", "(", "time_fraction", ")", "time_fraction", "-=", "minutes", "if", "seconds", "is", "None", ":", "time_fraction", "*=", "60", "seconds", "=", "int", "(", "time_fraction", ")", "time_fraction", "-=", "seconds", "time_fraction", "*=", "definitions", ".", "MICROSECONDS_PER_SECOND", "microseconds", "=", "int", "(", "time_fraction", ")", "if", "minutes", "is", "not", "None", "and", "minutes", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Minutes value: {0:d} out of bounds.'", ".", "format", "(", "minutes", ")", ")", "# TODO: support a leap second?", "if", "seconds", "is", "not", "None", "and", "seconds", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Seconds value: {0:d} out of bounds.'", ".", "format", "(", "seconds", ")", ")", "if", "time_zone_string_index", "<", "time_string_length", ":", "if", "(", "time_string_length", "-", "time_zone_string_index", "!=", "6", "or", "time_string", "[", "time_zone_string_index", "+", "3", "]", "!=", "':'", ")", ":", "raise", "ValueError", "(", "'Invalid time string.'", ")", "try", ":", "hours_from_utc", "=", "int", "(", "time_string", "[", "time_zone_string_index", "+", "1", ":", "time_zone_string_index", "+", "3", "]", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse time zone hours offset.'", ")", "if", "hours_from_utc", "not", "in", "range", "(", "0", ",", "15", ")", ":", "raise", "ValueError", "(", "'Time zone hours offset value out of bounds.'", ")", "try", ":", "minutes_from_utc", "=", "int", "(", "time_string", "[", "time_zone_string_index", "+", "4", ":", "time_zone_string_index", "+", "6", "]", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Unable to parse time zone minutes offset.'", ")", "if", "minutes_from_utc", "not", "in", "range", "(", "0", ",", "60", ")", ":", "raise", "ValueError", "(", "'Time zone minutes offset value out of bounds.'", ")", "# pylint: disable=invalid-unary-operand-type", "time_zone_offset", "=", "(", "hours_from_utc", "*", "60", ")", "+", "minutes_from_utc", "# Note that when the sign of the time zone offset is negative", "# the difference needs to be added. We do so by flipping the sign.", "if", "time_string", "[", "time_zone_string_index", "]", "!=", "'-'", ":", "time_zone_offset", "=", "-", "time_zone_offset", "return", "hours", ",", "minutes", ",", "seconds", ",", "microseconds", ",", "time_zone_offset" ]
Copies a time from an ISO 8601 date and time string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The faction of second and time zone offset are optional. Returns: tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds, time zone offset in minutes. Raises: ValueError: if the time string is invalid or not supported.
[ "Copies", "a", "time", "from", "an", "ISO", "8601", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L141-L296
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElements.CopyFromDateTimeString
def CopyFromDateTimeString(self, time_string): """Copies time elements from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) self._CopyFromDateTimeValues(date_time_values)
python
def CopyFromDateTimeString(self, time_string): """Copies time elements from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) self._CopyFromDateTimeValues(date_time_values)
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "self", ".", "_CopyFromDateTimeValues", "(", "date_time_values", ")" ]
Copies time elements from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC.
[ "Copies", "time", "elements", "from", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L298-L312
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElements.CopyFromStringISO8601
def CopyFromStringISO8601(self, time_string): """Copies time elements from an ISO 8601 date and time string. Currently not supported: * Duration notation: "P..." * Week notation "2016-W33" * Date with week number notation "2016-W33-3" * Date without year notation "--08-17" * Ordinal date notation "2016-230" Args: time_string (str): date and time value formatted as: YYYY-MM-DDThh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the time string is invalid or not supported. """ date_time_values = self._CopyDateTimeFromStringISO8601(time_string) self._CopyFromDateTimeValues(date_time_values)
python
def CopyFromStringISO8601(self, time_string): """Copies time elements from an ISO 8601 date and time string. Currently not supported: * Duration notation: "P..." * Week notation "2016-W33" * Date with week number notation "2016-W33-3" * Date without year notation "--08-17" * Ordinal date notation "2016-230" Args: time_string (str): date and time value formatted as: YYYY-MM-DDThh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the time string is invalid or not supported. """ date_time_values = self._CopyDateTimeFromStringISO8601(time_string) self._CopyFromDateTimeValues(date_time_values)
[ "def", "CopyFromStringISO8601", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromStringISO8601", "(", "time_string", ")", "self", ".", "_CopyFromDateTimeValues", "(", "date_time_values", ")" ]
Copies time elements from an ISO 8601 date and time string. Currently not supported: * Duration notation: "P..." * Week notation "2016-W33" * Date with week number notation "2016-W33-3" * Date without year notation "--08-17" * Ordinal date notation "2016-230" Args: time_string (str): date and time value formatted as: YYYY-MM-DDThh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the time string is invalid or not supported.
[ "Copies", "time", "elements", "from", "an", "ISO", "8601", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L314-L338
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElements.CopyFromStringTuple
def CopyFromStringTuple(self, time_elements_tuple): """Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes and seconds. Raises: ValueError: if the time elements tuple is invalid. """ if len(time_elements_tuple) < 6: raise ValueError(( 'Invalid time elements tuple at least 6 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) try: year = int(time_elements_tuple[0], 10) except (TypeError, ValueError): raise ValueError('Invalid year value: {0!s}'.format( time_elements_tuple[0])) try: month = int(time_elements_tuple[1], 10) except (TypeError, ValueError): raise ValueError('Invalid month value: {0!s}'.format( time_elements_tuple[1])) try: day_of_month = int(time_elements_tuple[2], 10) except (TypeError, ValueError): raise ValueError('Invalid day of month value: {0!s}'.format( time_elements_tuple[2])) try: hours = int(time_elements_tuple[3], 10) except (TypeError, ValueError): raise ValueError('Invalid hours value: {0!s}'.format( time_elements_tuple[3])) try: minutes = int(time_elements_tuple[4], 10) except (TypeError, ValueError): raise ValueError('Invalid minutes value: {0!s}'.format( time_elements_tuple[4])) try: seconds = int(time_elements_tuple[5], 10) except (TypeError, ValueError): raise ValueError('Invalid seconds value: {0!s}'.format( time_elements_tuple[5])) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self._time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds)
python
def CopyFromStringTuple(self, time_elements_tuple): """Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes and seconds. Raises: ValueError: if the time elements tuple is invalid. """ if len(time_elements_tuple) < 6: raise ValueError(( 'Invalid time elements tuple at least 6 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) try: year = int(time_elements_tuple[0], 10) except (TypeError, ValueError): raise ValueError('Invalid year value: {0!s}'.format( time_elements_tuple[0])) try: month = int(time_elements_tuple[1], 10) except (TypeError, ValueError): raise ValueError('Invalid month value: {0!s}'.format( time_elements_tuple[1])) try: day_of_month = int(time_elements_tuple[2], 10) except (TypeError, ValueError): raise ValueError('Invalid day of month value: {0!s}'.format( time_elements_tuple[2])) try: hours = int(time_elements_tuple[3], 10) except (TypeError, ValueError): raise ValueError('Invalid hours value: {0!s}'.format( time_elements_tuple[3])) try: minutes = int(time_elements_tuple[4], 10) except (TypeError, ValueError): raise ValueError('Invalid minutes value: {0!s}'.format( time_elements_tuple[4])) try: seconds = int(time_elements_tuple[5], 10) except (TypeError, ValueError): raise ValueError('Invalid seconds value: {0!s}'.format( time_elements_tuple[5])) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self._time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds)
[ "def", "CopyFromStringTuple", "(", "self", ",", "time_elements_tuple", ")", ":", "if", "len", "(", "time_elements_tuple", ")", "<", "6", ":", "raise", "ValueError", "(", "(", "'Invalid time elements tuple at least 6 elements required,'", "'got: {0:d}'", ")", ".", "format", "(", "len", "(", "time_elements_tuple", ")", ")", ")", "try", ":", "year", "=", "int", "(", "time_elements_tuple", "[", "0", "]", ",", "10", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid year value: {0!s}'", ".", "format", "(", "time_elements_tuple", "[", "0", "]", ")", ")", "try", ":", "month", "=", "int", "(", "time_elements_tuple", "[", "1", "]", ",", "10", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid month value: {0!s}'", ".", "format", "(", "time_elements_tuple", "[", "1", "]", ")", ")", "try", ":", "day_of_month", "=", "int", "(", "time_elements_tuple", "[", "2", "]", ",", "10", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid day of month value: {0!s}'", ".", "format", "(", "time_elements_tuple", "[", "2", "]", ")", ")", "try", ":", "hours", "=", "int", "(", "time_elements_tuple", "[", "3", "]", ",", "10", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid hours value: {0!s}'", ".", "format", "(", "time_elements_tuple", "[", "3", "]", ")", ")", "try", ":", "minutes", "=", "int", "(", "time_elements_tuple", "[", "4", "]", ",", "10", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid minutes value: {0!s}'", ".", "format", "(", "time_elements_tuple", "[", "4", "]", ")", ")", "try", ":", "seconds", "=", "int", "(", "time_elements_tuple", "[", "5", "]", ",", "10", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid seconds value: {0!s}'", ".", "format", "(", "time_elements_tuple", "[", "5", "]", ")", ")", "self", ".", "_normalized_timestamp", "=", "None", "self", ".", "_number_of_seconds", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "self", ".", "_time_elements_tuple", "=", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")" ]
Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes and seconds. Raises: ValueError: if the time elements tuple is invalid.
[ "Copies", "time", "elements", "from", "string", "-", "based", "time", "elements", "tuple", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L340-L396
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElements.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the time elements to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None if time elements are missing. """ if self._number_of_seconds is None: return None return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format( self._time_elements_tuple[0], self._time_elements_tuple[1], self._time_elements_tuple[2], self._time_elements_tuple[3], self._time_elements_tuple[4], self._time_elements_tuple[5])
python
def CopyToDateTimeString(self): """Copies the time elements to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None if time elements are missing. """ if self._number_of_seconds is None: return None return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format( self._time_elements_tuple[0], self._time_elements_tuple[1], self._time_elements_tuple[2], self._time_elements_tuple[3], self._time_elements_tuple[4], self._time_elements_tuple[5])
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "self", ".", "_number_of_seconds", "is", "None", ":", "return", "None", "return", "'{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'", ".", "format", "(", "self", ".", "_time_elements_tuple", "[", "0", "]", ",", "self", ".", "_time_elements_tuple", "[", "1", "]", ",", "self", ".", "_time_elements_tuple", "[", "2", "]", ",", "self", ".", "_time_elements_tuple", "[", "3", "]", ",", "self", ".", "_time_elements_tuple", "[", "4", "]", ",", "self", ".", "_time_elements_tuple", "[", "5", "]", ")" ]
Copies the time elements to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None if time elements are missing.
[ "Copies", "the", "time", "elements", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L398-L411
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElementsWithFractionOfSecond._CopyFromDateTimeValues
def _CopyFromDateTimeValues(self, date_time_values): """Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds. Raises: ValueError: if no helper can be created for the current precision. """ year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', 0) precision_helper = precisions.PrecisionHelperFactory.CreatePrecisionHelper( self._precision) fraction_of_second = precision_helper.CopyMicrosecondsToFractionOfSecond( microseconds) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self._time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds) self.fraction_of_second = fraction_of_second self.is_local_time = False
python
def _CopyFromDateTimeValues(self, date_time_values): """Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds. Raises: ValueError: if no helper can be created for the current precision. """ year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', 0) precision_helper = precisions.PrecisionHelperFactory.CreatePrecisionHelper( self._precision) fraction_of_second = precision_helper.CopyMicrosecondsToFractionOfSecond( microseconds) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self._time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds) self.fraction_of_second = fraction_of_second self.is_local_time = False
[ "def", "_CopyFromDateTimeValues", "(", "self", ",", "date_time_values", ")", ":", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date_time_values", ".", "get", "(", "'month'", ",", "0", ")", "day_of_month", "=", "date_time_values", ".", "get", "(", "'day_of_month'", ",", "0", ")", "hours", "=", "date_time_values", ".", "get", "(", "'hours'", ",", "0", ")", "minutes", "=", "date_time_values", ".", "get", "(", "'minutes'", ",", "0", ")", "seconds", "=", "date_time_values", ".", "get", "(", "'seconds'", ",", "0", ")", "microseconds", "=", "date_time_values", ".", "get", "(", "'microseconds'", ",", "0", ")", "precision_helper", "=", "precisions", ".", "PrecisionHelperFactory", ".", "CreatePrecisionHelper", "(", "self", ".", "_precision", ")", "fraction_of_second", "=", "precision_helper", ".", "CopyMicrosecondsToFractionOfSecond", "(", "microseconds", ")", "self", ".", "_normalized_timestamp", "=", "None", "self", ".", "_number_of_seconds", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "self", ".", "_time_elements_tuple", "=", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "self", ".", "fraction_of_second", "=", "fraction_of_second", "self", ".", "is_local_time", "=", "False" ]
Copies time elements from date and time values. Args: date_time_values (dict[str, int]): date and time values, such as year, month, day of month, hours, minutes, seconds, microseconds. Raises: ValueError: if no helper can be created for the current precision.
[ "Copies", "time", "elements", "from", "date", "and", "time", "values", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L465-L495
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElementsWithFractionOfSecond.CopyFromStringTuple
def CopyFromStringTuple(self, time_elements_tuple): """Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and fraction of seconds. Raises: ValueError: if the time elements tuple is invalid. """ if len(time_elements_tuple) < 7: raise ValueError(( 'Invalid time elements tuple at least 7 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) super(TimeElementsWithFractionOfSecond, self).CopyFromStringTuple( time_elements_tuple) try: fraction_of_second = decimal.Decimal(time_elements_tuple[6]) except (TypeError, ValueError): raise ValueError('Invalid fraction of second value: {0!s}'.format( time_elements_tuple[6])) if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError('Fraction of second value: {0:f} out of bounds.'.format( fraction_of_second)) self.fraction_of_second = fraction_of_second
python
def CopyFromStringTuple(self, time_elements_tuple): """Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and fraction of seconds. Raises: ValueError: if the time elements tuple is invalid. """ if len(time_elements_tuple) < 7: raise ValueError(( 'Invalid time elements tuple at least 7 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) super(TimeElementsWithFractionOfSecond, self).CopyFromStringTuple( time_elements_tuple) try: fraction_of_second = decimal.Decimal(time_elements_tuple[6]) except (TypeError, ValueError): raise ValueError('Invalid fraction of second value: {0!s}'.format( time_elements_tuple[6])) if fraction_of_second < 0.0 or fraction_of_second >= 1.0: raise ValueError('Fraction of second value: {0:f} out of bounds.'.format( fraction_of_second)) self.fraction_of_second = fraction_of_second
[ "def", "CopyFromStringTuple", "(", "self", ",", "time_elements_tuple", ")", ":", "if", "len", "(", "time_elements_tuple", ")", "<", "7", ":", "raise", "ValueError", "(", "(", "'Invalid time elements tuple at least 7 elements required,'", "'got: {0:d}'", ")", ".", "format", "(", "len", "(", "time_elements_tuple", ")", ")", ")", "super", "(", "TimeElementsWithFractionOfSecond", ",", "self", ")", ".", "CopyFromStringTuple", "(", "time_elements_tuple", ")", "try", ":", "fraction_of_second", "=", "decimal", ".", "Decimal", "(", "time_elements_tuple", "[", "6", "]", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid fraction of second value: {0!s}'", ".", "format", "(", "time_elements_tuple", "[", "6", "]", ")", ")", "if", "fraction_of_second", "<", "0.0", "or", "fraction_of_second", ">=", "1.0", ":", "raise", "ValueError", "(", "'Fraction of second value: {0:f} out of bounds.'", ".", "format", "(", "fraction_of_second", ")", ")", "self", ".", "fraction_of_second", "=", "fraction_of_second" ]
Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and fraction of seconds. Raises: ValueError: if the time elements tuple is invalid.
[ "Copies", "time", "elements", "from", "string", "-", "based", "time", "elements", "tuple", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L497-L526
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElementsWithFractionOfSecond.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the time elements to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or "YYYY-MM-DD hh:mm:ss.######" or None if time elements are missing. Raises: ValueError: if the precision value is unsupported. """ if self._number_of_seconds is None or self.fraction_of_second is None: return None precision_helper = precisions.PrecisionHelperFactory.CreatePrecisionHelper( self._precision) return precision_helper.CopyToDateTimeString( self._time_elements_tuple, self.fraction_of_second)
python
def CopyToDateTimeString(self): """Copies the time elements to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or "YYYY-MM-DD hh:mm:ss.######" or None if time elements are missing. Raises: ValueError: if the precision value is unsupported. """ if self._number_of_seconds is None or self.fraction_of_second is None: return None precision_helper = precisions.PrecisionHelperFactory.CreatePrecisionHelper( self._precision) return precision_helper.CopyToDateTimeString( self._time_elements_tuple, self.fraction_of_second)
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "self", ".", "_number_of_seconds", "is", "None", "or", "self", ".", "fraction_of_second", "is", "None", ":", "return", "None", "precision_helper", "=", "precisions", ".", "PrecisionHelperFactory", ".", "CreatePrecisionHelper", "(", "self", ".", "_precision", ")", "return", "precision_helper", ".", "CopyToDateTimeString", "(", "self", ".", "_time_elements_tuple", ",", "self", ".", "fraction_of_second", ")" ]
Copies the time elements to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or "YYYY-MM-DD hh:mm:ss.######" or None if time elements are missing. Raises: ValueError: if the precision value is unsupported.
[ "Copies", "the", "time", "elements", "to", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L528-L545
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElementsInMilliseconds.CopyFromStringTuple
def CopyFromStringTuple(self, time_elements_tuple): """Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and milliseconds. Raises: ValueError: if the time elements tuple is invalid. """ if len(time_elements_tuple) < 7: raise ValueError(( 'Invalid time elements tuple at least 7 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) year, month, day_of_month, hours, minutes, seconds, milliseconds = ( time_elements_tuple) try: milliseconds = int(milliseconds, 10) except (TypeError, ValueError): raise ValueError('Invalid millisecond value: {0!s}'.format(milliseconds)) if milliseconds < 0 or milliseconds >= definitions.MILLISECONDS_PER_SECOND: raise ValueError('Invalid number of milliseconds.') fraction_of_second = ( decimal.Decimal(milliseconds) / definitions.MILLISECONDS_PER_SECOND) time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds, str(fraction_of_second)) super(TimeElementsInMilliseconds, self).CopyFromStringTuple( time_elements_tuple)
python
def CopyFromStringTuple(self, time_elements_tuple): """Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and milliseconds. Raises: ValueError: if the time elements tuple is invalid. """ if len(time_elements_tuple) < 7: raise ValueError(( 'Invalid time elements tuple at least 7 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) year, month, day_of_month, hours, minutes, seconds, milliseconds = ( time_elements_tuple) try: milliseconds = int(milliseconds, 10) except (TypeError, ValueError): raise ValueError('Invalid millisecond value: {0!s}'.format(milliseconds)) if milliseconds < 0 or milliseconds >= definitions.MILLISECONDS_PER_SECOND: raise ValueError('Invalid number of milliseconds.') fraction_of_second = ( decimal.Decimal(milliseconds) / definitions.MILLISECONDS_PER_SECOND) time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds, str(fraction_of_second)) super(TimeElementsInMilliseconds, self).CopyFromStringTuple( time_elements_tuple)
[ "def", "CopyFromStringTuple", "(", "self", ",", "time_elements_tuple", ")", ":", "if", "len", "(", "time_elements_tuple", ")", "<", "7", ":", "raise", "ValueError", "(", "(", "'Invalid time elements tuple at least 7 elements required,'", "'got: {0:d}'", ")", ".", "format", "(", "len", "(", "time_elements_tuple", ")", ")", ")", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ",", "milliseconds", "=", "(", "time_elements_tuple", ")", "try", ":", "milliseconds", "=", "int", "(", "milliseconds", ",", "10", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid millisecond value: {0!s}'", ".", "format", "(", "milliseconds", ")", ")", "if", "milliseconds", "<", "0", "or", "milliseconds", ">=", "definitions", ".", "MILLISECONDS_PER_SECOND", ":", "raise", "ValueError", "(", "'Invalid number of milliseconds.'", ")", "fraction_of_second", "=", "(", "decimal", ".", "Decimal", "(", "milliseconds", ")", "/", "definitions", ".", "MILLISECONDS_PER_SECOND", ")", "time_elements_tuple", "=", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ",", "str", "(", "fraction_of_second", ")", ")", "super", "(", "TimeElementsInMilliseconds", ",", "self", ")", ".", "CopyFromStringTuple", "(", "time_elements_tuple", ")" ]
Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and milliseconds. Raises: ValueError: if the time elements tuple is invalid.
[ "Copies", "time", "elements", "from", "string", "-", "based", "time", "elements", "tuple", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L597-L632
train
log2timeline/dfdatetime
dfdatetime/time_elements.py
TimeElementsInMicroseconds.CopyFromStringTuple
def CopyFromStringTuple(self, time_elements_tuple): """Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and microseconds. Raises: ValueError: if the time elements tuple is invalid. """ if len(time_elements_tuple) < 7: raise ValueError(( 'Invalid time elements tuple at least 7 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) year, month, day_of_month, hours, minutes, seconds, microseconds = ( time_elements_tuple) try: microseconds = int(microseconds, 10) except (TypeError, ValueError): raise ValueError('Invalid microsecond value: {0!s}'.format(microseconds)) if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND: raise ValueError('Invalid number of microseconds.') fraction_of_second = ( decimal.Decimal(microseconds) / definitions.MICROSECONDS_PER_SECOND) time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds, str(fraction_of_second)) super(TimeElementsInMicroseconds, self).CopyFromStringTuple( time_elements_tuple)
python
def CopyFromStringTuple(self, time_elements_tuple): """Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and microseconds. Raises: ValueError: if the time elements tuple is invalid. """ if len(time_elements_tuple) < 7: raise ValueError(( 'Invalid time elements tuple at least 7 elements required,' 'got: {0:d}').format(len(time_elements_tuple))) year, month, day_of_month, hours, minutes, seconds, microseconds = ( time_elements_tuple) try: microseconds = int(microseconds, 10) except (TypeError, ValueError): raise ValueError('Invalid microsecond value: {0!s}'.format(microseconds)) if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND: raise ValueError('Invalid number of microseconds.') fraction_of_second = ( decimal.Decimal(microseconds) / definitions.MICROSECONDS_PER_SECOND) time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds, str(fraction_of_second)) super(TimeElementsInMicroseconds, self).CopyFromStringTuple( time_elements_tuple)
[ "def", "CopyFromStringTuple", "(", "self", ",", "time_elements_tuple", ")", ":", "if", "len", "(", "time_elements_tuple", ")", "<", "7", ":", "raise", "ValueError", "(", "(", "'Invalid time elements tuple at least 7 elements required,'", "'got: {0:d}'", ")", ".", "format", "(", "len", "(", "time_elements_tuple", ")", ")", ")", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ",", "microseconds", "=", "(", "time_elements_tuple", ")", "try", ":", "microseconds", "=", "int", "(", "microseconds", ",", "10", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "'Invalid microsecond value: {0!s}'", ".", "format", "(", "microseconds", ")", ")", "if", "microseconds", "<", "0", "or", "microseconds", ">=", "definitions", ".", "MICROSECONDS_PER_SECOND", ":", "raise", "ValueError", "(", "'Invalid number of microseconds.'", ")", "fraction_of_second", "=", "(", "decimal", ".", "Decimal", "(", "microseconds", ")", "/", "definitions", ".", "MICROSECONDS_PER_SECOND", ")", "time_elements_tuple", "=", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ",", "str", "(", "fraction_of_second", ")", ")", "super", "(", "TimeElementsInMicroseconds", ",", "self", ")", ".", "CopyFromStringTuple", "(", "time_elements_tuple", ")" ]
Copies time elements from string-based time elements tuple. Args: time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]): time elements, contains year, month, day of month, hours, minutes, seconds and microseconds. Raises: ValueError: if the time elements tuple is invalid.
[ "Copies", "time", "elements", "from", "string", "-", "based", "time", "elements", "tuple", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L684-L719
train
log2timeline/dfdatetime
dfdatetime/systemtime.py
Systemtime._GetNormalizedTimestamp
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._number_of_seconds is not None: self._normalized_timestamp = ( decimal.Decimal(self.milliseconds) / definitions.MILLISECONDS_PER_SECOND) self._normalized_timestamp += decimal.Decimal(self._number_of_seconds) return self._normalized_timestamp
python
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined. """ if self._normalized_timestamp is None: if self._number_of_seconds is not None: self._normalized_timestamp = ( decimal.Decimal(self.milliseconds) / definitions.MILLISECONDS_PER_SECOND) self._normalized_timestamp += decimal.Decimal(self._number_of_seconds) return self._normalized_timestamp
[ "def", "_GetNormalizedTimestamp", "(", "self", ")", ":", "if", "self", ".", "_normalized_timestamp", "is", "None", ":", "if", "self", ".", "_number_of_seconds", "is", "not", "None", ":", "self", ".", "_normalized_timestamp", "=", "(", "decimal", ".", "Decimal", "(", "self", ".", "milliseconds", ")", "/", "definitions", ".", "MILLISECONDS_PER_SECOND", ")", "self", ".", "_normalized_timestamp", "+=", "decimal", ".", "Decimal", "(", "self", ".", "_number_of_seconds", ")", "return", "self", ".", "_normalized_timestamp" ]
Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cannot be determined.
[ "Retrieves", "the", "normalized", "timestamp", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/systemtime.py#L109-L125
train
log2timeline/dfdatetime
dfdatetime/systemtime.py
Systemtime.CopyFromDateTimeString
def CopyFromDateTimeString(self, time_string): """Copies a SYSTEMTIME structure from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the date string is invalid or not supported. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', 0) milliseconds, _ = divmod( microseconds, definitions.MICROSECONDS_PER_MILLISECOND) if year < 1601 or year > 30827: raise ValueError('Unsupported year value: {0:d}.'.format(year)) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self.year = year self.month = month self.day_of_month = day_of_month # TODO: calculate day of week on demand. self.day_of_week = None self.hours = hours self.minutes = minutes self.seconds = seconds self.milliseconds = milliseconds self.is_local_time = False
python
def CopyFromDateTimeString(self, time_string): """Copies a SYSTEMTIME structure from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the date string is invalid or not supported. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', 0) milliseconds, _ = divmod( microseconds, definitions.MICROSECONDS_PER_MILLISECOND) if year < 1601 or year > 30827: raise ValueError('Unsupported year value: {0:d}.'.format(year)) self._normalized_timestamp = None self._number_of_seconds = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self.year = year self.month = month self.day_of_month = day_of_month # TODO: calculate day of week on demand. self.day_of_week = None self.hours = hours self.minutes = minutes self.seconds = seconds self.milliseconds = milliseconds self.is_local_time = False
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date_time_values", ".", "get", "(", "'month'", ",", "0", ")", "day_of_month", "=", "date_time_values", ".", "get", "(", "'day_of_month'", ",", "0", ")", "hours", "=", "date_time_values", ".", "get", "(", "'hours'", ",", "0", ")", "minutes", "=", "date_time_values", ".", "get", "(", "'minutes'", ",", "0", ")", "seconds", "=", "date_time_values", ".", "get", "(", "'seconds'", ",", "0", ")", "microseconds", "=", "date_time_values", ".", "get", "(", "'microseconds'", ",", "0", ")", "milliseconds", ",", "_", "=", "divmod", "(", "microseconds", ",", "definitions", ".", "MICROSECONDS_PER_MILLISECOND", ")", "if", "year", "<", "1601", "or", "year", ">", "30827", ":", "raise", "ValueError", "(", "'Unsupported year value: {0:d}.'", ".", "format", "(", "year", ")", ")", "self", ".", "_normalized_timestamp", "=", "None", "self", ".", "_number_of_seconds", "=", "self", ".", "_GetNumberOfSecondsFromElements", "(", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "seconds", ")", "self", ".", "year", "=", "year", "self", ".", "month", "=", "month", "self", ".", "day_of_month", "=", "day_of_month", "# TODO: calculate day of week on demand.", "self", ".", "day_of_week", "=", "None", "self", ".", "hours", "=", "hours", "self", ".", "minutes", "=", "minutes", "self", ".", "seconds", "=", "seconds", "self", ".", "milliseconds", "=", "milliseconds", "self", ".", "is_local_time", "=", "False" ]
Copies a SYSTEMTIME structure from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. Raises: ValueError: if the date string is invalid or not supported.
[ "Copies", "a", "SYSTEMTIME", "structure", "from", "a", "date", "and", "time", "string", "." ]
141ca4ef1eff3d354b5deaac3d81cb08506f98d6
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/systemtime.py#L127-L172
train
RyanBalfanz/django-smsish
smsish/sms/backends/locmem.py
SMSBackend.send_messages
def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() msg_count += 1 mail.outbox.extend(messages) return msg_count
python
def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() msg_count += 1 mail.outbox.extend(messages) return msg_count
[ "def", "send_messages", "(", "self", ",", "messages", ")", ":", "msg_count", "=", "0", "for", "message", "in", "messages", ":", "# .message() triggers header validation", "message", ".", "message", "(", ")", "msg_count", "+=", "1", "mail", ".", "outbox", ".", "extend", "(", "messages", ")", "return", "msg_count" ]
Redirect messages to the dummy outbox
[ "Redirect", "messages", "to", "the", "dummy", "outbox" ]
4d450e3d217cea9e373f16c5e4f0beb3218bd5c9
https://github.com/RyanBalfanz/django-smsish/blob/4d450e3d217cea9e373f16c5e4f0beb3218bd5c9/smsish/sms/backends/locmem.py#L20-L27
train
beniwohli/django-cms-search
cms_search/search_helpers/fields.py
MultiLangTemplateField._prepare_template
def _prepare_template(self, obj, needs_request=False): """ This is a copy of CharField.prepare_template, except that it adds a fake request to the context, which is mainly needed to render CMS placeholders """ if self.instance_name is None and self.template_name is None: raise SearchFieldError("This field requires either its instance_name variable to be populated or an explicit template_name in order to load the correct template.") if self.template_name is not None: template_names = self.template_name if not isinstance(template_names, (list, tuple)): template_names = [template_names] else: template_names = ['search/indexes/%s/%s_%s.txt' % (obj._meta.app_label, obj._meta.module_name, self.instance_name)] t = loader.select_template(template_names) ctx = {'object': obj} if needs_request: request = rf.get("/") request.session = {} ctx['request'] = request return t.render(Context(ctx))
python
def _prepare_template(self, obj, needs_request=False): """ This is a copy of CharField.prepare_template, except that it adds a fake request to the context, which is mainly needed to render CMS placeholders """ if self.instance_name is None and self.template_name is None: raise SearchFieldError("This field requires either its instance_name variable to be populated or an explicit template_name in order to load the correct template.") if self.template_name is not None: template_names = self.template_name if not isinstance(template_names, (list, tuple)): template_names = [template_names] else: template_names = ['search/indexes/%s/%s_%s.txt' % (obj._meta.app_label, obj._meta.module_name, self.instance_name)] t = loader.select_template(template_names) ctx = {'object': obj} if needs_request: request = rf.get("/") request.session = {} ctx['request'] = request return t.render(Context(ctx))
[ "def", "_prepare_template", "(", "self", ",", "obj", ",", "needs_request", "=", "False", ")", ":", "if", "self", ".", "instance_name", "is", "None", "and", "self", ".", "template_name", "is", "None", ":", "raise", "SearchFieldError", "(", "\"This field requires either its instance_name variable to be populated or an explicit template_name in order to load the correct template.\"", ")", "if", "self", ".", "template_name", "is", "not", "None", ":", "template_names", "=", "self", ".", "template_name", "if", "not", "isinstance", "(", "template_names", ",", "(", "list", ",", "tuple", ")", ")", ":", "template_names", "=", "[", "template_names", "]", "else", ":", "template_names", "=", "[", "'search/indexes/%s/%s_%s.txt'", "%", "(", "obj", ".", "_meta", ".", "app_label", ",", "obj", ".", "_meta", ".", "module_name", ",", "self", ".", "instance_name", ")", "]", "t", "=", "loader", ".", "select_template", "(", "template_names", ")", "ctx", "=", "{", "'object'", ":", "obj", "}", "if", "needs_request", ":", "request", "=", "rf", ".", "get", "(", "\"/\"", ")", "request", ".", "session", "=", "{", "}", "ctx", "[", "'request'", "]", "=", "request", "return", "t", ".", "render", "(", "Context", "(", "ctx", ")", ")" ]
This is a copy of CharField.prepare_template, except that it adds a fake request to the context, which is mainly needed to render CMS placeholders
[ "This", "is", "a", "copy", "of", "CharField", ".", "prepare_template", "except", "that", "it", "adds", "a", "fake", "request", "to", "the", "context", "which", "is", "mainly", "needed", "to", "render", "CMS", "placeholders" ]
57a1508fabd2285252b8f7e8ff778f2b7c2f3656
https://github.com/beniwohli/django-cms-search/blob/57a1508fabd2285252b8f7e8ff778f2b7c2f3656/cms_search/search_helpers/fields.py#L31-L53
train
beniwohli/django-cms-search
cms_search/search_helpers/templatetags/cms_search_tags.py
GetTransFieldTag.get_value
def get_value(self, context, obj, field_name): """ gets the translated value of field name. If `FALLBACK`evaluates to `True` and the field has no translation for the current language, it tries to find a fallback value, using the languages defined in `settings.LANGUAGES`. """ try: language = get_language() value = self.get_translated_value(obj, field_name, language) if value: return value if self.FALLBACK: for lang, lang_name in settings.LANGUAGES: if lang == language: # already tried this one... continue value = self.get_translated_value(obj, field_name, lang) if value: return value untranslated = getattr(obj, field_name) if self._is_truthy(untranslated): return untranslated else: return self.EMPTY_VALUE except Exception: if settings.TEMPLATE_DEBUG: raise return self.EMPTY_VALUE
python
def get_value(self, context, obj, field_name): """ gets the translated value of field name. If `FALLBACK`evaluates to `True` and the field has no translation for the current language, it tries to find a fallback value, using the languages defined in `settings.LANGUAGES`. """ try: language = get_language() value = self.get_translated_value(obj, field_name, language) if value: return value if self.FALLBACK: for lang, lang_name in settings.LANGUAGES: if lang == language: # already tried this one... continue value = self.get_translated_value(obj, field_name, lang) if value: return value untranslated = getattr(obj, field_name) if self._is_truthy(untranslated): return untranslated else: return self.EMPTY_VALUE except Exception: if settings.TEMPLATE_DEBUG: raise return self.EMPTY_VALUE
[ "def", "get_value", "(", "self", ",", "context", ",", "obj", ",", "field_name", ")", ":", "try", ":", "language", "=", "get_language", "(", ")", "value", "=", "self", ".", "get_translated_value", "(", "obj", ",", "field_name", ",", "language", ")", "if", "value", ":", "return", "value", "if", "self", ".", "FALLBACK", ":", "for", "lang", ",", "lang_name", "in", "settings", ".", "LANGUAGES", ":", "if", "lang", "==", "language", ":", "# already tried this one...", "continue", "value", "=", "self", ".", "get_translated_value", "(", "obj", ",", "field_name", ",", "lang", ")", "if", "value", ":", "return", "value", "untranslated", "=", "getattr", "(", "obj", ",", "field_name", ")", "if", "self", ".", "_is_truthy", "(", "untranslated", ")", ":", "return", "untranslated", "else", ":", "return", "self", ".", "EMPTY_VALUE", "except", "Exception", ":", "if", "settings", ".", "TEMPLATE_DEBUG", ":", "raise", "return", "self", ".", "EMPTY_VALUE" ]
gets the translated value of field name. If `FALLBACK`evaluates to `True` and the field has no translation for the current language, it tries to find a fallback value, using the languages defined in `settings.LANGUAGES`.
[ "gets", "the", "translated", "value", "of", "field", "name", ".", "If", "FALLBACK", "evaluates", "to", "True", "and", "the", "field", "has", "no", "translation", "for", "the", "current", "language", "it", "tries", "to", "find", "a", "fallback", "value", "using", "the", "languages", "defined", "in", "settings", ".", "LANGUAGES", "." ]
57a1508fabd2285252b8f7e8ff778f2b7c2f3656
https://github.com/beniwohli/django-cms-search/blob/57a1508fabd2285252b8f7e8ff778f2b7c2f3656/cms_search/search_helpers/templatetags/cms_search_tags.py#L29-L57
train
ribozz/sphinx-argparse
sphinxarg/markdown.py
customWalker
def customWalker(node, space=''): """ A convenience function to ease debugging. It will print the node structure that's returned from CommonMark The usage would be something like: >>> content = Parser().parse('Some big text block\n===================\n\nwith content\n') >>> customWalker(content) document heading text Some big text block paragraph text with content Spaces are used to convey nesting """ txt = '' try: txt = node.literal except: pass if txt is None or txt == '': print('{}{}'.format(space, node.t)) else: print('{}{}\t{}'.format(space, node.t, txt)) cur = node.first_child if cur: while cur is not None: customWalker(cur, space + ' ') cur = cur.nxt
python
def customWalker(node, space=''): """ A convenience function to ease debugging. It will print the node structure that's returned from CommonMark The usage would be something like: >>> content = Parser().parse('Some big text block\n===================\n\nwith content\n') >>> customWalker(content) document heading text Some big text block paragraph text with content Spaces are used to convey nesting """ txt = '' try: txt = node.literal except: pass if txt is None or txt == '': print('{}{}'.format(space, node.t)) else: print('{}{}\t{}'.format(space, node.t, txt)) cur = node.first_child if cur: while cur is not None: customWalker(cur, space + ' ') cur = cur.nxt
[ "def", "customWalker", "(", "node", ",", "space", "=", "''", ")", ":", "txt", "=", "''", "try", ":", "txt", "=", "node", ".", "literal", "except", ":", "pass", "if", "txt", "is", "None", "or", "txt", "==", "''", ":", "print", "(", "'{}{}'", ".", "format", "(", "space", ",", "node", ".", "t", ")", ")", "else", ":", "print", "(", "'{}{}\\t{}'", ".", "format", "(", "space", ",", "node", ".", "t", ",", "txt", ")", ")", "cur", "=", "node", ".", "first_child", "if", "cur", ":", "while", "cur", "is", "not", "None", ":", "customWalker", "(", "cur", ",", "space", "+", "' '", ")", "cur", "=", "cur", ".", "nxt" ]
A convenience function to ease debugging. It will print the node structure that's returned from CommonMark The usage would be something like: >>> content = Parser().parse('Some big text block\n===================\n\nwith content\n') >>> customWalker(content) document heading text Some big text block paragraph text with content Spaces are used to convey nesting
[ "A", "convenience", "function", "to", "ease", "debugging", ".", "It", "will", "print", "the", "node", "structure", "that", "s", "returned", "from", "CommonMark" ]
178672cd5c846440ff7ecd695e3708feea13e4b4
https://github.com/ribozz/sphinx-argparse/blob/178672cd5c846440ff7ecd695e3708feea13e4b4/sphinxarg/markdown.py#L13-L44
train
ribozz/sphinx-argparse
sphinxarg/markdown.py
paragraph
def paragraph(node): """ Process a paragraph, which includes all content under it """ text = '' if node.string_content is not None: text = node.string_content o = nodes.paragraph('', ' '.join(text)) o.line = node.sourcepos[0][0] for n in MarkDown(node): o.append(n) return o
python
def paragraph(node): """ Process a paragraph, which includes all content under it """ text = '' if node.string_content is not None: text = node.string_content o = nodes.paragraph('', ' '.join(text)) o.line = node.sourcepos[0][0] for n in MarkDown(node): o.append(n) return o
[ "def", "paragraph", "(", "node", ")", ":", "text", "=", "''", "if", "node", ".", "string_content", "is", "not", "None", ":", "text", "=", "node", ".", "string_content", "o", "=", "nodes", ".", "paragraph", "(", "''", ",", "' '", ".", "join", "(", "text", ")", ")", "o", ".", "line", "=", "node", ".", "sourcepos", "[", "0", "]", "[", "0", "]", "for", "n", "in", "MarkDown", "(", "node", ")", ":", "o", ".", "append", "(", "n", ")", "return", "o" ]
Process a paragraph, which includes all content under it
[ "Process", "a", "paragraph", "which", "includes", "all", "content", "under", "it" ]
178672cd5c846440ff7ecd695e3708feea13e4b4
https://github.com/ribozz/sphinx-argparse/blob/178672cd5c846440ff7ecd695e3708feea13e4b4/sphinxarg/markdown.py#L47-L59
train
ribozz/sphinx-argparse
sphinxarg/markdown.py
reference
def reference(node): """ A hyperlink. Note that alt text doesn't work, since there's no apparent way to do that in docutils """ o = nodes.reference() o['refuri'] = node.destination if node.title: o['name'] = node.title for n in MarkDown(node): o += n return o
python
def reference(node): """ A hyperlink. Note that alt text doesn't work, since there's no apparent way to do that in docutils """ o = nodes.reference() o['refuri'] = node.destination if node.title: o['name'] = node.title for n in MarkDown(node): o += n return o
[ "def", "reference", "(", "node", ")", ":", "o", "=", "nodes", ".", "reference", "(", ")", "o", "[", "'refuri'", "]", "=", "node", ".", "destination", "if", "node", ".", "title", ":", "o", "[", "'name'", "]", "=", "node", ".", "title", "for", "n", "in", "MarkDown", "(", "node", ")", ":", "o", "+=", "n", "return", "o" ]
A hyperlink. Note that alt text doesn't work, since there's no apparent way to do that in docutils
[ "A", "hyperlink", ".", "Note", "that", "alt", "text", "doesn", "t", "work", "since", "there", "s", "no", "apparent", "way", "to", "do", "that", "in", "docutils" ]
178672cd5c846440ff7ecd695e3708feea13e4b4
https://github.com/ribozz/sphinx-argparse/blob/178672cd5c846440ff7ecd695e3708feea13e4b4/sphinxarg/markdown.py#L83-L93
train
ribozz/sphinx-argparse
sphinxarg/markdown.py
emphasis
def emphasis(node): """ An italicized section """ o = nodes.emphasis() for n in MarkDown(node): o += n return o
python
def emphasis(node): """ An italicized section """ o = nodes.emphasis() for n in MarkDown(node): o += n return o
[ "def", "emphasis", "(", "node", ")", ":", "o", "=", "nodes", ".", "emphasis", "(", ")", "for", "n", "in", "MarkDown", "(", "node", ")", ":", "o", "+=", "n", "return", "o" ]
An italicized section
[ "An", "italicized", "section" ]
178672cd5c846440ff7ecd695e3708feea13e4b4
https://github.com/ribozz/sphinx-argparse/blob/178672cd5c846440ff7ecd695e3708feea13e4b4/sphinxarg/markdown.py#L96-L103
train
ribozz/sphinx-argparse
sphinxarg/markdown.py
strong
def strong(node): """ A bolded section """ o = nodes.strong() for n in MarkDown(node): o += n return o
python
def strong(node): """ A bolded section """ o = nodes.strong() for n in MarkDown(node): o += n return o
[ "def", "strong", "(", "node", ")", ":", "o", "=", "nodes", ".", "strong", "(", ")", "for", "n", "in", "MarkDown", "(", "node", ")", ":", "o", "+=", "n", "return", "o" ]
A bolded section
[ "A", "bolded", "section" ]
178672cd5c846440ff7ecd695e3708feea13e4b4
https://github.com/ribozz/sphinx-argparse/blob/178672cd5c846440ff7ecd695e3708feea13e4b4/sphinxarg/markdown.py#L106-L113
train
ribozz/sphinx-argparse
sphinxarg/markdown.py
literal
def literal(node): """ Inline code """ rendered = [] try: if node.info is not None: l = Lexer(node.literal, node.info, tokennames="long") for _ in l: rendered.append(node.inline(classes=_[0], text=_[1])) except: pass classes = ['code'] if node.info is not None: classes.append(node.info) if len(rendered) > 0: o = nodes.literal(classes=classes) for element in rendered: o += element else: o = nodes.literal(text=node.literal, classes=classes) for n in MarkDown(node): o += n return o
python
def literal(node): """ Inline code """ rendered = [] try: if node.info is not None: l = Lexer(node.literal, node.info, tokennames="long") for _ in l: rendered.append(node.inline(classes=_[0], text=_[1])) except: pass classes = ['code'] if node.info is not None: classes.append(node.info) if len(rendered) > 0: o = nodes.literal(classes=classes) for element in rendered: o += element else: o = nodes.literal(text=node.literal, classes=classes) for n in MarkDown(node): o += n return o
[ "def", "literal", "(", "node", ")", ":", "rendered", "=", "[", "]", "try", ":", "if", "node", ".", "info", "is", "not", "None", ":", "l", "=", "Lexer", "(", "node", ".", "literal", ",", "node", ".", "info", ",", "tokennames", "=", "\"long\"", ")", "for", "_", "in", "l", ":", "rendered", ".", "append", "(", "node", ".", "inline", "(", "classes", "=", "_", "[", "0", "]", ",", "text", "=", "_", "[", "1", "]", ")", ")", "except", ":", "pass", "classes", "=", "[", "'code'", "]", "if", "node", ".", "info", "is", "not", "None", ":", "classes", ".", "append", "(", "node", ".", "info", ")", "if", "len", "(", "rendered", ")", ">", "0", ":", "o", "=", "nodes", ".", "literal", "(", "classes", "=", "classes", ")", "for", "element", "in", "rendered", ":", "o", "+=", "element", "else", ":", "o", "=", "nodes", ".", "literal", "(", "text", "=", "node", ".", "literal", ",", "classes", "=", "classes", ")", "for", "n", "in", "MarkDown", "(", "node", ")", ":", "o", "+=", "n", "return", "o" ]
Inline code
[ "Inline", "code" ]
178672cd5c846440ff7ecd695e3708feea13e4b4
https://github.com/ribozz/sphinx-argparse/blob/178672cd5c846440ff7ecd695e3708feea13e4b4/sphinxarg/markdown.py#L116-L141
train