repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
markokr/rarfile | dumprar.py | get_file_flags | def get_file_flags(flags):
"""Show flag names and handle dict size.
"""
res = render_flags(flags & ~rf.RAR_FILE_DICTMASK, file_bits)
xf = (flags & rf.RAR_FILE_DICTMASK) >> 5
res += "," + file_parms[xf]
return res | python | def get_file_flags(flags):
"""Show flag names and handle dict size.
"""
res = render_flags(flags & ~rf.RAR_FILE_DICTMASK, file_bits)
xf = (flags & rf.RAR_FILE_DICTMASK) >> 5
res += "," + file_parms[xf]
return res | [
"def",
"get_file_flags",
"(",
"flags",
")",
":",
"res",
"=",
"render_flags",
"(",
"flags",
"&",
"~",
"rf",
".",
"RAR_FILE_DICTMASK",
",",
"file_bits",
")",
"xf",
"=",
"(",
"flags",
"&",
"rf",
".",
"RAR_FILE_DICTMASK",
")",
">>",
"5",
"res",
"+=",
"\",\... | Show flag names and handle dict size. | [
"Show",
"flag",
"names",
"and",
"handle",
"dict",
"size",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/dumprar.py#L192-L199 | train | 33,100 |
markokr/rarfile | dumprar.py | show_item_v3 | def show_item_v3(h):
"""Show any RAR3 record.
"""
st = rar3_type(h.type)
xprint("%s: hdrlen=%d datlen=%d", st, h.header_size, h.add_size)
if h.type in (rf.RAR_BLOCK_FILE, rf.RAR_BLOCK_SUB):
if h.host_os == rf.RAR_OS_UNIX:
s_mode = "0%o" % h.mode
else:
s_mode = "0x%x" % h.mode
xprint(" flags=0x%04x:%s", h.flags, get_file_flags(h.flags))
if h.host_os >= 0 and h.host_os < len(os_list):
s_os = os_list[h.host_os]
else:
s_os = "?"
xprint(" os=%d:%s ver=%d mode=%s meth=%c cmp=%d dec=%d vol=%d",
h.host_os, s_os,
h.extract_version, s_mode, h.compress_type,
h.compress_size, h.file_size, h.volume)
ucrc = (h.CRC + (1 << 32)) & ((1 << 32) - 1)
xprint(" crc=0x%08x (%d) date_time=%s", ucrc, h.CRC, fmt_time(h.date_time))
xprint(" name=%s", h.filename)
if h.mtime:
xprint(" mtime=%s", fmt_time(h.mtime))
if h.ctime:
xprint(" ctime=%s", fmt_time(h.ctime))
if h.atime:
xprint(" atime=%s", fmt_time(h.atime))
if h.arctime:
xprint(" arctime=%s", fmt_time(h.arctime))
elif h.type == rf.RAR_BLOCK_MAIN:
xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, main_bits))
elif h.type == rf.RAR_BLOCK_ENDARC:
xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, endarc_bits))
elif h.type == rf.RAR_BLOCK_MARK:
xprint(" flags=0x%04x:", h.flags)
else:
xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, generic_bits))
if h.comment is not None:
cm = repr(h.comment)
if cm[0] == 'u':
cm = cm[1:]
xprint(" comment=%s", cm) | python | def show_item_v3(h):
"""Show any RAR3 record.
"""
st = rar3_type(h.type)
xprint("%s: hdrlen=%d datlen=%d", st, h.header_size, h.add_size)
if h.type in (rf.RAR_BLOCK_FILE, rf.RAR_BLOCK_SUB):
if h.host_os == rf.RAR_OS_UNIX:
s_mode = "0%o" % h.mode
else:
s_mode = "0x%x" % h.mode
xprint(" flags=0x%04x:%s", h.flags, get_file_flags(h.flags))
if h.host_os >= 0 and h.host_os < len(os_list):
s_os = os_list[h.host_os]
else:
s_os = "?"
xprint(" os=%d:%s ver=%d mode=%s meth=%c cmp=%d dec=%d vol=%d",
h.host_os, s_os,
h.extract_version, s_mode, h.compress_type,
h.compress_size, h.file_size, h.volume)
ucrc = (h.CRC + (1 << 32)) & ((1 << 32) - 1)
xprint(" crc=0x%08x (%d) date_time=%s", ucrc, h.CRC, fmt_time(h.date_time))
xprint(" name=%s", h.filename)
if h.mtime:
xprint(" mtime=%s", fmt_time(h.mtime))
if h.ctime:
xprint(" ctime=%s", fmt_time(h.ctime))
if h.atime:
xprint(" atime=%s", fmt_time(h.atime))
if h.arctime:
xprint(" arctime=%s", fmt_time(h.arctime))
elif h.type == rf.RAR_BLOCK_MAIN:
xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, main_bits))
elif h.type == rf.RAR_BLOCK_ENDARC:
xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, endarc_bits))
elif h.type == rf.RAR_BLOCK_MARK:
xprint(" flags=0x%04x:", h.flags)
else:
xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, generic_bits))
if h.comment is not None:
cm = repr(h.comment)
if cm[0] == 'u':
cm = cm[1:]
xprint(" comment=%s", cm) | [
"def",
"show_item_v3",
"(",
"h",
")",
":",
"st",
"=",
"rar3_type",
"(",
"h",
".",
"type",
")",
"xprint",
"(",
"\"%s: hdrlen=%d datlen=%d\"",
",",
"st",
",",
"h",
".",
"header_size",
",",
"h",
".",
"add_size",
")",
"if",
"h",
".",
"type",
"in",
"(",
... | Show any RAR3 record. | [
"Show",
"any",
"RAR3",
"record",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/dumprar.py#L223-L266 | train | 33,101 |
markokr/rarfile | dumprar.py | check_crc | def check_crc(f, inf, desc):
"""Compare result crc to expected value.
"""
exp = inf._md_expect
if exp is None:
return
ucrc = f._md_context.digest()
if ucrc != exp:
print('crc error - %s - exp=%r got=%r' % (desc, exp, ucrc)) | python | def check_crc(f, inf, desc):
"""Compare result crc to expected value.
"""
exp = inf._md_expect
if exp is None:
return
ucrc = f._md_context.digest()
if ucrc != exp:
print('crc error - %s - exp=%r got=%r' % (desc, exp, ucrc)) | [
"def",
"check_crc",
"(",
"f",
",",
"inf",
",",
"desc",
")",
":",
"exp",
"=",
"inf",
".",
"_md_expect",
"if",
"exp",
"is",
"None",
":",
"return",
"ucrc",
"=",
"f",
".",
"_md_context",
".",
"digest",
"(",
")",
"if",
"ucrc",
"!=",
"exp",
":",
"print... | Compare result crc to expected value. | [
"Compare",
"result",
"crc",
"to",
"expected",
"value",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/dumprar.py#L358-L366 | train | 33,102 |
markokr/rarfile | rarfile.py | load_vint | def load_vint(buf, pos):
"""Load variable-size int."""
limit = min(pos + 11, len(buf))
res = ofs = 0
while pos < limit:
b = _byte_code(buf[pos])
res += ((b & 0x7F) << ofs)
pos += 1
ofs += 7
if b < 0x80:
return res, pos
raise BadRarFile('cannot load vint') | python | def load_vint(buf, pos):
"""Load variable-size int."""
limit = min(pos + 11, len(buf))
res = ofs = 0
while pos < limit:
b = _byte_code(buf[pos])
res += ((b & 0x7F) << ofs)
pos += 1
ofs += 7
if b < 0x80:
return res, pos
raise BadRarFile('cannot load vint') | [
"def",
"load_vint",
"(",
"buf",
",",
"pos",
")",
":",
"limit",
"=",
"min",
"(",
"pos",
"+",
"11",
",",
"len",
"(",
"buf",
")",
")",
"res",
"=",
"ofs",
"=",
"0",
"while",
"pos",
"<",
"limit",
":",
"b",
"=",
"_byte_code",
"(",
"buf",
"[",
"pos"... | Load variable-size int. | [
"Load",
"variable",
"-",
"size",
"int",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2596-L2607 | train | 33,103 |
markokr/rarfile | rarfile.py | load_byte | def load_byte(buf, pos):
"""Load single byte"""
end = pos + 1
if end > len(buf):
raise BadRarFile('cannot load byte')
return S_BYTE.unpack_from(buf, pos)[0], end | python | def load_byte(buf, pos):
"""Load single byte"""
end = pos + 1
if end > len(buf):
raise BadRarFile('cannot load byte')
return S_BYTE.unpack_from(buf, pos)[0], end | [
"def",
"load_byte",
"(",
"buf",
",",
"pos",
")",
":",
"end",
"=",
"pos",
"+",
"1",
"if",
"end",
">",
"len",
"(",
"buf",
")",
":",
"raise",
"BadRarFile",
"(",
"'cannot load byte'",
")",
"return",
"S_BYTE",
".",
"unpack_from",
"(",
"buf",
",",
"pos",
... | Load single byte | [
"Load",
"single",
"byte"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2609-L2614 | train | 33,104 |
markokr/rarfile | rarfile.py | load_le32 | def load_le32(buf, pos):
"""Load little-endian 32-bit integer"""
end = pos + 4
if end > len(buf):
raise BadRarFile('cannot load le32')
return S_LONG.unpack_from(buf, pos)[0], pos + 4 | python | def load_le32(buf, pos):
"""Load little-endian 32-bit integer"""
end = pos + 4
if end > len(buf):
raise BadRarFile('cannot load le32')
return S_LONG.unpack_from(buf, pos)[0], pos + 4 | [
"def",
"load_le32",
"(",
"buf",
",",
"pos",
")",
":",
"end",
"=",
"pos",
"+",
"4",
"if",
"end",
">",
"len",
"(",
"buf",
")",
":",
"raise",
"BadRarFile",
"(",
"'cannot load le32'",
")",
"return",
"S_LONG",
".",
"unpack_from",
"(",
"buf",
",",
"pos",
... | Load little-endian 32-bit integer | [
"Load",
"little",
"-",
"endian",
"32",
"-",
"bit",
"integer"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2616-L2621 | train | 33,105 |
markokr/rarfile | rarfile.py | load_bytes | def load_bytes(buf, num, pos):
"""Load sequence of bytes"""
end = pos + num
if end > len(buf):
raise BadRarFile('cannot load bytes')
return buf[pos : end], end | python | def load_bytes(buf, num, pos):
"""Load sequence of bytes"""
end = pos + num
if end > len(buf):
raise BadRarFile('cannot load bytes')
return buf[pos : end], end | [
"def",
"load_bytes",
"(",
"buf",
",",
"num",
",",
"pos",
")",
":",
"end",
"=",
"pos",
"+",
"num",
"if",
"end",
">",
"len",
"(",
"buf",
")",
":",
"raise",
"BadRarFile",
"(",
"'cannot load bytes'",
")",
"return",
"buf",
"[",
"pos",
":",
"end",
"]",
... | Load sequence of bytes | [
"Load",
"sequence",
"of",
"bytes"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2623-L2628 | train | 33,106 |
markokr/rarfile | rarfile.py | load_vstr | def load_vstr(buf, pos):
"""Load bytes prefixed by vint length"""
slen, pos = load_vint(buf, pos)
return load_bytes(buf, slen, pos) | python | def load_vstr(buf, pos):
"""Load bytes prefixed by vint length"""
slen, pos = load_vint(buf, pos)
return load_bytes(buf, slen, pos) | [
"def",
"load_vstr",
"(",
"buf",
",",
"pos",
")",
":",
"slen",
",",
"pos",
"=",
"load_vint",
"(",
"buf",
",",
"pos",
")",
"return",
"load_bytes",
"(",
"buf",
",",
"slen",
",",
"pos",
")"
] | Load bytes prefixed by vint length | [
"Load",
"bytes",
"prefixed",
"by",
"vint",
"length"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2630-L2633 | train | 33,107 |
markokr/rarfile | rarfile.py | load_dostime | def load_dostime(buf, pos):
"""Load LE32 dos timestamp"""
stamp, pos = load_le32(buf, pos)
tup = parse_dos_time(stamp)
return to_datetime(tup), pos | python | def load_dostime(buf, pos):
"""Load LE32 dos timestamp"""
stamp, pos = load_le32(buf, pos)
tup = parse_dos_time(stamp)
return to_datetime(tup), pos | [
"def",
"load_dostime",
"(",
"buf",
",",
"pos",
")",
":",
"stamp",
",",
"pos",
"=",
"load_le32",
"(",
"buf",
",",
"pos",
")",
"tup",
"=",
"parse_dos_time",
"(",
"stamp",
")",
"return",
"to_datetime",
"(",
"tup",
")",
",",
"pos"
] | Load LE32 dos timestamp | [
"Load",
"LE32",
"dos",
"timestamp"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2635-L2639 | train | 33,108 |
markokr/rarfile | rarfile.py | load_unixtime | def load_unixtime(buf, pos):
"""Load LE32 unix timestamp"""
secs, pos = load_le32(buf, pos)
dt = datetime.fromtimestamp(secs, UTC)
return dt, pos | python | def load_unixtime(buf, pos):
"""Load LE32 unix timestamp"""
secs, pos = load_le32(buf, pos)
dt = datetime.fromtimestamp(secs, UTC)
return dt, pos | [
"def",
"load_unixtime",
"(",
"buf",
",",
"pos",
")",
":",
"secs",
",",
"pos",
"=",
"load_le32",
"(",
"buf",
",",
"pos",
")",
"dt",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"secs",
",",
"UTC",
")",
"return",
"dt",
",",
"pos"
] | Load LE32 unix timestamp | [
"Load",
"LE32",
"unix",
"timestamp"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2641-L2645 | train | 33,109 |
markokr/rarfile | rarfile.py | load_windowstime | def load_windowstime(buf, pos):
"""Load LE64 windows timestamp"""
# unix epoch (1970) in seconds from windows epoch (1601)
unix_epoch = 11644473600
val1, pos = load_le32(buf, pos)
val2, pos = load_le32(buf, pos)
secs, n1secs = divmod((val2 << 32) | val1, 10000000)
dt = datetime.fromtimestamp(secs - unix_epoch, UTC)
dt = dt.replace(microsecond=n1secs // 10)
return dt, pos | python | def load_windowstime(buf, pos):
"""Load LE64 windows timestamp"""
# unix epoch (1970) in seconds from windows epoch (1601)
unix_epoch = 11644473600
val1, pos = load_le32(buf, pos)
val2, pos = load_le32(buf, pos)
secs, n1secs = divmod((val2 << 32) | val1, 10000000)
dt = datetime.fromtimestamp(secs - unix_epoch, UTC)
dt = dt.replace(microsecond=n1secs // 10)
return dt, pos | [
"def",
"load_windowstime",
"(",
"buf",
",",
"pos",
")",
":",
"# unix epoch (1970) in seconds from windows epoch (1601)",
"unix_epoch",
"=",
"11644473600",
"val1",
",",
"pos",
"=",
"load_le32",
"(",
"buf",
",",
"pos",
")",
"val2",
",",
"pos",
"=",
"load_le32",
"(... | Load LE64 windows timestamp | [
"Load",
"LE64",
"windows",
"timestamp"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2647-L2656 | train | 33,110 |
markokr/rarfile | rarfile.py | is_filelike | def is_filelike(obj):
"""Filename or file object?
"""
if isinstance(obj, (bytes, unicode)):
return False
res = True
for a in ('read', 'tell', 'seek'):
res = res and hasattr(obj, a)
if not res:
raise ValueError("Invalid object passed as file")
return True | python | def is_filelike(obj):
"""Filename or file object?
"""
if isinstance(obj, (bytes, unicode)):
return False
res = True
for a in ('read', 'tell', 'seek'):
res = res and hasattr(obj, a)
if not res:
raise ValueError("Invalid object passed as file")
return True | [
"def",
"is_filelike",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"bytes",
",",
"unicode",
")",
")",
":",
"return",
"False",
"res",
"=",
"True",
"for",
"a",
"in",
"(",
"'read'",
",",
"'tell'",
",",
"'seek'",
")",
":",
"res",
"... | Filename or file object? | [
"Filename",
"or",
"file",
"object?"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2728-L2738 | train | 33,111 |
markokr/rarfile | rarfile.py | rar3_s2k | def rar3_s2k(psw, salt):
"""String-to-key hash for RAR3.
"""
if not isinstance(psw, unicode):
psw = psw.decode('utf8')
seed = bytearray(psw.encode('utf-16le') + salt)
h = Rar3Sha1(rarbug=True)
iv = EMPTY
for i in range(16):
for j in range(0x4000):
cnt = S_LONG.pack(i * 0x4000 + j)
h.update(seed)
h.update(cnt[:3])
if j == 0:
iv += h.digest()[19:20]
key_be = h.digest()[:16]
key_le = pack("<LLLL", *unpack(">LLLL", key_be))
return key_le, iv | python | def rar3_s2k(psw, salt):
"""String-to-key hash for RAR3.
"""
if not isinstance(psw, unicode):
psw = psw.decode('utf8')
seed = bytearray(psw.encode('utf-16le') + salt)
h = Rar3Sha1(rarbug=True)
iv = EMPTY
for i in range(16):
for j in range(0x4000):
cnt = S_LONG.pack(i * 0x4000 + j)
h.update(seed)
h.update(cnt[:3])
if j == 0:
iv += h.digest()[19:20]
key_be = h.digest()[:16]
key_le = pack("<LLLL", *unpack(">LLLL", key_be))
return key_le, iv | [
"def",
"rar3_s2k",
"(",
"psw",
",",
"salt",
")",
":",
"if",
"not",
"isinstance",
"(",
"psw",
",",
"unicode",
")",
":",
"psw",
"=",
"psw",
".",
"decode",
"(",
"'utf8'",
")",
"seed",
"=",
"bytearray",
"(",
"psw",
".",
"encode",
"(",
"'utf-16le'",
")"... | String-to-key hash for RAR3. | [
"String",
"-",
"to",
"-",
"key",
"hash",
"for",
"RAR3",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2740-L2757 | train | 33,112 |
markokr/rarfile | rarfile.py | rar3_decompress | def rar3_decompress(vers, meth, data, declen=0, flags=0, crc=0, psw=None, salt=None):
"""Decompress blob of compressed data.
Used for data with non-standard header - eg. comments.
"""
# already uncompressed?
if meth == RAR_M0 and (flags & RAR_FILE_PASSWORD) == 0:
return data
# take only necessary flags
flags = flags & (RAR_FILE_PASSWORD | RAR_FILE_SALT | RAR_FILE_DICTMASK)
flags |= RAR_LONG_BLOCK
# file header
fname = b'data'
date = 0
mode = 0x20
fhdr = S_FILE_HDR.pack(len(data), declen, RAR_OS_MSDOS, crc,
date, vers, meth, len(fname), mode)
fhdr += fname
if flags & RAR_FILE_SALT:
if not salt:
return EMPTY
fhdr += salt
# full header
hlen = S_BLK_HDR.size + len(fhdr)
hdr = S_BLK_HDR.pack(0, RAR_BLOCK_FILE, flags, hlen) + fhdr
hcrc = rar_crc32(hdr[2:]) & 0xFFFF
hdr = S_BLK_HDR.pack(hcrc, RAR_BLOCK_FILE, flags, hlen) + fhdr
# archive main header
mh = S_BLK_HDR.pack(0x90CF, RAR_BLOCK_MAIN, 0, 13) + ZERO * (2 + 4)
# decompress via temp rar
tmpfd, tmpname = mkstemp(suffix='.rar')
tmpf = os.fdopen(tmpfd, "wb")
try:
tmpf.write(RAR_ID + mh + hdr + data)
tmpf.close()
cmd = [UNRAR_TOOL] + list(OPEN_ARGS)
add_password_arg(cmd, psw, (flags & RAR_FILE_PASSWORD))
cmd.append(tmpname)
p = custom_popen(cmd)
return p.communicate()[0]
finally:
tmpf.close()
os.unlink(tmpname) | python | def rar3_decompress(vers, meth, data, declen=0, flags=0, crc=0, psw=None, salt=None):
"""Decompress blob of compressed data.
Used for data with non-standard header - eg. comments.
"""
# already uncompressed?
if meth == RAR_M0 and (flags & RAR_FILE_PASSWORD) == 0:
return data
# take only necessary flags
flags = flags & (RAR_FILE_PASSWORD | RAR_FILE_SALT | RAR_FILE_DICTMASK)
flags |= RAR_LONG_BLOCK
# file header
fname = b'data'
date = 0
mode = 0x20
fhdr = S_FILE_HDR.pack(len(data), declen, RAR_OS_MSDOS, crc,
date, vers, meth, len(fname), mode)
fhdr += fname
if flags & RAR_FILE_SALT:
if not salt:
return EMPTY
fhdr += salt
# full header
hlen = S_BLK_HDR.size + len(fhdr)
hdr = S_BLK_HDR.pack(0, RAR_BLOCK_FILE, flags, hlen) + fhdr
hcrc = rar_crc32(hdr[2:]) & 0xFFFF
hdr = S_BLK_HDR.pack(hcrc, RAR_BLOCK_FILE, flags, hlen) + fhdr
# archive main header
mh = S_BLK_HDR.pack(0x90CF, RAR_BLOCK_MAIN, 0, 13) + ZERO * (2 + 4)
# decompress via temp rar
tmpfd, tmpname = mkstemp(suffix='.rar')
tmpf = os.fdopen(tmpfd, "wb")
try:
tmpf.write(RAR_ID + mh + hdr + data)
tmpf.close()
cmd = [UNRAR_TOOL] + list(OPEN_ARGS)
add_password_arg(cmd, psw, (flags & RAR_FILE_PASSWORD))
cmd.append(tmpname)
p = custom_popen(cmd)
return p.communicate()[0]
finally:
tmpf.close()
os.unlink(tmpname) | [
"def",
"rar3_decompress",
"(",
"vers",
",",
"meth",
",",
"data",
",",
"declen",
"=",
"0",
",",
"flags",
"=",
"0",
",",
"crc",
"=",
"0",
",",
"psw",
"=",
"None",
",",
"salt",
"=",
"None",
")",
":",
"# already uncompressed?",
"if",
"meth",
"==",
"RAR... | Decompress blob of compressed data.
Used for data with non-standard header - eg. comments. | [
"Decompress",
"blob",
"of",
"compressed",
"data",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2759-L2808 | train | 33,113 |
markokr/rarfile | rarfile.py | to_datetime | def to_datetime(t):
"""Convert 6-part time tuple into datetime object.
"""
if t is None:
return None
# extract values
year, mon, day, h, m, s = t
# assume the values are valid
try:
return datetime(year, mon, day, h, m, s)
except ValueError:
pass
# sanitize invalid values
mday = (0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
if mon < 1:
mon = 1
if mon > 12:
mon = 12
if day < 1:
day = 1
if day > mday[mon]:
day = mday[mon]
if h > 23:
h = 23
if m > 59:
m = 59
if s > 59:
s = 59
if mon == 2 and day == 29:
try:
return datetime(year, mon, day, h, m, s)
except ValueError:
day = 28
return datetime(year, mon, day, h, m, s) | python | def to_datetime(t):
"""Convert 6-part time tuple into datetime object.
"""
if t is None:
return None
# extract values
year, mon, day, h, m, s = t
# assume the values are valid
try:
return datetime(year, mon, day, h, m, s)
except ValueError:
pass
# sanitize invalid values
mday = (0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
if mon < 1:
mon = 1
if mon > 12:
mon = 12
if day < 1:
day = 1
if day > mday[mon]:
day = mday[mon]
if h > 23:
h = 23
if m > 59:
m = 59
if s > 59:
s = 59
if mon == 2 and day == 29:
try:
return datetime(year, mon, day, h, m, s)
except ValueError:
day = 28
return datetime(year, mon, day, h, m, s) | [
"def",
"to_datetime",
"(",
"t",
")",
":",
"if",
"t",
"is",
"None",
":",
"return",
"None",
"# extract values",
"year",
",",
"mon",
",",
"day",
",",
"h",
",",
"m",
",",
"s",
"=",
"t",
"# assume the values are valid",
"try",
":",
"return",
"datetime",
"("... | Convert 6-part time tuple into datetime object. | [
"Convert",
"6",
"-",
"part",
"time",
"tuple",
"into",
"datetime",
"object",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2810-L2846 | train | 33,114 |
markokr/rarfile | rarfile.py | parse_dos_time | def parse_dos_time(stamp):
"""Parse standard 32-bit DOS timestamp.
"""
sec, stamp = stamp & 0x1F, stamp >> 5
mn, stamp = stamp & 0x3F, stamp >> 6
hr, stamp = stamp & 0x1F, stamp >> 5
day, stamp = stamp & 0x1F, stamp >> 5
mon, stamp = stamp & 0x0F, stamp >> 4
yr = (stamp & 0x7F) + 1980
return (yr, mon, day, hr, mn, sec * 2) | python | def parse_dos_time(stamp):
"""Parse standard 32-bit DOS timestamp.
"""
sec, stamp = stamp & 0x1F, stamp >> 5
mn, stamp = stamp & 0x3F, stamp >> 6
hr, stamp = stamp & 0x1F, stamp >> 5
day, stamp = stamp & 0x1F, stamp >> 5
mon, stamp = stamp & 0x0F, stamp >> 4
yr = (stamp & 0x7F) + 1980
return (yr, mon, day, hr, mn, sec * 2) | [
"def",
"parse_dos_time",
"(",
"stamp",
")",
":",
"sec",
",",
"stamp",
"=",
"stamp",
"&",
"0x1F",
",",
"stamp",
">>",
"5",
"mn",
",",
"stamp",
"=",
"stamp",
"&",
"0x3F",
",",
"stamp",
">>",
"6",
"hr",
",",
"stamp",
"=",
"stamp",
"&",
"0x1F",
",",
... | Parse standard 32-bit DOS timestamp. | [
"Parse",
"standard",
"32",
"-",
"bit",
"DOS",
"timestamp",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2848-L2857 | train | 33,115 |
markokr/rarfile | rarfile.py | custom_popen | def custom_popen(cmd):
"""Disconnect cmd from parent fds, read only from stdout.
"""
# needed for py2exe
creationflags = 0
if sys.platform == 'win32':
creationflags = 0x08000000 # CREATE_NO_WINDOW
# run command
try:
p = Popen(cmd, bufsize=0, stdout=PIPE, stdin=PIPE, stderr=STDOUT,
creationflags=creationflags)
except OSError as ex:
if ex.errno == errno.ENOENT:
raise RarCannotExec("Unrar not installed? (rarfile.UNRAR_TOOL=%r)" % UNRAR_TOOL)
if ex.errno == errno.EACCES or ex.errno == errno.EPERM:
raise RarCannotExec("Cannot execute unrar (rarfile.UNRAR_TOOL=%r)" % UNRAR_TOOL)
raise
return p | python | def custom_popen(cmd):
"""Disconnect cmd from parent fds, read only from stdout.
"""
# needed for py2exe
creationflags = 0
if sys.platform == 'win32':
creationflags = 0x08000000 # CREATE_NO_WINDOW
# run command
try:
p = Popen(cmd, bufsize=0, stdout=PIPE, stdin=PIPE, stderr=STDOUT,
creationflags=creationflags)
except OSError as ex:
if ex.errno == errno.ENOENT:
raise RarCannotExec("Unrar not installed? (rarfile.UNRAR_TOOL=%r)" % UNRAR_TOOL)
if ex.errno == errno.EACCES or ex.errno == errno.EPERM:
raise RarCannotExec("Cannot execute unrar (rarfile.UNRAR_TOOL=%r)" % UNRAR_TOOL)
raise
return p | [
"def",
"custom_popen",
"(",
"cmd",
")",
":",
"# needed for py2exe",
"creationflags",
"=",
"0",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"creationflags",
"=",
"0x08000000",
"# CREATE_NO_WINDOW",
"# run command",
"try",
":",
"p",
"=",
"Popen",
"(",
"c... | Disconnect cmd from parent fds, read only from stdout. | [
"Disconnect",
"cmd",
"from",
"parent",
"fds",
"read",
"only",
"from",
"stdout",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2859-L2877 | train | 33,116 |
markokr/rarfile | rarfile.py | custom_check | def custom_check(cmd, ignore_retcode=False):
"""Run command, collect output, raise error if needed.
"""
p = custom_popen(cmd)
out, _ = p.communicate()
if p.returncode and not ignore_retcode:
raise RarExecError("Check-run failed")
return out | python | def custom_check(cmd, ignore_retcode=False):
"""Run command, collect output, raise error if needed.
"""
p = custom_popen(cmd)
out, _ = p.communicate()
if p.returncode and not ignore_retcode:
raise RarExecError("Check-run failed")
return out | [
"def",
"custom_check",
"(",
"cmd",
",",
"ignore_retcode",
"=",
"False",
")",
":",
"p",
"=",
"custom_popen",
"(",
"cmd",
")",
"out",
",",
"_",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
"and",
"not",
"ignore_retcode",
":",
"... | Run command, collect output, raise error if needed. | [
"Run",
"command",
"collect",
"output",
"raise",
"error",
"if",
"needed",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2879-L2886 | train | 33,117 |
markokr/rarfile | rarfile.py | check_returncode | def check_returncode(p, out):
"""Raise exception according to unrar exit code.
"""
code = p.returncode
if code == 0:
return
# map return code to exception class, codes from rar.txt
errmap = [None,
RarWarning, RarFatalError, RarCRCError, RarLockedArchiveError, # 1..4
RarWriteError, RarOpenError, RarUserError, RarMemoryError, # 5..8
RarCreateError, RarNoFilesError, RarWrongPassword] # 9..11
if UNRAR_TOOL == ALT_TOOL:
errmap = [None]
if code > 0 and code < len(errmap):
exc = errmap[code]
elif code == 255:
exc = RarUserBreak
elif code < 0:
exc = RarSignalExit
else:
exc = RarUnknownError
# format message
if out:
msg = "%s [%d]: %s" % (exc.__doc__, p.returncode, out)
else:
msg = "%s [%d]" % (exc.__doc__, p.returncode)
raise exc(msg) | python | def check_returncode(p, out):
"""Raise exception according to unrar exit code.
"""
code = p.returncode
if code == 0:
return
# map return code to exception class, codes from rar.txt
errmap = [None,
RarWarning, RarFatalError, RarCRCError, RarLockedArchiveError, # 1..4
RarWriteError, RarOpenError, RarUserError, RarMemoryError, # 5..8
RarCreateError, RarNoFilesError, RarWrongPassword] # 9..11
if UNRAR_TOOL == ALT_TOOL:
errmap = [None]
if code > 0 and code < len(errmap):
exc = errmap[code]
elif code == 255:
exc = RarUserBreak
elif code < 0:
exc = RarSignalExit
else:
exc = RarUnknownError
# format message
if out:
msg = "%s [%d]: %s" % (exc.__doc__, p.returncode, out)
else:
msg = "%s [%d]" % (exc.__doc__, p.returncode)
raise exc(msg) | [
"def",
"check_returncode",
"(",
"p",
",",
"out",
")",
":",
"code",
"=",
"p",
".",
"returncode",
"if",
"code",
"==",
"0",
":",
"return",
"# map return code to exception class, codes from rar.txt",
"errmap",
"=",
"[",
"None",
",",
"RarWarning",
",",
"RarFatalError... | Raise exception according to unrar exit code. | [
"Raise",
"exception",
"according",
"to",
"unrar",
"exit",
"code",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2898-L2927 | train | 33,118 |
markokr/rarfile | rarfile.py | membuf_tempfile | def membuf_tempfile(memfile):
"""Write in-memory file object to real file."""
memfile.seek(0, 0)
tmpfd, tmpname = mkstemp(suffix='.rar')
tmpf = os.fdopen(tmpfd, "wb")
try:
while True:
buf = memfile.read(BSIZE)
if not buf:
break
tmpf.write(buf)
tmpf.close()
except:
tmpf.close()
os.unlink(tmpname)
raise
return tmpname | python | def membuf_tempfile(memfile):
"""Write in-memory file object to real file."""
memfile.seek(0, 0)
tmpfd, tmpname = mkstemp(suffix='.rar')
tmpf = os.fdopen(tmpfd, "wb")
try:
while True:
buf = memfile.read(BSIZE)
if not buf:
break
tmpf.write(buf)
tmpf.close()
except:
tmpf.close()
os.unlink(tmpname)
raise
return tmpname | [
"def",
"membuf_tempfile",
"(",
"memfile",
")",
":",
"memfile",
".",
"seek",
"(",
"0",
",",
"0",
")",
"tmpfd",
",",
"tmpname",
"=",
"mkstemp",
"(",
"suffix",
"=",
"'.rar'",
")",
"tmpf",
"=",
"os",
".",
"fdopen",
"(",
"tmpfd",
",",
"\"wb\"",
")",
"tr... | Write in-memory file object to real file. | [
"Write",
"in",
"-",
"memory",
"file",
"object",
"to",
"real",
"file",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2933-L2951 | train | 33,119 |
markokr/rarfile | rarfile.py | RarInfo.isdir | def isdir(self):
"""Returns True if entry is a directory.
"""
if self.type == RAR_BLOCK_FILE:
return (self.flags & RAR_FILE_DIRECTORY) == RAR_FILE_DIRECTORY
return False | python | def isdir(self):
"""Returns True if entry is a directory.
"""
if self.type == RAR_BLOCK_FILE:
return (self.flags & RAR_FILE_DIRECTORY) == RAR_FILE_DIRECTORY
return False | [
"def",
"isdir",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"==",
"RAR_BLOCK_FILE",
":",
"return",
"(",
"self",
".",
"flags",
"&",
"RAR_FILE_DIRECTORY",
")",
"==",
"RAR_FILE_DIRECTORY",
"return",
"False"
] | Returns True if entry is a directory. | [
"Returns",
"True",
"if",
"entry",
"is",
"a",
"directory",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L616-L621 | train | 33,120 |
markokr/rarfile | rarfile.py | RarFile.setpassword | def setpassword(self, password):
"""Sets the password to use when extracting.
"""
self._password = password
if self._file_parser:
if self._file_parser.has_header_encryption():
self._file_parser = None
if not self._file_parser:
self._parse()
else:
self._file_parser.setpassword(self._password) | python | def setpassword(self, password):
"""Sets the password to use when extracting.
"""
self._password = password
if self._file_parser:
if self._file_parser.has_header_encryption():
self._file_parser = None
if not self._file_parser:
self._parse()
else:
self._file_parser.setpassword(self._password) | [
"def",
"setpassword",
"(",
"self",
",",
"password",
")",
":",
"self",
".",
"_password",
"=",
"password",
"if",
"self",
".",
"_file_parser",
":",
"if",
"self",
".",
"_file_parser",
".",
"has_header_encryption",
"(",
")",
":",
"self",
".",
"_file_parser",
"=... | Sets the password to use when extracting. | [
"Sets",
"the",
"password",
"to",
"use",
"when",
"extracting",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L685-L695 | train | 33,121 |
markokr/rarfile | rarfile.py | RarFile.read | def read(self, fname, psw=None):
"""Return uncompressed data for archive entry.
For longer files using :meth:`RarFile.open` may be better idea.
Parameters:
fname
filename or RarInfo instance
psw
password to use for extracting.
"""
with self.open(fname, 'r', psw) as f:
return f.read() | python | def read(self, fname, psw=None):
"""Return uncompressed data for archive entry.
For longer files using :meth:`RarFile.open` may be better idea.
Parameters:
fname
filename or RarInfo instance
psw
password to use for extracting.
"""
with self.open(fname, 'r', psw) as f:
return f.read() | [
"def",
"read",
"(",
"self",
",",
"fname",
",",
"psw",
"=",
"None",
")",
":",
"with",
"self",
".",
"open",
"(",
"fname",
",",
"'r'",
",",
"psw",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | Return uncompressed data for archive entry.
For longer files using :meth:`RarFile.open` may be better idea.
Parameters:
fname
filename or RarInfo instance
psw
password to use for extracting. | [
"Return",
"uncompressed",
"data",
"for",
"archive",
"entry",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L767-L781 | train | 33,122 |
markokr/rarfile | rarfile.py | RarFile.extract | def extract(self, member, path=None, pwd=None):
"""Extract single file into current directory.
Parameters:
member
filename or :class:`RarInfo` instance
path
optional destination path
pwd
optional password to use
"""
if isinstance(member, RarInfo):
fname = member.filename
else:
fname = member
self._extract([fname], path, pwd) | python | def extract(self, member, path=None, pwd=None):
"""Extract single file into current directory.
Parameters:
member
filename or :class:`RarInfo` instance
path
optional destination path
pwd
optional password to use
"""
if isinstance(member, RarInfo):
fname = member.filename
else:
fname = member
self._extract([fname], path, pwd) | [
"def",
"extract",
"(",
"self",
",",
"member",
",",
"path",
"=",
"None",
",",
"pwd",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"member",
",",
"RarInfo",
")",
":",
"fname",
"=",
"member",
".",
"filename",
"else",
":",
"fname",
"=",
"member",
"s... | Extract single file into current directory.
Parameters:
member
filename or :class:`RarInfo` instance
path
optional destination path
pwd
optional password to use | [
"Extract",
"single",
"file",
"into",
"current",
"directory",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L792-L808 | train | 33,123 |
markokr/rarfile | rarfile.py | RarFile.extractall | def extractall(self, path=None, members=None, pwd=None):
"""Extract all files into current directory.
Parameters:
path
optional destination path
members
optional filename or :class:`RarInfo` instance list to extract
pwd
optional password to use
"""
fnlist = []
if members is not None:
for m in members:
if isinstance(m, RarInfo):
fnlist.append(m.filename)
else:
fnlist.append(m)
self._extract(fnlist, path, pwd) | python | def extractall(self, path=None, members=None, pwd=None):
"""Extract all files into current directory.
Parameters:
path
optional destination path
members
optional filename or :class:`RarInfo` instance list to extract
pwd
optional password to use
"""
fnlist = []
if members is not None:
for m in members:
if isinstance(m, RarInfo):
fnlist.append(m.filename)
else:
fnlist.append(m)
self._extract(fnlist, path, pwd) | [
"def",
"extractall",
"(",
"self",
",",
"path",
"=",
"None",
",",
"members",
"=",
"None",
",",
"pwd",
"=",
"None",
")",
":",
"fnlist",
"=",
"[",
"]",
"if",
"members",
"is",
"not",
"None",
":",
"for",
"m",
"in",
"members",
":",
"if",
"isinstance",
... | Extract all files into current directory.
Parameters:
path
optional destination path
members
optional filename or :class:`RarInfo` instance list to extract
pwd
optional password to use | [
"Extract",
"all",
"files",
"into",
"current",
"directory",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L810-L829 | train | 33,124 |
markokr/rarfile | rarfile.py | CommonParser.has_header_encryption | def has_header_encryption(self):
"""Returns True if headers are encrypted
"""
if self._hdrenc_main:
return True
if self._main:
if self._main.flags & RAR_MAIN_PASSWORD:
return True
return False | python | def has_header_encryption(self):
"""Returns True if headers are encrypted
"""
if self._hdrenc_main:
return True
if self._main:
if self._main.flags & RAR_MAIN_PASSWORD:
return True
return False | [
"def",
"has_header_encryption",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hdrenc_main",
":",
"return",
"True",
"if",
"self",
".",
"_main",
":",
"if",
"self",
".",
"_main",
".",
"flags",
"&",
"RAR_MAIN_PASSWORD",
":",
"return",
"True",
"return",
"False"
] | Returns True if headers are encrypted | [
"Returns",
"True",
"if",
"headers",
"are",
"encrypted"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L924-L932 | train | 33,125 |
markokr/rarfile | rarfile.py | CommonParser.getinfo | def getinfo(self, member):
"""Return RarInfo for filename
"""
if isinstance(member, RarInfo):
fname = member.filename
else:
fname = member
# accept both ways here
if PATH_SEP == '/':
fname2 = fname.replace("\\", "/")
else:
fname2 = fname.replace("/", "\\")
try:
return self._info_map[fname]
except KeyError:
try:
return self._info_map[fname2]
except KeyError:
raise NoRarEntry("No such file: %s" % fname) | python | def getinfo(self, member):
"""Return RarInfo for filename
"""
if isinstance(member, RarInfo):
fname = member.filename
else:
fname = member
# accept both ways here
if PATH_SEP == '/':
fname2 = fname.replace("\\", "/")
else:
fname2 = fname.replace("/", "\\")
try:
return self._info_map[fname]
except KeyError:
try:
return self._info_map[fname2]
except KeyError:
raise NoRarEntry("No such file: %s" % fname) | [
"def",
"getinfo",
"(",
"self",
",",
"member",
")",
":",
"if",
"isinstance",
"(",
"member",
",",
"RarInfo",
")",
":",
"fname",
"=",
"member",
".",
"filename",
"else",
":",
"fname",
"=",
"member",
"# accept both ways here",
"if",
"PATH_SEP",
"==",
"'/'",
"... | Return RarInfo for filename | [
"Return",
"RarInfo",
"for",
"filename"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L955-L975 | train | 33,126 |
markokr/rarfile | rarfile.py | CommonParser.parse | def parse(self):
"""Process file."""
self._fd = None
try:
self._parse_real()
finally:
if self._fd:
self._fd.close()
self._fd = None | python | def parse(self):
"""Process file."""
self._fd = None
try:
self._parse_real()
finally:
if self._fd:
self._fd.close()
self._fd = None | [
"def",
"parse",
"(",
"self",
")",
":",
"self",
".",
"_fd",
"=",
"None",
"try",
":",
"self",
".",
"_parse_real",
"(",
")",
"finally",
":",
"if",
"self",
".",
"_fd",
":",
"self",
".",
"_fd",
".",
"close",
"(",
")",
"self",
".",
"_fd",
"=",
"None"... | Process file. | [
"Process",
"file",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L978-L986 | train | 33,127 |
markokr/rarfile | rarfile.py | CommonParser.open | def open(self, inf, psw):
"""Return stream object for file data."""
if inf.file_redir:
# cannot leave to unrar as it expects copied file to exist
if inf.file_redir[0] in (RAR5_XREDIR_FILE_COPY, RAR5_XREDIR_HARD_LINK):
inf = self.getinfo(inf.file_redir[2])
if not inf:
raise BadRarFile('cannot find copied file')
if inf.flags & RAR_FILE_SPLIT_BEFORE:
raise NeedFirstVolume("Partial file, please start from first volume: " + inf.filename)
# is temp write usable?
use_hack = 1
if not self._main:
use_hack = 0
elif self._main._must_disable_hack():
use_hack = 0
elif inf._must_disable_hack():
use_hack = 0
elif is_filelike(self._rarfile):
pass
elif inf.file_size > HACK_SIZE_LIMIT:
use_hack = 0
elif not USE_EXTRACT_HACK:
use_hack = 0
# now extract
if inf.compress_type == RAR_M0 and (inf.flags & RAR_FILE_PASSWORD) == 0 and inf.file_redir is None:
return self._open_clear(inf)
elif use_hack:
return self._open_hack(inf, psw)
elif is_filelike(self._rarfile):
return self._open_unrar_membuf(self._rarfile, inf, psw)
else:
return self._open_unrar(self._rarfile, inf, psw) | python | def open(self, inf, psw):
"""Return stream object for file data."""
if inf.file_redir:
# cannot leave to unrar as it expects copied file to exist
if inf.file_redir[0] in (RAR5_XREDIR_FILE_COPY, RAR5_XREDIR_HARD_LINK):
inf = self.getinfo(inf.file_redir[2])
if not inf:
raise BadRarFile('cannot find copied file')
if inf.flags & RAR_FILE_SPLIT_BEFORE:
raise NeedFirstVolume("Partial file, please start from first volume: " + inf.filename)
# is temp write usable?
use_hack = 1
if not self._main:
use_hack = 0
elif self._main._must_disable_hack():
use_hack = 0
elif inf._must_disable_hack():
use_hack = 0
elif is_filelike(self._rarfile):
pass
elif inf.file_size > HACK_SIZE_LIMIT:
use_hack = 0
elif not USE_EXTRACT_HACK:
use_hack = 0
# now extract
if inf.compress_type == RAR_M0 and (inf.flags & RAR_FILE_PASSWORD) == 0 and inf.file_redir is None:
return self._open_clear(inf)
elif use_hack:
return self._open_hack(inf, psw)
elif is_filelike(self._rarfile):
return self._open_unrar_membuf(self._rarfile, inf, psw)
else:
return self._open_unrar(self._rarfile, inf, psw) | [
"def",
"open",
"(",
"self",
",",
"inf",
",",
"psw",
")",
":",
"if",
"inf",
".",
"file_redir",
":",
"# cannot leave to unrar as it expects copied file to exist",
"if",
"inf",
".",
"file_redir",
"[",
"0",
"]",
"in",
"(",
"RAR5_XREDIR_FILE_COPY",
",",
"RAR5_XREDIR_... | Return stream object for file data. | [
"Return",
"stream",
"object",
"for",
"file",
"data",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L1108-L1144 | train | 33,128 |
markokr/rarfile | rarfile.py | UnicodeFilename.enc_byte | def enc_byte(self):
"""Copy encoded byte."""
try:
c = self.encdata[self.encpos]
self.encpos += 1
return c
except IndexError:
self.failed = 1
return 0 | python | def enc_byte(self):
"""Copy encoded byte."""
try:
c = self.encdata[self.encpos]
self.encpos += 1
return c
except IndexError:
self.failed = 1
return 0 | [
"def",
"enc_byte",
"(",
"self",
")",
":",
"try",
":",
"c",
"=",
"self",
".",
"encdata",
"[",
"self",
".",
"encpos",
"]",
"self",
".",
"encpos",
"+=",
"1",
"return",
"c",
"except",
"IndexError",
":",
"self",
".",
"failed",
"=",
"1",
"return",
"0"
] | Copy encoded byte. | [
"Copy",
"encoded",
"byte",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L1909-L1917 | train | 33,129 |
markokr/rarfile | rarfile.py | UnicodeFilename.std_byte | def std_byte(self):
"""Copy byte from 8-bit representation."""
try:
return self.std_name[self.pos]
except IndexError:
self.failed = 1
return ord('?') | python | def std_byte(self):
"""Copy byte from 8-bit representation."""
try:
return self.std_name[self.pos]
except IndexError:
self.failed = 1
return ord('?') | [
"def",
"std_byte",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"std_name",
"[",
"self",
".",
"pos",
"]",
"except",
"IndexError",
":",
"self",
".",
"failed",
"=",
"1",
"return",
"ord",
"(",
"'?'",
")"
] | Copy byte from 8-bit representation. | [
"Copy",
"byte",
"from",
"8",
"-",
"bit",
"representation",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L1919-L1925 | train | 33,130 |
markokr/rarfile | rarfile.py | UnicodeFilename.put | def put(self, lo, hi):
"""Copy 16-bit value to result."""
self.buf.append(lo)
self.buf.append(hi)
self.pos += 1 | python | def put(self, lo, hi):
"""Copy 16-bit value to result."""
self.buf.append(lo)
self.buf.append(hi)
self.pos += 1 | [
"def",
"put",
"(",
"self",
",",
"lo",
",",
"hi",
")",
":",
"self",
".",
"buf",
".",
"append",
"(",
"lo",
")",
"self",
".",
"buf",
".",
"append",
"(",
"hi",
")",
"self",
".",
"pos",
"+=",
"1"
] | Copy 16-bit value to result. | [
"Copy",
"16",
"-",
"bit",
"value",
"to",
"result",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L1927-L1931 | train | 33,131 |
markokr/rarfile | rarfile.py | UnicodeFilename.decode | def decode(self):
"""Decompress compressed UTF16 value."""
hi = self.enc_byte()
flagbits = 0
while self.encpos < len(self.encdata):
if flagbits == 0:
flags = self.enc_byte()
flagbits = 8
flagbits -= 2
t = (flags >> flagbits) & 3
if t == 0:
self.put(self.enc_byte(), 0)
elif t == 1:
self.put(self.enc_byte(), hi)
elif t == 2:
self.put(self.enc_byte(), self.enc_byte())
else:
n = self.enc_byte()
if n & 0x80:
c = self.enc_byte()
for _ in range((n & 0x7f) + 2):
lo = (self.std_byte() + c) & 0xFF
self.put(lo, hi)
else:
for _ in range(n + 2):
self.put(self.std_byte(), 0)
return self.buf.decode("utf-16le", "replace") | python | def decode(self):
"""Decompress compressed UTF16 value."""
hi = self.enc_byte()
flagbits = 0
while self.encpos < len(self.encdata):
if flagbits == 0:
flags = self.enc_byte()
flagbits = 8
flagbits -= 2
t = (flags >> flagbits) & 3
if t == 0:
self.put(self.enc_byte(), 0)
elif t == 1:
self.put(self.enc_byte(), hi)
elif t == 2:
self.put(self.enc_byte(), self.enc_byte())
else:
n = self.enc_byte()
if n & 0x80:
c = self.enc_byte()
for _ in range((n & 0x7f) + 2):
lo = (self.std_byte() + c) & 0xFF
self.put(lo, hi)
else:
for _ in range(n + 2):
self.put(self.std_byte(), 0)
return self.buf.decode("utf-16le", "replace") | [
"def",
"decode",
"(",
"self",
")",
":",
"hi",
"=",
"self",
".",
"enc_byte",
"(",
")",
"flagbits",
"=",
"0",
"while",
"self",
".",
"encpos",
"<",
"len",
"(",
"self",
".",
"encdata",
")",
":",
"if",
"flagbits",
"==",
"0",
":",
"flags",
"=",
"self",... | Decompress compressed UTF16 value. | [
"Decompress",
"compressed",
"UTF16",
"value",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L1933-L1959 | train | 33,132 |
markokr/rarfile | rarfile.py | RarExtFile.read | def read(self, cnt=None):
"""Read all or specified amount of data from archive entry."""
# sanitize cnt
if cnt is None or cnt < 0:
cnt = self._remain
elif cnt > self._remain:
cnt = self._remain
if cnt == 0:
return EMPTY
# actual read
data = self._read(cnt)
if data:
self._md_context.update(data)
self._remain -= len(data)
if len(data) != cnt:
raise BadRarFile("Failed the read enough data")
# done?
if not data or self._remain == 0:
# self.close()
self._check()
return data | python | def read(self, cnt=None):
"""Read all or specified amount of data from archive entry."""
# sanitize cnt
if cnt is None or cnt < 0:
cnt = self._remain
elif cnt > self._remain:
cnt = self._remain
if cnt == 0:
return EMPTY
# actual read
data = self._read(cnt)
if data:
self._md_context.update(data)
self._remain -= len(data)
if len(data) != cnt:
raise BadRarFile("Failed the read enough data")
# done?
if not data or self._remain == 0:
# self.close()
self._check()
return data | [
"def",
"read",
"(",
"self",
",",
"cnt",
"=",
"None",
")",
":",
"# sanitize cnt",
"if",
"cnt",
"is",
"None",
"or",
"cnt",
"<",
"0",
":",
"cnt",
"=",
"self",
".",
"_remain",
"elif",
"cnt",
">",
"self",
".",
"_remain",
":",
"cnt",
"=",
"self",
".",
... | Read all or specified amount of data from archive entry. | [
"Read",
"all",
"or",
"specified",
"amount",
"of",
"data",
"from",
"archive",
"entry",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2002-L2025 | train | 33,133 |
markokr/rarfile | rarfile.py | RarExtFile._check | def _check(self):
"""Check final CRC."""
final = self._md_context.digest()
exp = self._inf._md_expect
if exp is None:
return
if final is None:
return
if self._returncode:
check_returncode(self, '')
if self._remain != 0:
raise BadRarFile("Failed the read enough data")
if final != exp:
raise BadRarFile("Corrupt file - CRC check failed: %s - exp=%r got=%r" % (
self._inf.filename, exp, final)) | python | def _check(self):
"""Check final CRC."""
final = self._md_context.digest()
exp = self._inf._md_expect
if exp is None:
return
if final is None:
return
if self._returncode:
check_returncode(self, '')
if self._remain != 0:
raise BadRarFile("Failed the read enough data")
if final != exp:
raise BadRarFile("Corrupt file - CRC check failed: %s - exp=%r got=%r" % (
self._inf.filename, exp, final)) | [
"def",
"_check",
"(",
"self",
")",
":",
"final",
"=",
"self",
".",
"_md_context",
".",
"digest",
"(",
")",
"exp",
"=",
"self",
".",
"_inf",
".",
"_md_expect",
"if",
"exp",
"is",
"None",
":",
"return",
"if",
"final",
"is",
"None",
":",
"return",
"if... | Check final CRC. | [
"Check",
"final",
"CRC",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2027-L2041 | train | 33,134 |
markokr/rarfile | rarfile.py | RarExtFile.seek | def seek(self, ofs, whence=0):
"""Seek in data.
On uncompressed files, the seeking works by actual
seeks so it's fast. On compresses files its slow
- forward seeking happends by reading ahead,
backwards by re-opening and decompressing from the start.
"""
# disable crc check when seeking
self._md_context = NoHashContext()
fsize = self._inf.file_size
cur_ofs = self.tell()
if whence == 0: # seek from beginning of file
new_ofs = ofs
elif whence == 1: # seek from current position
new_ofs = cur_ofs + ofs
elif whence == 2: # seek from end of file
new_ofs = fsize + ofs
else:
raise ValueError('Invalid value for whence')
# sanity check
if new_ofs < 0:
new_ofs = 0
elif new_ofs > fsize:
new_ofs = fsize
# do the actual seek
if new_ofs >= cur_ofs:
self._skip(new_ofs - cur_ofs)
else:
# reopen and seek
self._open()
self._skip(new_ofs)
return self.tell() | python | def seek(self, ofs, whence=0):
"""Seek in data.
On uncompressed files, the seeking works by actual
seeks so it's fast. On compresses files its slow
- forward seeking happends by reading ahead,
backwards by re-opening and decompressing from the start.
"""
# disable crc check when seeking
self._md_context = NoHashContext()
fsize = self._inf.file_size
cur_ofs = self.tell()
if whence == 0: # seek from beginning of file
new_ofs = ofs
elif whence == 1: # seek from current position
new_ofs = cur_ofs + ofs
elif whence == 2: # seek from end of file
new_ofs = fsize + ofs
else:
raise ValueError('Invalid value for whence')
# sanity check
if new_ofs < 0:
new_ofs = 0
elif new_ofs > fsize:
new_ofs = fsize
# do the actual seek
if new_ofs >= cur_ofs:
self._skip(new_ofs - cur_ofs)
else:
# reopen and seek
self._open()
self._skip(new_ofs)
return self.tell() | [
"def",
"seek",
"(",
"self",
",",
"ofs",
",",
"whence",
"=",
"0",
")",
":",
"# disable crc check when seeking",
"self",
".",
"_md_context",
"=",
"NoHashContext",
"(",
")",
"fsize",
"=",
"self",
".",
"_inf",
".",
"file_size",
"cur_ofs",
"=",
"self",
".",
"... | Seek in data.
On uncompressed files, the seeking works by actual
seeks so it's fast. On compresses files its slow
- forward seeking happends by reading ahead,
backwards by re-opening and decompressing from the start. | [
"Seek",
"in",
"data",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2070-L2107 | train | 33,135 |
markokr/rarfile | rarfile.py | RarExtFile._skip | def _skip(self, cnt):
"""Read and discard data"""
while cnt > 0:
if cnt > 8192:
buf = self.read(8192)
else:
buf = self.read(cnt)
if not buf:
break
cnt -= len(buf) | python | def _skip(self, cnt):
"""Read and discard data"""
while cnt > 0:
if cnt > 8192:
buf = self.read(8192)
else:
buf = self.read(cnt)
if not buf:
break
cnt -= len(buf) | [
"def",
"_skip",
"(",
"self",
",",
"cnt",
")",
":",
"while",
"cnt",
">",
"0",
":",
"if",
"cnt",
">",
"8192",
":",
"buf",
"=",
"self",
".",
"read",
"(",
"8192",
")",
"else",
":",
"buf",
"=",
"self",
".",
"read",
"(",
"cnt",
")",
"if",
"not",
... | Read and discard data | [
"Read",
"and",
"discard",
"data"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2109-L2118 | train | 33,136 |
markokr/rarfile | rarfile.py | PipeReader._read | def _read(self, cnt):
"""Read from pipe."""
# normal read is usually enough
data = self._fd.read(cnt)
if len(data) == cnt or not data:
return data
# short read, try looping
buf = [data]
cnt -= len(data)
while cnt > 0:
data = self._fd.read(cnt)
if not data:
break
cnt -= len(data)
buf.append(data)
return EMPTY.join(buf) | python | def _read(self, cnt):
"""Read from pipe."""
# normal read is usually enough
data = self._fd.read(cnt)
if len(data) == cnt or not data:
return data
# short read, try looping
buf = [data]
cnt -= len(data)
while cnt > 0:
data = self._fd.read(cnt)
if not data:
break
cnt -= len(data)
buf.append(data)
return EMPTY.join(buf) | [
"def",
"_read",
"(",
"self",
",",
"cnt",
")",
":",
"# normal read is usually enough",
"data",
"=",
"self",
".",
"_fd",
".",
"read",
"(",
"cnt",
")",
"if",
"len",
"(",
"data",
")",
"==",
"cnt",
"or",
"not",
"data",
":",
"return",
"data",
"# short read, ... | Read from pipe. | [
"Read",
"from",
"pipe",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2181-L2198 | train | 33,137 |
markokr/rarfile | rarfile.py | DirectReader._skip | def _skip(self, cnt):
"""RAR Seek, skipping through rar files to get to correct position
"""
while cnt > 0:
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# fd is in read pos, do the read
if cnt > self._cur_avail:
cnt -= self._cur_avail
self._remain -= self._cur_avail
self._cur_avail = 0
else:
self._fd.seek(cnt, 1)
self._cur_avail -= cnt
self._remain -= cnt
cnt = 0 | python | def _skip(self, cnt):
"""RAR Seek, skipping through rar files to get to correct position
"""
while cnt > 0:
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# fd is in read pos, do the read
if cnt > self._cur_avail:
cnt -= self._cur_avail
self._remain -= self._cur_avail
self._cur_avail = 0
else:
self._fd.seek(cnt, 1)
self._cur_avail -= cnt
self._remain -= cnt
cnt = 0 | [
"def",
"_skip",
"(",
"self",
",",
"cnt",
")",
":",
"while",
"cnt",
">",
"0",
":",
"# next vol needed?",
"if",
"self",
".",
"_cur_avail",
"==",
"0",
":",
"if",
"not",
"self",
".",
"_open_next",
"(",
")",
":",
"break",
"# fd is in read pos, do the read",
"... | RAR Seek, skipping through rar files to get to correct position | [
"RAR",
"Seek",
"skipping",
"through",
"rar",
"files",
"to",
"get",
"to",
"correct",
"position"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2246-L2265 | train | 33,138 |
markokr/rarfile | rarfile.py | DirectReader._read | def _read(self, cnt):
"""Read from potentially multi-volume archive."""
buf = []
while cnt > 0:
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# fd is in read pos, do the read
if cnt > self._cur_avail:
data = self._fd.read(self._cur_avail)
else:
data = self._fd.read(cnt)
if not data:
break
# got some data
cnt -= len(data)
self._cur_avail -= len(data)
buf.append(data)
if len(buf) == 1:
return buf[0]
return EMPTY.join(buf) | python | def _read(self, cnt):
"""Read from potentially multi-volume archive."""
buf = []
while cnt > 0:
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# fd is in read pos, do the read
if cnt > self._cur_avail:
data = self._fd.read(self._cur_avail)
else:
data = self._fd.read(cnt)
if not data:
break
# got some data
cnt -= len(data)
self._cur_avail -= len(data)
buf.append(data)
if len(buf) == 1:
return buf[0]
return EMPTY.join(buf) | [
"def",
"_read",
"(",
"self",
",",
"cnt",
")",
":",
"buf",
"=",
"[",
"]",
"while",
"cnt",
">",
"0",
":",
"# next vol needed?",
"if",
"self",
".",
"_cur_avail",
"==",
"0",
":",
"if",
"not",
"self",
".",
"_open_next",
"(",
")",
":",
"break",
"# fd is ... | Read from potentially multi-volume archive. | [
"Read",
"from",
"potentially",
"multi",
"-",
"volume",
"archive",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2267-L2292 | train | 33,139 |
markokr/rarfile | rarfile.py | DirectReader.readinto | def readinto(self, buf):
"""Zero-copy read directly into buffer."""
got = 0
vbuf = memoryview(buf)
while got < len(buf):
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# length for next read
cnt = len(buf) - got
if cnt > self._cur_avail:
cnt = self._cur_avail
# read into temp view
res = self._fd.readinto(vbuf[got : got + cnt])
if not res:
break
self._md_context.update(vbuf[got : got + res])
self._cur_avail -= res
self._remain -= res
got += res
return got | python | def readinto(self, buf):
"""Zero-copy read directly into buffer."""
got = 0
vbuf = memoryview(buf)
while got < len(buf):
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# length for next read
cnt = len(buf) - got
if cnt > self._cur_avail:
cnt = self._cur_avail
# read into temp view
res = self._fd.readinto(vbuf[got : got + cnt])
if not res:
break
self._md_context.update(vbuf[got : got + res])
self._cur_avail -= res
self._remain -= res
got += res
return got | [
"def",
"readinto",
"(",
"self",
",",
"buf",
")",
":",
"got",
"=",
"0",
"vbuf",
"=",
"memoryview",
"(",
"buf",
")",
"while",
"got",
"<",
"len",
"(",
"buf",
")",
":",
"# next vol needed?",
"if",
"self",
".",
"_cur_avail",
"==",
"0",
":",
"if",
"not",... | Zero-copy read directly into buffer. | [
"Zero",
"-",
"copy",
"read",
"directly",
"into",
"buffer",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2328-L2351 | train | 33,140 |
markokr/rarfile | rarfile.py | HeaderDecrypt.read | def read(self, cnt=None):
"""Read and decrypt."""
if cnt > 8 * 1024:
raise BadRarFile('Bad count to header decrypt - wrong password?')
# consume old data
if cnt <= len(self.buf):
res = self.buf[:cnt]
self.buf = self.buf[cnt:]
return res
res = self.buf
self.buf = EMPTY
cnt -= len(res)
# decrypt new data
blklen = 16
while cnt > 0:
enc = self.f.read(blklen)
if len(enc) < blklen:
break
dec = self.ciph.decrypt(enc)
if cnt >= len(dec):
res += dec
cnt -= len(dec)
else:
res += dec[:cnt]
self.buf = dec[cnt:]
cnt = 0
return res | python | def read(self, cnt=None):
"""Read and decrypt."""
if cnt > 8 * 1024:
raise BadRarFile('Bad count to header decrypt - wrong password?')
# consume old data
if cnt <= len(self.buf):
res = self.buf[:cnt]
self.buf = self.buf[cnt:]
return res
res = self.buf
self.buf = EMPTY
cnt -= len(res)
# decrypt new data
blklen = 16
while cnt > 0:
enc = self.f.read(blklen)
if len(enc) < blklen:
break
dec = self.ciph.decrypt(enc)
if cnt >= len(dec):
res += dec
cnt -= len(dec)
else:
res += dec[:cnt]
self.buf = dec[cnt:]
cnt = 0
return res | [
"def",
"read",
"(",
"self",
",",
"cnt",
"=",
"None",
")",
":",
"if",
"cnt",
">",
"8",
"*",
"1024",
":",
"raise",
"BadRarFile",
"(",
"'Bad count to header decrypt - wrong password?'",
")",
"# consume old data",
"if",
"cnt",
"<=",
"len",
"(",
"self",
".",
"b... | Read and decrypt. | [
"Read",
"and",
"decrypt",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2365-L2394 | train | 33,141 |
markokr/rarfile | rarfile.py | Blake2SP.update | def update(self, data):
"""Hash data.
"""
view = memoryview(data)
bs = self.block_size
if self._buf:
need = bs - len(self._buf)
if len(view) < need:
self._buf += view.tobytes()
return
self._add_block(self._buf + view[:need].tobytes())
view = view[need:]
while len(view) >= bs:
self._add_block(view[:bs])
view = view[bs:]
self._buf = view.tobytes() | python | def update(self, data):
"""Hash data.
"""
view = memoryview(data)
bs = self.block_size
if self._buf:
need = bs - len(self._buf)
if len(view) < need:
self._buf += view.tobytes()
return
self._add_block(self._buf + view[:need].tobytes())
view = view[need:]
while len(view) >= bs:
self._add_block(view[:bs])
view = view[bs:]
self._buf = view.tobytes() | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"view",
"=",
"memoryview",
"(",
"data",
")",
"bs",
"=",
"self",
".",
"block_size",
"if",
"self",
".",
"_buf",
":",
"need",
"=",
"bs",
"-",
"len",
"(",
"self",
".",
"_buf",
")",
"if",
"len",
"... | Hash data. | [
"Hash",
"data",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2503-L2518 | train | 33,142 |
markokr/rarfile | rarfile.py | Blake2SP.digest | def digest(self):
"""Return final digest value.
"""
if self._digest is None:
if self._buf:
self._add_block(self._buf)
self._buf = EMPTY
ctx = self._blake2s(0, 1, True)
for t in self._thread:
ctx.update(t.digest())
self._digest = ctx.digest()
return self._digest | python | def digest(self):
"""Return final digest value.
"""
if self._digest is None:
if self._buf:
self._add_block(self._buf)
self._buf = EMPTY
ctx = self._blake2s(0, 1, True)
for t in self._thread:
ctx.update(t.digest())
self._digest = ctx.digest()
return self._digest | [
"def",
"digest",
"(",
"self",
")",
":",
"if",
"self",
".",
"_digest",
"is",
"None",
":",
"if",
"self",
".",
"_buf",
":",
"self",
".",
"_add_block",
"(",
"self",
".",
"_buf",
")",
"self",
".",
"_buf",
"=",
"EMPTY",
"ctx",
"=",
"self",
".",
"_blake... | Return final digest value. | [
"Return",
"final",
"digest",
"value",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2520-L2531 | train | 33,143 |
markokr/rarfile | rarfile.py | Rar3Sha1.update | def update(self, data):
"""Process more data."""
self._md.update(data)
bufpos = self._nbytes & 63
self._nbytes += len(data)
if self._rarbug and len(data) > 64:
dpos = self.block_size - bufpos
while dpos + self.block_size <= len(data):
self._corrupt(data, dpos)
dpos += self.block_size | python | def update(self, data):
"""Process more data."""
self._md.update(data)
bufpos = self._nbytes & 63
self._nbytes += len(data)
if self._rarbug and len(data) > 64:
dpos = self.block_size - bufpos
while dpos + self.block_size <= len(data):
self._corrupt(data, dpos)
dpos += self.block_size | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_md",
".",
"update",
"(",
"data",
")",
"bufpos",
"=",
"self",
".",
"_nbytes",
"&",
"63",
"self",
".",
"_nbytes",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"_rarbug",
"and"... | Process more data. | [
"Process",
"more",
"data",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2555-L2565 | train | 33,144 |
markokr/rarfile | rarfile.py | Rar3Sha1._corrupt | def _corrupt(self, data, dpos):
"""Corruption from SHA1 core."""
ws = list(self._BLK_BE.unpack_from(data, dpos))
for t in range(16, 80):
tmp = ws[(t - 3) & 15] ^ ws[(t - 8) & 15] ^ ws[(t - 14) & 15] ^ ws[(t - 16) & 15]
ws[t & 15] = ((tmp << 1) | (tmp >> (32 - 1))) & 0xFFFFFFFF
self._BLK_LE.pack_into(data, dpos, *ws) | python | def _corrupt(self, data, dpos):
"""Corruption from SHA1 core."""
ws = list(self._BLK_BE.unpack_from(data, dpos))
for t in range(16, 80):
tmp = ws[(t - 3) & 15] ^ ws[(t - 8) & 15] ^ ws[(t - 14) & 15] ^ ws[(t - 16) & 15]
ws[t & 15] = ((tmp << 1) | (tmp >> (32 - 1))) & 0xFFFFFFFF
self._BLK_LE.pack_into(data, dpos, *ws) | [
"def",
"_corrupt",
"(",
"self",
",",
"data",
",",
"dpos",
")",
":",
"ws",
"=",
"list",
"(",
"self",
".",
"_BLK_BE",
".",
"unpack_from",
"(",
"data",
",",
"dpos",
")",
")",
"for",
"t",
"in",
"range",
"(",
"16",
",",
"80",
")",
":",
"tmp",
"=",
... | Corruption from SHA1 core. | [
"Corruption",
"from",
"SHA1",
"core",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2575-L2581 | train | 33,145 |
chhantyal/taggit-selectize | taggit_selectize/views.py | get_tags_recommendation | def get_tags_recommendation(request):
"""
Taggit autocomplete ajax view.
Response objects are filtered based on query param.
Tags are by default limited to 10, use TAGGIT_SELECTIZE_RECOMMENDATION_LIMIT settings to specify.
"""
query = request.GET.get('query')
limit = settings.TAGGIT_SELECTIZE['RECOMMENDATION_LIMIT']
try:
cls = import_string(settings.TAGGIT_SELECTIZE_THROUGH)
except AttributeError:
cls = Tag
if query:
tags = cls.objects.filter(name__icontains=query).values('name')[:limit]
else:
tags = cls.objects.values()[:limit]
data = json.dumps({
'tags': list(tags)
})
return HttpResponse(data, content_type='application/json') | python | def get_tags_recommendation(request):
"""
Taggit autocomplete ajax view.
Response objects are filtered based on query param.
Tags are by default limited to 10, use TAGGIT_SELECTIZE_RECOMMENDATION_LIMIT settings to specify.
"""
query = request.GET.get('query')
limit = settings.TAGGIT_SELECTIZE['RECOMMENDATION_LIMIT']
try:
cls = import_string(settings.TAGGIT_SELECTIZE_THROUGH)
except AttributeError:
cls = Tag
if query:
tags = cls.objects.filter(name__icontains=query).values('name')[:limit]
else:
tags = cls.objects.values()[:limit]
data = json.dumps({
'tags': list(tags)
})
return HttpResponse(data, content_type='application/json') | [
"def",
"get_tags_recommendation",
"(",
"request",
")",
":",
"query",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'query'",
")",
"limit",
"=",
"settings",
".",
"TAGGIT_SELECTIZE",
"[",
"'RECOMMENDATION_LIMIT'",
"]",
"try",
":",
"cls",
"=",
"import_string",
... | Taggit autocomplete ajax view.
Response objects are filtered based on query param.
Tags are by default limited to 10, use TAGGIT_SELECTIZE_RECOMMENDATION_LIMIT settings to specify. | [
"Taggit",
"autocomplete",
"ajax",
"view",
".",
"Response",
"objects",
"are",
"filtered",
"based",
"on",
"query",
"param",
".",
"Tags",
"are",
"by",
"default",
"limited",
"to",
"10",
"use",
"TAGGIT_SELECTIZE_RECOMMENDATION_LIMIT",
"settings",
"to",
"specify",
"."
] | 363897fa83933b769ea1e4a0e9a7a489873d8239 | https://github.com/chhantyal/taggit-selectize/blob/363897fa83933b769ea1e4a0e9a7a489873d8239/taggit_selectize/views.py#L8-L31 | train | 33,146 |
chhantyal/taggit-selectize | taggit_selectize/utils.py | parse_tags | def parse_tags(tagstring):
"""
Parses tag input, with multiple word input being activated and
delineated by commas and double quotes. Quotes take precedence, so
they may contain commas.
Returns a sorted list of unique tag names.
Adapted from Taggit, modified to not split strings on spaces.
Ported from Jonathan Buchanan's `django-tagging
<http://django-tagging.googlecode.com/>`_
"""
if not tagstring:
return []
tagstring = force_text(tagstring)
words = []
buffer = []
# Defer splitting of non-quoted sections until we know if there are
# any unquoted commas.
to_be_split = []
i = iter(tagstring)
try:
while True:
c = six.next(i)
if c == '"':
if buffer:
to_be_split.append(''.join(buffer))
buffer = []
c = six.next(i)
while c != '"':
buffer.append(c)
c = six.next(i)
if buffer:
word = ''.join(buffer).strip()
if word:
words.append(word)
buffer = []
else:
buffer.append(c)
except StopIteration:
# If we were parsing an open quote which was never closed treat
# the buffer as unquoted.
if buffer:
to_be_split.append(''.join(buffer))
if to_be_split:
for chunk in to_be_split:
words.extend(split_strip(chunk, settings.TAGGIT_SELECTIZE['DELIMITER']))
words = list(set(words))
words.sort()
return words | python | def parse_tags(tagstring):
"""
Parses tag input, with multiple word input being activated and
delineated by commas and double quotes. Quotes take precedence, so
they may contain commas.
Returns a sorted list of unique tag names.
Adapted from Taggit, modified to not split strings on spaces.
Ported from Jonathan Buchanan's `django-tagging
<http://django-tagging.googlecode.com/>`_
"""
if not tagstring:
return []
tagstring = force_text(tagstring)
words = []
buffer = []
# Defer splitting of non-quoted sections until we know if there are
# any unquoted commas.
to_be_split = []
i = iter(tagstring)
try:
while True:
c = six.next(i)
if c == '"':
if buffer:
to_be_split.append(''.join(buffer))
buffer = []
c = six.next(i)
while c != '"':
buffer.append(c)
c = six.next(i)
if buffer:
word = ''.join(buffer).strip()
if word:
words.append(word)
buffer = []
else:
buffer.append(c)
except StopIteration:
# If we were parsing an open quote which was never closed treat
# the buffer as unquoted.
if buffer:
to_be_split.append(''.join(buffer))
if to_be_split:
for chunk in to_be_split:
words.extend(split_strip(chunk, settings.TAGGIT_SELECTIZE['DELIMITER']))
words = list(set(words))
words.sort()
return words | [
"def",
"parse_tags",
"(",
"tagstring",
")",
":",
"if",
"not",
"tagstring",
":",
"return",
"[",
"]",
"tagstring",
"=",
"force_text",
"(",
"tagstring",
")",
"words",
"=",
"[",
"]",
"buffer",
"=",
"[",
"]",
"# Defer splitting of non-quoted sections until we know if... | Parses tag input, with multiple word input being activated and
delineated by commas and double quotes. Quotes take precedence, so
they may contain commas.
Returns a sorted list of unique tag names.
Adapted from Taggit, modified to not split strings on spaces.
Ported from Jonathan Buchanan's `django-tagging
<http://django-tagging.googlecode.com/>`_ | [
"Parses",
"tag",
"input",
"with",
"multiple",
"word",
"input",
"being",
"activated",
"and",
"delineated",
"by",
"commas",
"and",
"double",
"quotes",
".",
"Quotes",
"take",
"precedence",
"so",
"they",
"may",
"contain",
"commas",
"."
] | 363897fa83933b769ea1e4a0e9a7a489873d8239 | https://github.com/chhantyal/taggit-selectize/blob/363897fa83933b769ea1e4a0e9a7a489873d8239/taggit_selectize/utils.py#L7-L59 | train | 33,147 |
chhantyal/taggit-selectize | taggit_selectize/utils.py | join_tags | def join_tags(tags):
"""
Given list of ``Tag`` instances, creates a string representation of
the list suitable for editing by the user, such that submitting the
given string representation back without changing it will give the
same list of tags.
Tag names which contain DELIMITER will be double quoted.
Adapted from Taggit's _edit_string_for_tags()
Ported from Jonathan Buchanan's `django-tagging
<http://django-tagging.googlecode.com/>`_
"""
names = []
delimiter = settings.TAGGIT_SELECTIZE['DELIMITER']
for tag in tags:
name = tag.name
if delimiter in name or ' ' in name:
names.append('"%s"' % name)
else:
names.append(name)
return delimiter.join(sorted(names)) | python | def join_tags(tags):
"""
Given list of ``Tag`` instances, creates a string representation of
the list suitable for editing by the user, such that submitting the
given string representation back without changing it will give the
same list of tags.
Tag names which contain DELIMITER will be double quoted.
Adapted from Taggit's _edit_string_for_tags()
Ported from Jonathan Buchanan's `django-tagging
<http://django-tagging.googlecode.com/>`_
"""
names = []
delimiter = settings.TAGGIT_SELECTIZE['DELIMITER']
for tag in tags:
name = tag.name
if delimiter in name or ' ' in name:
names.append('"%s"' % name)
else:
names.append(name)
return delimiter.join(sorted(names)) | [
"def",
"join_tags",
"(",
"tags",
")",
":",
"names",
"=",
"[",
"]",
"delimiter",
"=",
"settings",
".",
"TAGGIT_SELECTIZE",
"[",
"'DELIMITER'",
"]",
"for",
"tag",
"in",
"tags",
":",
"name",
"=",
"tag",
".",
"name",
"if",
"delimiter",
"in",
"name",
"or",
... | Given list of ``Tag`` instances, creates a string representation of
the list suitable for editing by the user, such that submitting the
given string representation back without changing it will give the
same list of tags.
Tag names which contain DELIMITER will be double quoted.
Adapted from Taggit's _edit_string_for_tags()
Ported from Jonathan Buchanan's `django-tagging
<http://django-tagging.googlecode.com/>`_ | [
"Given",
"list",
"of",
"Tag",
"instances",
"creates",
"a",
"string",
"representation",
"of",
"the",
"list",
"suitable",
"for",
"editing",
"by",
"the",
"user",
"such",
"that",
"submitting",
"the",
"given",
"string",
"representation",
"back",
"without",
"changing"... | 363897fa83933b769ea1e4a0e9a7a489873d8239 | https://github.com/chhantyal/taggit-selectize/blob/363897fa83933b769ea1e4a0e9a7a489873d8239/taggit_selectize/utils.py#L62-L84 | train | 33,148 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/management/templates/python-engine/project_package/_logging.py | get_logger | def get_logger(name, namespace='{{project.package}}',
log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR):
"""Build a logger that outputs to a file and to the console,"""
log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or
os.getenv('LOG_LEVEL', log_level))
log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or
os.getenv('LOG_DIR', log_dir))
logger = logging.getLogger('{}.{}'.format(namespace, name))
logger.setLevel(log_level)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Create a console stream handler
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
try:
if log_dir:
log_path = os.path.abspath(log_dir)
log_filename = '{name}.{pid}.log'.format(
name=namespace, pid=os.getpid())
file_path = str(os.path.join(log_path, log_filename))
if not os.path.exists(log_path):
os.makedirs(log_path, mode=774)
# Create a file handler
file_handler = logging.FileHandler(file_path)
file_handler.setLevel(log_level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
except OSError as e:
logger.error('Could not create log file {file}: {error}'.format(
file=file_path, error=e.strerror))
return logger | python | def get_logger(name, namespace='{{project.package}}',
log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR):
"""Build a logger that outputs to a file and to the console,"""
log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or
os.getenv('LOG_LEVEL', log_level))
log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or
os.getenv('LOG_DIR', log_dir))
logger = logging.getLogger('{}.{}'.format(namespace, name))
logger.setLevel(log_level)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Create a console stream handler
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
try:
if log_dir:
log_path = os.path.abspath(log_dir)
log_filename = '{name}.{pid}.log'.format(
name=namespace, pid=os.getpid())
file_path = str(os.path.join(log_path, log_filename))
if not os.path.exists(log_path):
os.makedirs(log_path, mode=774)
# Create a file handler
file_handler = logging.FileHandler(file_path)
file_handler.setLevel(log_level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
except OSError as e:
logger.error('Could not create log file {file}: {error}'.format(
file=file_path, error=e.strerror))
return logger | [
"def",
"get_logger",
"(",
"name",
",",
"namespace",
"=",
"'{{project.package}}'",
",",
"log_level",
"=",
"DEFAULT_LOG_LEVEL",
",",
"log_dir",
"=",
"DEFAULT_LOG_DIR",
")",
":",
"log_level",
"=",
"(",
"os",
".",
"getenv",
"(",
"'{}_LOG_LEVEL'",
".",
"format",
"(... | Build a logger that outputs to a file and to the console, | [
"Build",
"a",
"logger",
"that",
"outputs",
"to",
"a",
"file",
"and",
"to",
"the",
"console"
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/management/templates/python-engine/project_package/_logging.py#L36-L77 | train | 33,149 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/config.py | Configuration.get | def get(cls, key, section=None, **kwargs):
"""
Retrieves a config value from dict.
If not found twrows an InvalidScanbooconfigException.
"""
section = section or cls._default_sect
if section not in cls._conf:
cls._load(section=section)
value = cls._conf[section].get(key)
# if not found in context read default
if not value and section != cls._default_sect:
value = cls._conf[cls._default_sect].get(key) if cls._default_sect in cls._conf else None
if value is None:
if 'default' in kwargs: # behave as {}.get(x, default='fallback')
_def_value = kwargs['default']
logger.warn("Static configuration [{}] was not found. Using the default value [{}].".format(key, _def_value))
return _def_value
else:
raise InvalidConfigException(u'Not found entry: {}'.format(key))
try:
value = from_json(value) # parse value
except (TypeError, ValueError):
pass # if not json parseable, then keep the string value
return value | python | def get(cls, key, section=None, **kwargs):
"""
Retrieves a config value from dict.
If not found twrows an InvalidScanbooconfigException.
"""
section = section or cls._default_sect
if section not in cls._conf:
cls._load(section=section)
value = cls._conf[section].get(key)
# if not found in context read default
if not value and section != cls._default_sect:
value = cls._conf[cls._default_sect].get(key) if cls._default_sect in cls._conf else None
if value is None:
if 'default' in kwargs: # behave as {}.get(x, default='fallback')
_def_value = kwargs['default']
logger.warn("Static configuration [{}] was not found. Using the default value [{}].".format(key, _def_value))
return _def_value
else:
raise InvalidConfigException(u'Not found entry: {}'.format(key))
try:
value = from_json(value) # parse value
except (TypeError, ValueError):
pass # if not json parseable, then keep the string value
return value | [
"def",
"get",
"(",
"cls",
",",
"key",
",",
"section",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"section",
"=",
"section",
"or",
"cls",
".",
"_default_sect",
"if",
"section",
"not",
"in",
"cls",
".",
"_conf",
":",
"cls",
".",
"_load",
"(",
... | Retrieves a config value from dict.
If not found twrows an InvalidScanbooconfigException. | [
"Retrieves",
"a",
"config",
"value",
"from",
"dict",
".",
"If",
"not",
"found",
"twrows",
"an",
"InvalidScanbooconfigException",
"."
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/config.py#L90-L118 | train | 33,150 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/config.py | Configuration.keys | def keys(cls, section=None):
"""Get a list with all config keys"""
section = section or cls._default_sect
if section not in cls._conf:
cls._load(section=section)
return cls._conf[section].keys() | python | def keys(cls, section=None):
"""Get a list with all config keys"""
section = section or cls._default_sect
if section not in cls._conf:
cls._load(section=section)
return cls._conf[section].keys() | [
"def",
"keys",
"(",
"cls",
",",
"section",
"=",
"None",
")",
":",
"section",
"=",
"section",
"or",
"cls",
".",
"_default_sect",
"if",
"section",
"not",
"in",
"cls",
".",
"_conf",
":",
"cls",
".",
"_load",
"(",
"section",
"=",
"section",
")",
"return"... | Get a list with all config keys | [
"Get",
"a",
"list",
"with",
"all",
"config",
"keys"
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/config.py#L121-L126 | train | 33,151 |
vmware/column | column/api/controller/credential_controller.py | Credential.get | def get(self):
"""Get a credential by file path"""
args = self.get_parser.parse_args()
cred = self.manager.get_credential(args)
if cred is None:
return abort(http_client.BAD_REQUEST,
message='Unable to decrypt credential value.')
else:
return cred | python | def get(self):
"""Get a credential by file path"""
args = self.get_parser.parse_args()
cred = self.manager.get_credential(args)
if cred is None:
return abort(http_client.BAD_REQUEST,
message='Unable to decrypt credential value.')
else:
return cred | [
"def",
"get",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"get_parser",
".",
"parse_args",
"(",
")",
"cred",
"=",
"self",
".",
"manager",
".",
"get_credential",
"(",
"args",
")",
"if",
"cred",
"is",
"None",
":",
"return",
"abort",
"(",
"http_cli... | Get a credential by file path | [
"Get",
"a",
"credential",
"by",
"file",
"path"
] | 86c72b29e8c1ec58474bd39757f18a3834a446ef | https://github.com/vmware/column/blob/86c72b29e8c1ec58474bd39757f18a3834a446ef/column/api/controller/credential_controller.py#L47-L55 | train | 33,152 |
vmware/column | column/api/controller/credential_controller.py | Credential.put | def put(self):
"""Update a credential by file path"""
cred_payload = utils.uni_to_str(json.loads(request.get_data()))
return self.manager.update_credential(cred_payload) | python | def put(self):
"""Update a credential by file path"""
cred_payload = utils.uni_to_str(json.loads(request.get_data()))
return self.manager.update_credential(cred_payload) | [
"def",
"put",
"(",
"self",
")",
":",
"cred_payload",
"=",
"utils",
".",
"uni_to_str",
"(",
"json",
".",
"loads",
"(",
"request",
".",
"get_data",
"(",
")",
")",
")",
"return",
"self",
".",
"manager",
".",
"update_credential",
"(",
"cred_payload",
")"
] | Update a credential by file path | [
"Update",
"a",
"credential",
"by",
"file",
"path"
] | 86c72b29e8c1ec58474bd39757f18a3834a446ef | https://github.com/vmware/column/blob/86c72b29e8c1ec58474bd39757f18a3834a446ef/column/api/controller/credential_controller.py#L58-L61 | train | 33,153 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | HttpClient.parse_response | def parse_response(self, response):
"""
Parse the response and build a `scanboo_common.http_client.HttpResponse` object.
For successful responses, convert the json data into a dict.
:param response: the `requests` response
:return: [HttpResponse] response object
"""
status = response.status_code
if response.ok:
data = response.json()
return HttpResponse(ok=response.ok, status=status, errors=None, data=data)
else:
try:
errors = response.json()
except ValueError:
errors = response.content
return HttpResponse(ok=response.ok, status=status, errors=errors, data=None) | python | def parse_response(self, response):
"""
Parse the response and build a `scanboo_common.http_client.HttpResponse` object.
For successful responses, convert the json data into a dict.
:param response: the `requests` response
:return: [HttpResponse] response object
"""
status = response.status_code
if response.ok:
data = response.json()
return HttpResponse(ok=response.ok, status=status, errors=None, data=data)
else:
try:
errors = response.json()
except ValueError:
errors = response.content
return HttpResponse(ok=response.ok, status=status, errors=errors, data=None) | [
"def",
"parse_response",
"(",
"self",
",",
"response",
")",
":",
"status",
"=",
"response",
".",
"status_code",
"if",
"response",
".",
"ok",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"return",
"HttpResponse",
"(",
"ok",
"=",
"response",
".",
... | Parse the response and build a `scanboo_common.http_client.HttpResponse` object.
For successful responses, convert the json data into a dict.
:param response: the `requests` response
:return: [HttpResponse] response object | [
"Parse",
"the",
"response",
"and",
"build",
"a",
"scanboo_common",
".",
"http_client",
".",
"HttpResponse",
"object",
".",
"For",
"successful",
"responses",
"convert",
"the",
"json",
"data",
"into",
"a",
"dict",
"."
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L69-L87 | train | 33,154 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | HttpClient.get_all | def get_all(self, path, data=None, limit=100):
"""Encapsulates GET all requests"""
return ListResultSet(path=path, data=data or {}, limit=limit) | python | def get_all(self, path, data=None, limit=100):
"""Encapsulates GET all requests"""
return ListResultSet(path=path, data=data or {}, limit=limit) | [
"def",
"get_all",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"limit",
"=",
"100",
")",
":",
"return",
"ListResultSet",
"(",
"path",
"=",
"path",
",",
"data",
"=",
"data",
"or",
"{",
"}",
",",
"limit",
"=",
"limit",
")"
] | Encapsulates GET all requests | [
"Encapsulates",
"GET",
"all",
"requests"
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L101-L103 | train | 33,155 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | HttpClient.get | def get(self, path, data=None):
"""Encapsulates GET requests"""
data = data or {}
response = requests.get(self.url(path), params=data, headers=self.request_header())
return self.parse_response(response) | python | def get(self, path, data=None):
"""Encapsulates GET requests"""
data = data or {}
response = requests.get(self.url(path), params=data, headers=self.request_header())
return self.parse_response(response) | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
")",
":",
"data",
"=",
"data",
"or",
"{",
"}",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
"(",
"path",
")",
",",
"params",
"=",
"data",
",",
"headers",
"="... | Encapsulates GET requests | [
"Encapsulates",
"GET",
"requests"
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L105-L109 | train | 33,156 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/http_client.py | HttpClient.post | def post(self, path, data=None):
"""Encapsulates POST requests"""
data = data or {}
response = requests.post(self.url(path), data=to_json(data), headers=self.request_header())
return self.parse_response(response) | python | def post(self, path, data=None):
"""Encapsulates POST requests"""
data = data or {}
response = requests.post(self.url(path), data=to_json(data), headers=self.request_header())
return self.parse_response(response) | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
")",
":",
"data",
"=",
"data",
"or",
"{",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"url",
"(",
"path",
")",
",",
"data",
"=",
"to_json",
"(",
"data",
")"... | Encapsulates POST requests | [
"Encapsulates",
"POST",
"requests"
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L111-L115 | train | 33,157 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/data.py | MarvinData.download_file | def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024):
"""
Download file from a given url
"""
local_file_name = local_file_name if local_file_name else url.split('/')[-1]
filepath = os.path.join(cls.data_path, local_file_name)
if not os.path.exists(filepath) or force:
try:
headers = requests.head(url, allow_redirects=True).headers
length = headers.get('Content-Length')
logger.info("Starting download of {} file with {} bytes ...".format(url, length))
widgets = [
'Downloading file please wait...', progressbar.Percentage(),
' ', progressbar.Bar(),
' ', progressbar.ETA(),
' ', progressbar.FileTransferSpeed(),
]
bar = progressbar.ProgressBar(widgets=widgets, max_value=int(length) + chunk_size).start()
r = requests.get(url, stream=True)
with open(filepath, 'wb') as f:
total_chunk = 0
for chunk in r.iter_content(chunk_size):
if chunk:
f.write(chunk)
total_chunk += chunk_size
bar.update(total_chunk)
bar.finish()
except:
if os.path.exists(filepath):
os.remove(filepath)
raise
return filepath | python | def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024):
"""
Download file from a given url
"""
local_file_name = local_file_name if local_file_name else url.split('/')[-1]
filepath = os.path.join(cls.data_path, local_file_name)
if not os.path.exists(filepath) or force:
try:
headers = requests.head(url, allow_redirects=True).headers
length = headers.get('Content-Length')
logger.info("Starting download of {} file with {} bytes ...".format(url, length))
widgets = [
'Downloading file please wait...', progressbar.Percentage(),
' ', progressbar.Bar(),
' ', progressbar.ETA(),
' ', progressbar.FileTransferSpeed(),
]
bar = progressbar.ProgressBar(widgets=widgets, max_value=int(length) + chunk_size).start()
r = requests.get(url, stream=True)
with open(filepath, 'wb') as f:
total_chunk = 0
for chunk in r.iter_content(chunk_size):
if chunk:
f.write(chunk)
total_chunk += chunk_size
bar.update(total_chunk)
bar.finish()
except:
if os.path.exists(filepath):
os.remove(filepath)
raise
return filepath | [
"def",
"download_file",
"(",
"cls",
",",
"url",
",",
"local_file_name",
"=",
"None",
",",
"force",
"=",
"False",
",",
"chunk_size",
"=",
"1024",
")",
":",
"local_file_name",
"=",
"local_file_name",
"if",
"local_file_name",
"else",
"url",
".",
"split",
"(",
... | Download file from a given url | [
"Download",
"file",
"from",
"a",
"given",
"url"
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/data.py#L90-L132 | train | 33,158 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | chunks | def chunks(lst, size):
"""Yield successive n-sized chunks from lst."""
for i in xrange(0, len(lst), size):
yield lst[i:i + size] | python | def chunks(lst, size):
"""Yield successive n-sized chunks from lst."""
for i in xrange(0, len(lst), size):
yield lst[i:i + size] | [
"def",
"chunks",
"(",
"lst",
",",
"size",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"lst",
")",
",",
"size",
")",
":",
"yield",
"lst",
"[",
"i",
":",
"i",
"+",
"size",
"]"
] | Yield successive n-sized chunks from lst. | [
"Yield",
"successive",
"n",
"-",
"sized",
"chunks",
"from",
"lst",
"."
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L110-L113 | train | 33,159 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | _to_json_default | def _to_json_default(obj):
"""Helper to convert non default objects to json.
Usage:
simplejson.dumps(data, default=_to_json_default)
"""
# Datetime
if isinstance(obj, datetime.datetime):
return obj.isoformat()
# UUID
if isinstance(obj, uuid.UUID):
return str(obj)
# numpy
if hasattr(obj, 'item'):
return obj.item()
# # Enum
# if hasattr(obj, 'value'):
# return obj.value
try:
return obj.id
except Exception:
raise TypeError('{obj} is not JSON serializable'.format(obj=repr(obj))) | python | def _to_json_default(obj):
"""Helper to convert non default objects to json.
Usage:
simplejson.dumps(data, default=_to_json_default)
"""
# Datetime
if isinstance(obj, datetime.datetime):
return obj.isoformat()
# UUID
if isinstance(obj, uuid.UUID):
return str(obj)
# numpy
if hasattr(obj, 'item'):
return obj.item()
# # Enum
# if hasattr(obj, 'value'):
# return obj.value
try:
return obj.id
except Exception:
raise TypeError('{obj} is not JSON serializable'.format(obj=repr(obj))) | [
"def",
"_to_json_default",
"(",
"obj",
")",
":",
"# Datetime",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"obj",
".",
"isoformat",
"(",
")",
"# UUID",
"if",
"isinstance",
"(",
"obj",
",",
"uuid",
".",
"UUID",
... | Helper to convert non default objects to json.
Usage:
simplejson.dumps(data, default=_to_json_default) | [
"Helper",
"to",
"convert",
"non",
"default",
"objects",
"to",
"json",
"."
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L116-L141 | train | 33,160 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | _from_json_object_hook | def _from_json_object_hook(obj):
"""Converts a json string, where datetime and UUID objects were converted
into strings using the '_to_json_default', into a python object.
Usage:
simplejson.loads(data, object_hook=_from_json_object_hook)
"""
for key, value in obj.items():
# Check for datetime objects
if isinstance(value, str):
dt_result = datetime_regex.match(value)
if dt_result:
year, month, day, hour, minute, second = map(
lambda x: int(x), dt_result.groups())
obj[key] = datetime.datetime(
year, month, day, hour, minute, second)
else:
dt_result = uuid_regex.match(value)
if dt_result:
obj[key] = uuid.UUID(value)
return obj | python | def _from_json_object_hook(obj):
"""Converts a json string, where datetime and UUID objects were converted
into strings using the '_to_json_default', into a python object.
Usage:
simplejson.loads(data, object_hook=_from_json_object_hook)
"""
for key, value in obj.items():
# Check for datetime objects
if isinstance(value, str):
dt_result = datetime_regex.match(value)
if dt_result:
year, month, day, hour, minute, second = map(
lambda x: int(x), dt_result.groups())
obj[key] = datetime.datetime(
year, month, day, hour, minute, second)
else:
dt_result = uuid_regex.match(value)
if dt_result:
obj[key] = uuid.UUID(value)
return obj | [
"def",
"_from_json_object_hook",
"(",
"obj",
")",
":",
"for",
"key",
",",
"value",
"in",
"obj",
".",
"items",
"(",
")",
":",
"# Check for datetime objects",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"dt_result",
"=",
"datetime_regex",
".",
"m... | Converts a json string, where datetime and UUID objects were converted
into strings using the '_to_json_default', into a python object.
Usage:
simplejson.loads(data, object_hook=_from_json_object_hook) | [
"Converts",
"a",
"json",
"string",
"where",
"datetime",
"and",
"UUID",
"objects",
"were",
"converted",
"into",
"strings",
"using",
"the",
"_to_json_default",
"into",
"a",
"python",
"object",
"."
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L148-L169 | train | 33,161 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | check_path | def check_path(path, create=False):
"""
Check for a path on filesystem
:param path: str - path name
:param create: bool - create if do not exist
:return: bool - path exists
"""
if not os.path.exists(path):
if create:
os.makedirs(path)
return os.path.exists(path)
else:
return False
return True | python | def check_path(path, create=False):
"""
Check for a path on filesystem
:param path: str - path name
:param create: bool - create if do not exist
:return: bool - path exists
"""
if not os.path.exists(path):
if create:
os.makedirs(path)
return os.path.exists(path)
else:
return False
return True | [
"def",
"check_path",
"(",
"path",
",",
"create",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"create",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"exists... | Check for a path on filesystem
:param path: str - path name
:param create: bool - create if do not exist
:return: bool - path exists | [
"Check",
"for",
"a",
"path",
"on",
"filesystem"
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L245-L260 | train | 33,162 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/utils.py | url_encode | def url_encode(url):
"""
Convert special characters using %xx escape.
:param url: str
:return: str - encoded url
"""
if isinstance(url, text_type):
url = url.encode('utf8')
return quote(url, ':/%?&=') | python | def url_encode(url):
"""
Convert special characters using %xx escape.
:param url: str
:return: str - encoded url
"""
if isinstance(url, text_type):
url = url.encode('utf8')
return quote(url, ':/%?&=') | [
"def",
"url_encode",
"(",
"url",
")",
":",
"if",
"isinstance",
"(",
"url",
",",
"text_type",
")",
":",
"url",
"=",
"url",
".",
"encode",
"(",
"'utf8'",
")",
"return",
"quote",
"(",
"url",
",",
"':/%?&='",
")"
] | Convert special characters using %xx escape.
:param url: str
:return: str - encoded url | [
"Convert",
"special",
"characters",
"using",
"%xx",
"escape",
"."
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/utils.py#L286-L295 | train | 33,163 |
vmware/column | column/api/controller/run_controller.py | Run.get | def get(self, id):
"""Get run by id"""
run = self.backend_store.get_run(id)
if not run:
return abort(http_client.NOT_FOUND,
message="Run {} doesn't exist".format(id))
return run_model.format_response(run) | python | def get(self, id):
"""Get run by id"""
run = self.backend_store.get_run(id)
if not run:
return abort(http_client.NOT_FOUND,
message="Run {} doesn't exist".format(id))
return run_model.format_response(run) | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"run",
"=",
"self",
".",
"backend_store",
".",
"get_run",
"(",
"id",
")",
"if",
"not",
"run",
":",
"return",
"abort",
"(",
"http_client",
".",
"NOT_FOUND",
",",
"message",
"=",
"\"Run {} doesn't exist\"",
... | Get run by id | [
"Get",
"run",
"by",
"id"
] | 86c72b29e8c1ec58474bd39757f18a3834a446ef | https://github.com/vmware/column/blob/86c72b29e8c1ec58474bd39757f18a3834a446ef/column/api/controller/run_controller.py#L62-L68 | train | 33,164 |
vmware/column | column/api/controller/run_controller.py | Run.delete | def delete(self, id):
"""Delete run by id"""
run = self.backend_store.get_run(id)
if not run:
return abort(http_client.NOT_FOUND,
message="Run {} doesn't exist".format(id))
if not self.manager.delete_run(run):
return abort(http_client.BAD_REQUEST,
message="Failed to find the task queue "
"manager of run {}.".format(id))
return '', http_client.NO_CONTENT | python | def delete(self, id):
"""Delete run by id"""
run = self.backend_store.get_run(id)
if not run:
return abort(http_client.NOT_FOUND,
message="Run {} doesn't exist".format(id))
if not self.manager.delete_run(run):
return abort(http_client.BAD_REQUEST,
message="Failed to find the task queue "
"manager of run {}.".format(id))
return '', http_client.NO_CONTENT | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"run",
"=",
"self",
".",
"backend_store",
".",
"get_run",
"(",
"id",
")",
"if",
"not",
"run",
":",
"return",
"abort",
"(",
"http_client",
".",
"NOT_FOUND",
",",
"message",
"=",
"\"Run {} doesn't exist\""... | Delete run by id | [
"Delete",
"run",
"by",
"id"
] | 86c72b29e8c1ec58474bd39757f18a3834a446ef | https://github.com/vmware/column/blob/86c72b29e8c1ec58474bd39757f18a3834a446ef/column/api/controller/run_controller.py#L70-L80 | train | 33,165 |
vmware/column | column/api/controller/run_controller.py | RunList.get | def get(self):
"""Get run list"""
LOG.info('Returning all ansible runs')
response = []
for run in self.backend_store.list_runs():
response.append(run_model.format_response(run))
return response | python | def get(self):
"""Get run list"""
LOG.info('Returning all ansible runs')
response = []
for run in self.backend_store.list_runs():
response.append(run_model.format_response(run))
return response | [
"def",
"get",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"'Returning all ansible runs'",
")",
"response",
"=",
"[",
"]",
"for",
"run",
"in",
"self",
".",
"backend_store",
".",
"list_runs",
"(",
")",
":",
"response",
".",
"append",
"(",
"run_model",
... | Get run list | [
"Get",
"run",
"list"
] | 86c72b29e8c1ec58474bd39757f18a3834a446ef | https://github.com/vmware/column/blob/86c72b29e8c1ec58474bd39757f18a3834a446ef/column/api/controller/run_controller.py#L96-L102 | train | 33,166 |
vmware/column | column/api/controller/run_controller.py | RunList.post | def post(self):
"""Trigger a new run"""
run_payload = utils.uni_to_str(json.loads(request.get_data()))
run_payload['id'] = str(uuid.uuid4())
LOG.info('Triggering new ansible run %s', run_payload['id'])
run = self.manager.create_run(run_payload)
return run_model.format_response(run), http_client.CREATED | python | def post(self):
"""Trigger a new run"""
run_payload = utils.uni_to_str(json.loads(request.get_data()))
run_payload['id'] = str(uuid.uuid4())
LOG.info('Triggering new ansible run %s', run_payload['id'])
run = self.manager.create_run(run_payload)
return run_model.format_response(run), http_client.CREATED | [
"def",
"post",
"(",
"self",
")",
":",
"run_payload",
"=",
"utils",
".",
"uni_to_str",
"(",
"json",
".",
"loads",
"(",
"request",
".",
"get_data",
"(",
")",
")",
")",
"run_payload",
"[",
"'id'",
"]",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
... | Trigger a new run | [
"Trigger",
"a",
"new",
"run"
] | 86c72b29e8c1ec58474bd39757f18a3834a446ef | https://github.com/vmware/column/blob/86c72b29e8c1ec58474bd39757f18a3834a446ef/column/api/controller/run_controller.py#L105-L111 | train | 33,167 |
marvin-ai/marvin-python-toolbox | marvin_python_toolbox/common/data_source_provider.py | get_spark_session | def get_spark_session(enable_hive=False, app_name='marvin-engine', configs=[]):
"""Return a Spark Session object"""
# Prepare spark context to be used
import findspark
findspark.init()
from pyspark.sql import SparkSession
# prepare spark sesseion to be returned
spark = SparkSession.builder
spark = spark.appName(app_name)
spark = spark.enableHiveSupport() if enable_hive else spark
# if has configs
for config in configs:
spark = spark.config(config)
return spark.getOrCreate() | python | def get_spark_session(enable_hive=False, app_name='marvin-engine', configs=[]):
"""Return a Spark Session object"""
# Prepare spark context to be used
import findspark
findspark.init()
from pyspark.sql import SparkSession
# prepare spark sesseion to be returned
spark = SparkSession.builder
spark = spark.appName(app_name)
spark = spark.enableHiveSupport() if enable_hive else spark
# if has configs
for config in configs:
spark = spark.config(config)
return spark.getOrCreate() | [
"def",
"get_spark_session",
"(",
"enable_hive",
"=",
"False",
",",
"app_name",
"=",
"'marvin-engine'",
",",
"configs",
"=",
"[",
"]",
")",
":",
"# Prepare spark context to be used",
"import",
"findspark",
"findspark",
".",
"init",
"(",
")",
"from",
"pyspark",
".... | Return a Spark Session object | [
"Return",
"a",
"Spark",
"Session",
"object"
] | 7c95cb2f9698b989150ab94c1285f3a9eaaba423 | https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/data_source_provider.py#L25-L43 | train | 33,168 |
Erotemic/timerit | timerit/core.py | chunks | def chunks(seq, size):
""" simple two-line alternative to `ubelt.chunks` """
return (seq[pos:pos + size] for pos in range(0, len(seq), size)) | python | def chunks(seq, size):
""" simple two-line alternative to `ubelt.chunks` """
return (seq[pos:pos + size] for pos in range(0, len(seq), size)) | [
"def",
"chunks",
"(",
"seq",
",",
"size",
")",
":",
"return",
"(",
"seq",
"[",
"pos",
":",
"pos",
"+",
"size",
"]",
"for",
"pos",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"seq",
")",
",",
"size",
")",
")"
] | simple two-line alternative to `ubelt.chunks` | [
"simple",
"two",
"-",
"line",
"alternative",
"to",
"ubelt",
".",
"chunks"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L99-L101 | train | 33,169 |
Erotemic/timerit | timerit/core.py | _trychar | def _trychar(char, fallback, asciimode=None): # nocover
"""
Logic from IPython timeit to handle terminals that cant show mu
Args:
char (str): character, typically unicode, to try to use
fallback (str): ascii character to use if stdout cannot encode char
asciimode (bool): if True, always use fallback
Example:
>>> char = _trychar('µs', 'us')
>>> print('char = {}'.format(char))
>>> assert _trychar('µs', 'us', asciimode=True) == 'us'
"""
if asciimode is True:
# If we request ascii mode simply return it
return fallback
if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: # pragma: nobranch
try:
char.encode(sys.stdout.encoding)
except Exception: # nocover
pass
else:
return char
return fallback | python | def _trychar(char, fallback, asciimode=None): # nocover
"""
Logic from IPython timeit to handle terminals that cant show mu
Args:
char (str): character, typically unicode, to try to use
fallback (str): ascii character to use if stdout cannot encode char
asciimode (bool): if True, always use fallback
Example:
>>> char = _trychar('µs', 'us')
>>> print('char = {}'.format(char))
>>> assert _trychar('µs', 'us', asciimode=True) == 'us'
"""
if asciimode is True:
# If we request ascii mode simply return it
return fallback
if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: # pragma: nobranch
try:
char.encode(sys.stdout.encoding)
except Exception: # nocover
pass
else:
return char
return fallback | [
"def",
"_trychar",
"(",
"char",
",",
"fallback",
",",
"asciimode",
"=",
"None",
")",
":",
"# nocover",
"if",
"asciimode",
"is",
"True",
":",
"# If we request ascii mode simply return it",
"return",
"fallback",
"if",
"hasattr",
"(",
"sys",
".",
"stdout",
",",
"... | Logic from IPython timeit to handle terminals that cant show mu
Args:
char (str): character, typically unicode, to try to use
fallback (str): ascii character to use if stdout cannot encode char
asciimode (bool): if True, always use fallback
Example:
>>> char = _trychar('µs', 'us')
>>> print('char = {}'.format(char))
>>> assert _trychar('µs', 'us', asciimode=True) == 'us' | [
"Logic",
"from",
"IPython",
"timeit",
"to",
"handle",
"terminals",
"that",
"cant",
"show",
"mu"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L518-L543 | train | 33,170 |
Erotemic/timerit | timerit/core.py | Timer.tic | def tic(self):
""" starts the timer """
if self.verbose:
self.flush()
self.write('\ntic(%r)' % self.label)
if self.newline:
self.write('\n')
self.flush()
self.tstart = self._time()
return self | python | def tic(self):
""" starts the timer """
if self.verbose:
self.flush()
self.write('\ntic(%r)' % self.label)
if self.newline:
self.write('\n')
self.flush()
self.tstart = self._time()
return self | [
"def",
"tic",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
":",
"self",
".",
"flush",
"(",
")",
"self",
".",
"write",
"(",
"'\\ntic(%r)'",
"%",
"self",
".",
"label",
")",
"if",
"self",
".",
"newline",
":",
"self",
".",
"write",
"(",
"'\\n... | starts the timer | [
"starts",
"the",
"timer"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L70-L79 | train | 33,171 |
Erotemic/timerit | timerit/core.py | Timer.toc | def toc(self):
""" stops the timer """
elapsed = self._time() - self.tstart
if self.verbose:
self.write('...toc(%r)=%.4fs\n' % (self.label, elapsed))
self.flush()
return elapsed | python | def toc(self):
""" stops the timer """
elapsed = self._time() - self.tstart
if self.verbose:
self.write('...toc(%r)=%.4fs\n' % (self.label, elapsed))
self.flush()
return elapsed | [
"def",
"toc",
"(",
"self",
")",
":",
"elapsed",
"=",
"self",
".",
"_time",
"(",
")",
"-",
"self",
".",
"tstart",
"if",
"self",
".",
"verbose",
":",
"self",
".",
"write",
"(",
"'...toc(%r)=%.4fs\\n'",
"%",
"(",
"self",
".",
"label",
",",
"elapsed",
... | stops the timer | [
"stops",
"the",
"timer"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L81-L87 | train | 33,172 |
Erotemic/timerit | timerit/core.py | Timerit.reset | def reset(self, label=None):
"""
clears all measurements, allowing the object to be reused
Args:
label (str, optional) : optionally change the label
Example:
>>> from timerit import Timerit
>>> import math
>>> ti = Timerit(num=10, unit='us', verbose=True)
>>> _ = ti.reset(label='10!').call(math.factorial, 10)
Timed best=...s, mean=...s for 10!
>>> _ = ti.reset(label='20!').call(math.factorial, 20)
Timed best=...s, mean=...s for 20!
>>> _ = ti.reset().call(math.factorial, 20)
Timed best=...s, mean=...s for 20!
"""
if label:
self.label = label
self.times = []
self.n_loops = None
self.total_time = None
return self | python | def reset(self, label=None):
"""
clears all measurements, allowing the object to be reused
Args:
label (str, optional) : optionally change the label
Example:
>>> from timerit import Timerit
>>> import math
>>> ti = Timerit(num=10, unit='us', verbose=True)
>>> _ = ti.reset(label='10!').call(math.factorial, 10)
Timed best=...s, mean=...s for 10!
>>> _ = ti.reset(label='20!').call(math.factorial, 20)
Timed best=...s, mean=...s for 20!
>>> _ = ti.reset().call(math.factorial, 20)
Timed best=...s, mean=...s for 20!
"""
if label:
self.label = label
self.times = []
self.n_loops = None
self.total_time = None
return self | [
"def",
"reset",
"(",
"self",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
":",
"self",
".",
"label",
"=",
"label",
"self",
".",
"times",
"=",
"[",
"]",
"self",
".",
"n_loops",
"=",
"None",
"self",
".",
"total_time",
"=",
"None",
"return",
... | clears all measurements, allowing the object to be reused
Args:
label (str, optional) : optionally change the label
Example:
>>> from timerit import Timerit
>>> import math
>>> ti = Timerit(num=10, unit='us', verbose=True)
>>> _ = ti.reset(label='10!').call(math.factorial, 10)
Timed best=...s, mean=...s for 10!
>>> _ = ti.reset(label='20!').call(math.factorial, 20)
Timed best=...s, mean=...s for 20!
>>> _ = ti.reset().call(math.factorial, 20)
Timed best=...s, mean=...s for 20! | [
"clears",
"all",
"measurements",
"allowing",
"the",
"object",
"to",
"be",
"reused"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L180-L203 | train | 33,173 |
Erotemic/timerit | timerit/core.py | Timerit.call | def call(self, func, *args, **kwargs):
"""
Alternative way to time a simple function call using condensed syntax.
Returns:
self (timerit.Timerit): Use `min`, or `mean` to get a scalar. Use
`print` to output a report to stdout.
Example:
>>> import math
>>> time = Timerit(num=10).call(math.factorial, 50).min()
>>> assert time > 0
"""
for timer in self:
with timer:
func(*args, **kwargs)
return self | python | def call(self, func, *args, **kwargs):
"""
Alternative way to time a simple function call using condensed syntax.
Returns:
self (timerit.Timerit): Use `min`, or `mean` to get a scalar. Use
`print` to output a report to stdout.
Example:
>>> import math
>>> time = Timerit(num=10).call(math.factorial, 50).min()
>>> assert time > 0
"""
for timer in self:
with timer:
func(*args, **kwargs)
return self | [
"def",
"call",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"timer",
"in",
"self",
":",
"with",
"timer",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | Alternative way to time a simple function call using condensed syntax.
Returns:
self (timerit.Timerit): Use `min`, or `mean` to get a scalar. Use
`print` to output a report to stdout.
Example:
>>> import math
>>> time = Timerit(num=10).call(math.factorial, 50).min()
>>> assert time > 0 | [
"Alternative",
"way",
"to",
"time",
"a",
"simple",
"function",
"call",
"using",
"condensed",
"syntax",
"."
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L205-L221 | train | 33,174 |
Erotemic/timerit | timerit/core.py | Timerit.mean | def mean(self):
"""
The mean of the best results of each trial.
Returns:
float: mean of measured seconds
Note:
This is typically less informative than simply looking at the min.
It is recommended to use min as the expectation value rather than
mean in most cases.
Example:
>>> import math
>>> self = Timerit(num=10, verbose=0)
>>> self.call(math.factorial, 50)
>>> assert self.mean() > 0
"""
chunk_iter = chunks(self.times, self.bestof)
times = list(map(min, chunk_iter))
mean = sum(times) / len(times)
return mean | python | def mean(self):
"""
The mean of the best results of each trial.
Returns:
float: mean of measured seconds
Note:
This is typically less informative than simply looking at the min.
It is recommended to use min as the expectation value rather than
mean in most cases.
Example:
>>> import math
>>> self = Timerit(num=10, verbose=0)
>>> self.call(math.factorial, 50)
>>> assert self.mean() > 0
"""
chunk_iter = chunks(self.times, self.bestof)
times = list(map(min, chunk_iter))
mean = sum(times) / len(times)
return mean | [
"def",
"mean",
"(",
"self",
")",
":",
"chunk_iter",
"=",
"chunks",
"(",
"self",
".",
"times",
",",
"self",
".",
"bestof",
")",
"times",
"=",
"list",
"(",
"map",
"(",
"min",
",",
"chunk_iter",
")",
")",
"mean",
"=",
"sum",
"(",
"times",
")",
"/",
... | The mean of the best results of each trial.
Returns:
float: mean of measured seconds
Note:
This is typically less informative than simply looking at the min.
It is recommended to use min as the expectation value rather than
mean in most cases.
Example:
>>> import math
>>> self = Timerit(num=10, verbose=0)
>>> self.call(math.factorial, 50)
>>> assert self.mean() > 0 | [
"The",
"mean",
"of",
"the",
"best",
"results",
"of",
"each",
"trial",
"."
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L289-L310 | train | 33,175 |
Erotemic/timerit | timerit/core.py | Timerit.std | def std(self):
"""
The standard deviation of the best results of each trial.
Returns:
float: standard deviation of measured seconds
Note:
As mentioned in the timeit source code, the standard deviation is
not often useful. Typically the minimum value is most informative.
Example:
>>> import math
>>> self = Timerit(num=10, verbose=1)
>>> self.call(math.factorial, 50)
>>> assert self.std() >= 0
"""
import math
chunk_iter = chunks(self.times, self.bestof)
times = list(map(min, chunk_iter))
mean = sum(times) / len(times)
std = math.sqrt(sum((t - mean) ** 2 for t in times) / len(times))
return std | python | def std(self):
"""
The standard deviation of the best results of each trial.
Returns:
float: standard deviation of measured seconds
Note:
As mentioned in the timeit source code, the standard deviation is
not often useful. Typically the minimum value is most informative.
Example:
>>> import math
>>> self = Timerit(num=10, verbose=1)
>>> self.call(math.factorial, 50)
>>> assert self.std() >= 0
"""
import math
chunk_iter = chunks(self.times, self.bestof)
times = list(map(min, chunk_iter))
mean = sum(times) / len(times)
std = math.sqrt(sum((t - mean) ** 2 for t in times) / len(times))
return std | [
"def",
"std",
"(",
"self",
")",
":",
"import",
"math",
"chunk_iter",
"=",
"chunks",
"(",
"self",
".",
"times",
",",
"self",
".",
"bestof",
")",
"times",
"=",
"list",
"(",
"map",
"(",
"min",
",",
"chunk_iter",
")",
")",
"mean",
"=",
"sum",
"(",
"t... | The standard deviation of the best results of each trial.
Returns:
float: standard deviation of measured seconds
Note:
As mentioned in the timeit source code, the standard deviation is
not often useful. Typically the minimum value is most informative.
Example:
>>> import math
>>> self = Timerit(num=10, verbose=1)
>>> self.call(math.factorial, 50)
>>> assert self.std() >= 0 | [
"The",
"standard",
"deviation",
"of",
"the",
"best",
"results",
"of",
"each",
"trial",
"."
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L312-L334 | train | 33,176 |
Erotemic/timerit | timerit/core.py | Timerit.report | def report(self, verbose=1):
"""
Creates a human readable report
Args:
verbose (int): verbosity level. Either 1, 2, or 3.
Returns:
str: the report
SeeAlso:
timerit.Timerit.print
Example:
>>> import math
>>> ti = Timerit(num=1).call(math.factorial, 5)
>>> print(ti.report(verbose=1))
Timed best=...s, mean=...s
"""
lines = []
if verbose >= 2:
# use a multi-line format for high verbosity
lines.append(self._status_line(tense='past'))
if verbose >= 3:
unit, mag = _choose_unit(self.total_time, self.unit,
self._asciimode)
lines.append(' body took: {total:.{pr}{t}} {unit}'.format(
total=self.total_time / mag,
t=self._precision_type,
pr=self._precision, unit=unit))
lines.append(' time per loop: {}'.format(self._seconds_str()))
else:
# use a single-line format for low verbosity
line = 'Timed ' + self._seconds_str()
if self.label:
line += ' for ' + self.label
lines.append(line)
text = '\n'.join(lines)
return text | python | def report(self, verbose=1):
"""
Creates a human readable report
Args:
verbose (int): verbosity level. Either 1, 2, or 3.
Returns:
str: the report
SeeAlso:
timerit.Timerit.print
Example:
>>> import math
>>> ti = Timerit(num=1).call(math.factorial, 5)
>>> print(ti.report(verbose=1))
Timed best=...s, mean=...s
"""
lines = []
if verbose >= 2:
# use a multi-line format for high verbosity
lines.append(self._status_line(tense='past'))
if verbose >= 3:
unit, mag = _choose_unit(self.total_time, self.unit,
self._asciimode)
lines.append(' body took: {total:.{pr}{t}} {unit}'.format(
total=self.total_time / mag,
t=self._precision_type,
pr=self._precision, unit=unit))
lines.append(' time per loop: {}'.format(self._seconds_str()))
else:
# use a single-line format for low verbosity
line = 'Timed ' + self._seconds_str()
if self.label:
line += ' for ' + self.label
lines.append(line)
text = '\n'.join(lines)
return text | [
"def",
"report",
"(",
"self",
",",
"verbose",
"=",
"1",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"verbose",
">=",
"2",
":",
"# use a multi-line format for high verbosity",
"lines",
".",
"append",
"(",
"self",
".",
"_status_line",
"(",
"tense",
"=",
"'past'"... | Creates a human readable report
Args:
verbose (int): verbosity level. Either 1, 2, or 3.
Returns:
str: the report
SeeAlso:
timerit.Timerit.print
Example:
>>> import math
>>> ti = Timerit(num=1).call(math.factorial, 5)
>>> print(ti.report(verbose=1))
Timed best=...s, mean=...s | [
"Creates",
"a",
"human",
"readable",
"report"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L383-L421 | train | 33,177 |
Erotemic/timerit | setup.py | parse_description | def parse_description():
"""
Parse the description in the README file
pandoc --from=markdown --to=rst --output=README.rst README.md
CommandLine:
python -c "import setup; print(setup.parse_description())"
"""
from os.path import dirname, join, exists
readme_fpath = join(dirname(__file__), 'README.rst')
# This breaks on pip install, so check that it exists.
if exists(readme_fpath):
textlines = []
with open(readme_fpath, 'r') as f:
textlines = f.readlines()
text = ''.join(textlines).strip()
return text
return '' | python | def parse_description():
"""
Parse the description in the README file
pandoc --from=markdown --to=rst --output=README.rst README.md
CommandLine:
python -c "import setup; print(setup.parse_description())"
"""
from os.path import dirname, join, exists
readme_fpath = join(dirname(__file__), 'README.rst')
# This breaks on pip install, so check that it exists.
if exists(readme_fpath):
textlines = []
with open(readme_fpath, 'r') as f:
textlines = f.readlines()
text = ''.join(textlines).strip()
return text
return '' | [
"def",
"parse_description",
"(",
")",
":",
"from",
"os",
".",
"path",
"import",
"dirname",
",",
"join",
",",
"exists",
"readme_fpath",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"'README.rst'",
")",
"# This breaks on pip install, so check that it exis... | Parse the description in the README file
pandoc --from=markdown --to=rst --output=README.rst README.md
CommandLine:
python -c "import setup; print(setup.parse_description())" | [
"Parse",
"the",
"description",
"in",
"the",
"README",
"file"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/setup.py#L67-L85 | train | 33,178 |
Erotemic/timerit | setup.py | parse_requirements | def parse_requirements(fname='requirements.txt'):
"""
Parse the package dependencies listed in a requirements file but strips
specific versioning information.
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
from os.path import dirname, join, exists
import re
require_fpath = join(dirname(__file__), fname)
# This breaks on pip install, so check that it exists.
if exists(require_fpath):
with open(require_fpath, 'r') as f:
packages = []
for line in f.readlines():
line = line.strip()
if line and not line.startswith('#'):
if line.startswith('-e '):
package = line.split('#egg=')[1]
packages.append(package)
else:
pat = '|'.join(['>', '>=', '=='])
package = re.split(pat, line)[0]
packages.append(package)
return packages
return [] | python | def parse_requirements(fname='requirements.txt'):
"""
Parse the package dependencies listed in a requirements file but strips
specific versioning information.
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
from os.path import dirname, join, exists
import re
require_fpath = join(dirname(__file__), fname)
# This breaks on pip install, so check that it exists.
if exists(require_fpath):
with open(require_fpath, 'r') as f:
packages = []
for line in f.readlines():
line = line.strip()
if line and not line.startswith('#'):
if line.startswith('-e '):
package = line.split('#egg=')[1]
packages.append(package)
else:
pat = '|'.join(['>', '>=', '=='])
package = re.split(pat, line)[0]
packages.append(package)
return packages
return [] | [
"def",
"parse_requirements",
"(",
"fname",
"=",
"'requirements.txt'",
")",
":",
"from",
"os",
".",
"path",
"import",
"dirname",
",",
"join",
",",
"exists",
"import",
"re",
"require_fpath",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"fname",
")... | Parse the package dependencies listed in a requirements file but strips
specific versioning information.
CommandLine:
python -c "import setup; print(setup.parse_requirements())" | [
"Parse",
"the",
"package",
"dependencies",
"listed",
"in",
"a",
"requirements",
"file",
"but",
"strips",
"specific",
"versioning",
"information",
"."
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/setup.py#L88-L114 | train | 33,179 |
shoyer/cyordereddict | python3/cyordereddict/benchmark/benchmark.py | benchmark | def benchmark(repeat=10):
"""Benchmark cyordereddict.OrderedDict against collections.OrderedDict
"""
columns = ['Test', 'Code', 'Ratio (stdlib / cython)']
res = _calculate_benchmarks(repeat)
try:
from tabulate import tabulate
print(tabulate(res, columns, 'rst'))
except ImportError:
print(columns)
print(res) | python | def benchmark(repeat=10):
"""Benchmark cyordereddict.OrderedDict against collections.OrderedDict
"""
columns = ['Test', 'Code', 'Ratio (stdlib / cython)']
res = _calculate_benchmarks(repeat)
try:
from tabulate import tabulate
print(tabulate(res, columns, 'rst'))
except ImportError:
print(columns)
print(res) | [
"def",
"benchmark",
"(",
"repeat",
"=",
"10",
")",
":",
"columns",
"=",
"[",
"'Test'",
",",
"'Code'",
",",
"'Ratio (stdlib / cython)'",
"]",
"res",
"=",
"_calculate_benchmarks",
"(",
"repeat",
")",
"try",
":",
"from",
"tabulate",
"import",
"tabulate",
"print... | Benchmark cyordereddict.OrderedDict against collections.OrderedDict | [
"Benchmark",
"cyordereddict",
".",
"OrderedDict",
"against",
"collections",
".",
"OrderedDict"
] | 248e3e8616441554c87175820204e269a3afb32a | https://github.com/shoyer/cyordereddict/blob/248e3e8616441554c87175820204e269a3afb32a/python3/cyordereddict/benchmark/benchmark.py#L47-L57 | train | 33,180 |
ambitioninc/django-manager-utils | manager_utils/upsert2.py | _get_update_fields | def _get_update_fields(model, uniques, to_update):
"""
Get the fields to be updated in an upsert.
Always exclude auto_now_add, auto_created fields, and unique fields in an update
"""
fields = {
field.attname: field
for field in model._meta.fields
}
if to_update is None:
to_update = [
field.attname for field in model._meta.fields
]
to_update = [
attname for attname in to_update
if (attname not in uniques
and not getattr(fields[attname], 'auto_now_add', False)
and not fields[attname].auto_created)
]
return to_update | python | def _get_update_fields(model, uniques, to_update):
"""
Get the fields to be updated in an upsert.
Always exclude auto_now_add, auto_created fields, and unique fields in an update
"""
fields = {
field.attname: field
for field in model._meta.fields
}
if to_update is None:
to_update = [
field.attname for field in model._meta.fields
]
to_update = [
attname for attname in to_update
if (attname not in uniques
and not getattr(fields[attname], 'auto_now_add', False)
and not fields[attname].auto_created)
]
return to_update | [
"def",
"_get_update_fields",
"(",
"model",
",",
"uniques",
",",
"to_update",
")",
":",
"fields",
"=",
"{",
"field",
".",
"attname",
":",
"field",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"fields",
"}",
"if",
"to_update",
"is",
"None",
":",
"to... | Get the fields to be updated in an upsert.
Always exclude auto_now_add, auto_created fields, and unique fields in an update | [
"Get",
"the",
"fields",
"to",
"be",
"updated",
"in",
"an",
"upsert",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/upsert2.py#L38-L61 | train | 33,181 |
ambitioninc/django-manager-utils | manager_utils/upsert2.py | _fill_auto_fields | def _fill_auto_fields(model, values):
"""
Given a list of models, fill in auto_now and auto_now_add fields
for upserts. Since django manager utils passes Django's ORM, these values
have to be automatically constructed
"""
auto_field_names = [
f.attname
for f in model._meta.fields
if getattr(f, 'auto_now', False) or getattr(f, 'auto_now_add', False)
]
now = timezone.now()
for value in values:
for f in auto_field_names:
setattr(value, f, now)
return values | python | def _fill_auto_fields(model, values):
"""
Given a list of models, fill in auto_now and auto_now_add fields
for upserts. Since django manager utils passes Django's ORM, these values
have to be automatically constructed
"""
auto_field_names = [
f.attname
for f in model._meta.fields
if getattr(f, 'auto_now', False) or getattr(f, 'auto_now_add', False)
]
now = timezone.now()
for value in values:
for f in auto_field_names:
setattr(value, f, now)
return values | [
"def",
"_fill_auto_fields",
"(",
"model",
",",
"values",
")",
":",
"auto_field_names",
"=",
"[",
"f",
".",
"attname",
"for",
"f",
"in",
"model",
".",
"_meta",
".",
"fields",
"if",
"getattr",
"(",
"f",
",",
"'auto_now'",
",",
"False",
")",
"or",
"getatt... | Given a list of models, fill in auto_now and auto_now_add fields
for upserts. Since django manager utils passes Django's ORM, these values
have to be automatically constructed | [
"Given",
"a",
"list",
"of",
"models",
"fill",
"in",
"auto_now",
"and",
"auto_now_add",
"fields",
"for",
"upserts",
".",
"Since",
"django",
"manager",
"utils",
"passes",
"Django",
"s",
"ORM",
"these",
"values",
"have",
"to",
"be",
"automatically",
"constructed"... | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/upsert2.py#L64-L80 | train | 33,182 |
ambitioninc/django-manager-utils | manager_utils/upsert2.py | _sort_by_unique_fields | def _sort_by_unique_fields(model, model_objs, unique_fields):
"""
Sort a list of models by their unique fields.
Sorting models in an upsert greatly reduces the chances of deadlock
when doing concurrent upserts
"""
unique_fields = [
field for field in model._meta.fields
if field.attname in unique_fields
]
def sort_key(model_obj):
return tuple(
field.get_db_prep_save(getattr(model_obj, field.attname),
connection)
for field in unique_fields
)
return sorted(model_objs, key=sort_key) | python | def _sort_by_unique_fields(model, model_objs, unique_fields):
"""
Sort a list of models by their unique fields.
Sorting models in an upsert greatly reduces the chances of deadlock
when doing concurrent upserts
"""
unique_fields = [
field for field in model._meta.fields
if field.attname in unique_fields
]
def sort_key(model_obj):
return tuple(
field.get_db_prep_save(getattr(model_obj, field.attname),
connection)
for field in unique_fields
)
return sorted(model_objs, key=sort_key) | [
"def",
"_sort_by_unique_fields",
"(",
"model",
",",
"model_objs",
",",
"unique_fields",
")",
":",
"unique_fields",
"=",
"[",
"field",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"fields",
"if",
"field",
".",
"attname",
"in",
"unique_fields",
"]",
"def"... | Sort a list of models by their unique fields.
Sorting models in an upsert greatly reduces the chances of deadlock
when doing concurrent upserts | [
"Sort",
"a",
"list",
"of",
"models",
"by",
"their",
"unique",
"fields",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/upsert2.py#L83-L101 | train | 33,183 |
ambitioninc/django-manager-utils | manager_utils/upsert2.py | _fetch | def _fetch(
queryset, model_objs, unique_fields, update_fields, returning, sync,
ignore_duplicate_updates=True, return_untouched=False
):
"""
Perfom the upsert and do an optional sync operation
"""
model = queryset.model
if (return_untouched or sync) and returning is not True:
returning = set(returning) if returning else set()
returning.add(model._meta.pk.name)
upserted = []
deleted = []
# We must return untouched rows when doing a sync operation
return_untouched = True if sync else return_untouched
if model_objs:
sql, sql_args = _get_upsert_sql(queryset, model_objs, unique_fields, update_fields, returning,
ignore_duplicate_updates=ignore_duplicate_updates,
return_untouched=return_untouched)
with connection.cursor() as cursor:
cursor.execute(sql, sql_args)
if cursor.description:
nt_result = namedtuple('Result', [col[0] for col in cursor.description])
upserted = [nt_result(*row) for row in cursor.fetchall()]
pk_field = model._meta.pk.name
if sync:
orig_ids = queryset.values_list(pk_field, flat=True)
deleted = set(orig_ids) - {getattr(r, pk_field) for r in upserted}
model.objects.filter(pk__in=deleted).delete()
nt_deleted_result = namedtuple('DeletedResult', [model._meta.pk.name, 'status_'])
return UpsertResult(
upserted + [nt_deleted_result(**{pk_field: d, 'status_': 'd'}) for d in deleted]
) | python | def _fetch(
queryset, model_objs, unique_fields, update_fields, returning, sync,
ignore_duplicate_updates=True, return_untouched=False
):
"""
Perfom the upsert and do an optional sync operation
"""
model = queryset.model
if (return_untouched or sync) and returning is not True:
returning = set(returning) if returning else set()
returning.add(model._meta.pk.name)
upserted = []
deleted = []
# We must return untouched rows when doing a sync operation
return_untouched = True if sync else return_untouched
if model_objs:
sql, sql_args = _get_upsert_sql(queryset, model_objs, unique_fields, update_fields, returning,
ignore_duplicate_updates=ignore_duplicate_updates,
return_untouched=return_untouched)
with connection.cursor() as cursor:
cursor.execute(sql, sql_args)
if cursor.description:
nt_result = namedtuple('Result', [col[0] for col in cursor.description])
upserted = [nt_result(*row) for row in cursor.fetchall()]
pk_field = model._meta.pk.name
if sync:
orig_ids = queryset.values_list(pk_field, flat=True)
deleted = set(orig_ids) - {getattr(r, pk_field) for r in upserted}
model.objects.filter(pk__in=deleted).delete()
nt_deleted_result = namedtuple('DeletedResult', [model._meta.pk.name, 'status_'])
return UpsertResult(
upserted + [nt_deleted_result(**{pk_field: d, 'status_': 'd'}) for d in deleted]
) | [
"def",
"_fetch",
"(",
"queryset",
",",
"model_objs",
",",
"unique_fields",
",",
"update_fields",
",",
"returning",
",",
"sync",
",",
"ignore_duplicate_updates",
"=",
"True",
",",
"return_untouched",
"=",
"False",
")",
":",
"model",
"=",
"queryset",
".",
"model... | Perfom the upsert and do an optional sync operation | [
"Perfom",
"the",
"upsert",
"and",
"do",
"an",
"optional",
"sync",
"operation"
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/upsert2.py#L252-L288 | train | 33,184 |
ambitioninc/django-manager-utils | manager_utils/upsert2.py | upsert | def upsert(
queryset, model_objs, unique_fields,
update_fields=None, returning=False, sync=False,
ignore_duplicate_updates=True,
return_untouched=False
):
"""
Perform a bulk upsert on a table, optionally syncing the results.
Args:
queryset (Model|QuerySet): A model or a queryset that defines the collection to sync
model_objs (List[Model]): A list of Django models to sync. All models in this list
will be bulk upserted and any models not in the table (or queryset) will be deleted
if sync=True.
unique_fields (List[str]): A list of fields that define the uniqueness of the model. The
model must have a unique constraint on these fields
update_fields (List[str], default=None): A list of fields to update whenever objects
already exist. If an empty list is provided, it is equivalent to doing a bulk
insert on the objects that don't exist. If `None`, all fields will be updated.
returning (bool|List[str]): If True, returns all fields. If a list, only returns
fields in the list
sync (bool, default=False): Perform a sync operation on the queryset
ignore_duplicate_updates (bool, default=False): Don't perform an update if the row is
a duplicate.
return_untouched (bool, default=False): Return untouched rows by the operation
"""
queryset = queryset if isinstance(queryset, models.QuerySet) else queryset.objects.all()
model = queryset.model
# Populate automatically generated fields in the rows like date times
_fill_auto_fields(model, model_objs)
# Sort the rows to reduce the chances of deadlock during concurrent upserts
model_objs = _sort_by_unique_fields(model, model_objs, unique_fields)
update_fields = _get_update_fields(model, unique_fields, update_fields)
return _fetch(queryset, model_objs, unique_fields, update_fields, returning, sync,
ignore_duplicate_updates=ignore_duplicate_updates,
return_untouched=return_untouched) | python | def upsert(
queryset, model_objs, unique_fields,
update_fields=None, returning=False, sync=False,
ignore_duplicate_updates=True,
return_untouched=False
):
"""
Perform a bulk upsert on a table, optionally syncing the results.
Args:
queryset (Model|QuerySet): A model or a queryset that defines the collection to sync
model_objs (List[Model]): A list of Django models to sync. All models in this list
will be bulk upserted and any models not in the table (or queryset) will be deleted
if sync=True.
unique_fields (List[str]): A list of fields that define the uniqueness of the model. The
model must have a unique constraint on these fields
update_fields (List[str], default=None): A list of fields to update whenever objects
already exist. If an empty list is provided, it is equivalent to doing a bulk
insert on the objects that don't exist. If `None`, all fields will be updated.
returning (bool|List[str]): If True, returns all fields. If a list, only returns
fields in the list
sync (bool, default=False): Perform a sync operation on the queryset
ignore_duplicate_updates (bool, default=False): Don't perform an update if the row is
a duplicate.
return_untouched (bool, default=False): Return untouched rows by the operation
"""
queryset = queryset if isinstance(queryset, models.QuerySet) else queryset.objects.all()
model = queryset.model
# Populate automatically generated fields in the rows like date times
_fill_auto_fields(model, model_objs)
# Sort the rows to reduce the chances of deadlock during concurrent upserts
model_objs = _sort_by_unique_fields(model, model_objs, unique_fields)
update_fields = _get_update_fields(model, unique_fields, update_fields)
return _fetch(queryset, model_objs, unique_fields, update_fields, returning, sync,
ignore_duplicate_updates=ignore_duplicate_updates,
return_untouched=return_untouched) | [
"def",
"upsert",
"(",
"queryset",
",",
"model_objs",
",",
"unique_fields",
",",
"update_fields",
"=",
"None",
",",
"returning",
"=",
"False",
",",
"sync",
"=",
"False",
",",
"ignore_duplicate_updates",
"=",
"True",
",",
"return_untouched",
"=",
"False",
")",
... | Perform a bulk upsert on a table, optionally syncing the results.
Args:
queryset (Model|QuerySet): A model or a queryset that defines the collection to sync
model_objs (List[Model]): A list of Django models to sync. All models in this list
will be bulk upserted and any models not in the table (or queryset) will be deleted
if sync=True.
unique_fields (List[str]): A list of fields that define the uniqueness of the model. The
model must have a unique constraint on these fields
update_fields (List[str], default=None): A list of fields to update whenever objects
already exist. If an empty list is provided, it is equivalent to doing a bulk
insert on the objects that don't exist. If `None`, all fields will be updated.
returning (bool|List[str]): If True, returns all fields. If a list, only returns
fields in the list
sync (bool, default=False): Perform a sync operation on the queryset
ignore_duplicate_updates (bool, default=False): Don't perform an update if the row is
a duplicate.
return_untouched (bool, default=False): Return untouched rows by the operation | [
"Perform",
"a",
"bulk",
"upsert",
"on",
"a",
"table",
"optionally",
"syncing",
"the",
"results",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/upsert2.py#L291-L329 | train | 33,185 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | _get_upserts_distinct | def _get_upserts_distinct(queryset, model_objs_updated, model_objs_created, unique_fields):
"""
Given a list of model objects that were updated and model objects that were created,
fetch the pks of the newly created models and return the two lists in a tuple
"""
# Keep track of the created models
created_models = []
# If we created new models query for them
if model_objs_created:
created_models.extend(
queryset.extra(
where=['({unique_fields_sql}) in %s'.format(
unique_fields_sql=', '.join(unique_fields)
)],
params=[
tuple([
tuple([
getattr(model_obj, field)
for field in unique_fields
])
for model_obj in model_objs_created
])
]
)
)
# Return the models
return model_objs_updated, created_models | python | def _get_upserts_distinct(queryset, model_objs_updated, model_objs_created, unique_fields):
"""
Given a list of model objects that were updated and model objects that were created,
fetch the pks of the newly created models and return the two lists in a tuple
"""
# Keep track of the created models
created_models = []
# If we created new models query for them
if model_objs_created:
created_models.extend(
queryset.extra(
where=['({unique_fields_sql}) in %s'.format(
unique_fields_sql=', '.join(unique_fields)
)],
params=[
tuple([
tuple([
getattr(model_obj, field)
for field in unique_fields
])
for model_obj in model_objs_created
])
]
)
)
# Return the models
return model_objs_updated, created_models | [
"def",
"_get_upserts_distinct",
"(",
"queryset",
",",
"model_objs_updated",
",",
"model_objs_created",
",",
"unique_fields",
")",
":",
"# Keep track of the created models",
"created_models",
"=",
"[",
"]",
"# If we created new models query for them",
"if",
"model_objs_created",... | Given a list of model objects that were updated and model objects that were created,
fetch the pks of the newly created models and return the two lists in a tuple | [
"Given",
"a",
"list",
"of",
"model",
"objects",
"that",
"were",
"updated",
"and",
"model",
"objects",
"that",
"were",
"created",
"fetch",
"the",
"pks",
"of",
"the",
"newly",
"created",
"models",
"and",
"return",
"the",
"two",
"lists",
"in",
"a",
"tuple"
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L37-L66 | train | 33,186 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | _get_model_objs_to_update_and_create | def _get_model_objs_to_update_and_create(model_objs, unique_fields, update_fields, extant_model_objs):
"""
Used by bulk_upsert to gather lists of models that should be updated and created.
"""
# Find all of the objects to update and all of the objects to create
model_objs_to_update, model_objs_to_create = list(), list()
for model_obj in model_objs:
extant_model_obj = extant_model_objs.get(tuple(getattr(model_obj, field) for field in unique_fields), None)
if extant_model_obj is None:
# If the object needs to be created, make a new instance of it
model_objs_to_create.append(model_obj)
else:
# If the object needs to be updated, update its fields
for field in update_fields:
setattr(extant_model_obj, field, getattr(model_obj, field))
model_objs_to_update.append(extant_model_obj)
return model_objs_to_update, model_objs_to_create | python | def _get_model_objs_to_update_and_create(model_objs, unique_fields, update_fields, extant_model_objs):
"""
Used by bulk_upsert to gather lists of models that should be updated and created.
"""
# Find all of the objects to update and all of the objects to create
model_objs_to_update, model_objs_to_create = list(), list()
for model_obj in model_objs:
extant_model_obj = extant_model_objs.get(tuple(getattr(model_obj, field) for field in unique_fields), None)
if extant_model_obj is None:
# If the object needs to be created, make a new instance of it
model_objs_to_create.append(model_obj)
else:
# If the object needs to be updated, update its fields
for field in update_fields:
setattr(extant_model_obj, field, getattr(model_obj, field))
model_objs_to_update.append(extant_model_obj)
return model_objs_to_update, model_objs_to_create | [
"def",
"_get_model_objs_to_update_and_create",
"(",
"model_objs",
",",
"unique_fields",
",",
"update_fields",
",",
"extant_model_objs",
")",
":",
"# Find all of the objects to update and all of the objects to create",
"model_objs_to_update",
",",
"model_objs_to_create",
"=",
"list"... | Used by bulk_upsert to gather lists of models that should be updated and created. | [
"Used",
"by",
"bulk_upsert",
"to",
"gather",
"lists",
"of",
"models",
"that",
"should",
"be",
"updated",
"and",
"created",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L79-L97 | train | 33,187 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | _get_prepped_model_field | def _get_prepped_model_field(model_obj, field):
"""
Gets the value of a field of a model obj that is prepared for the db.
"""
# Get the field
field = model_obj._meta.get_field(field)
# Get the value
value = field.get_db_prep_save(getattr(model_obj, field.attname), connection)
# Return the value
return value | python | def _get_prepped_model_field(model_obj, field):
"""
Gets the value of a field of a model obj that is prepared for the db.
"""
# Get the field
field = model_obj._meta.get_field(field)
# Get the value
value = field.get_db_prep_save(getattr(model_obj, field.attname), connection)
# Return the value
return value | [
"def",
"_get_prepped_model_field",
"(",
"model_obj",
",",
"field",
")",
":",
"# Get the field",
"field",
"=",
"model_obj",
".",
"_meta",
".",
"get_field",
"(",
"field",
")",
"# Get the value",
"value",
"=",
"field",
".",
"get_db_prep_save",
"(",
"getattr",
"(",
... | Gets the value of a field of a model obj that is prepared for the db. | [
"Gets",
"the",
"value",
"of",
"a",
"field",
"of",
"a",
"model",
"obj",
"that",
"is",
"prepared",
"for",
"the",
"db",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L100-L112 | train | 33,188 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | get_or_none | def get_or_none(queryset, **query_params):
"""
Get an object or return None if it doesn't exist.
:param query_params: The query parameters used in the lookup.
:returns: A model object if one exists with the query params, None otherwise.
Examples:
.. code-block:: python
model_obj = get_or_none(TestModel.objects, int_field=1)
print(model_obj)
None
TestModel.objects.create(int_field=1)
model_obj = get_or_none(TestModel.objects, int_field=1)
print(model_obj.int_field)
1
"""
try:
obj = queryset.get(**query_params)
except queryset.model.DoesNotExist:
obj = None
return obj | python | def get_or_none(queryset, **query_params):
"""
Get an object or return None if it doesn't exist.
:param query_params: The query parameters used in the lookup.
:returns: A model object if one exists with the query params, None otherwise.
Examples:
.. code-block:: python
model_obj = get_or_none(TestModel.objects, int_field=1)
print(model_obj)
None
TestModel.objects.create(int_field=1)
model_obj = get_or_none(TestModel.objects, int_field=1)
print(model_obj.int_field)
1
"""
try:
obj = queryset.get(**query_params)
except queryset.model.DoesNotExist:
obj = None
return obj | [
"def",
"get_or_none",
"(",
"queryset",
",",
"*",
"*",
"query_params",
")",
":",
"try",
":",
"obj",
"=",
"queryset",
".",
"get",
"(",
"*",
"*",
"query_params",
")",
"except",
"queryset",
".",
"model",
".",
"DoesNotExist",
":",
"obj",
"=",
"None",
"retur... | Get an object or return None if it doesn't exist.
:param query_params: The query parameters used in the lookup.
:returns: A model object if one exists with the query params, None otherwise.
Examples:
.. code-block:: python
model_obj = get_or_none(TestModel.objects, int_field=1)
print(model_obj)
None
TestModel.objects.create(int_field=1)
model_obj = get_or_none(TestModel.objects, int_field=1)
print(model_obj.int_field)
1 | [
"Get",
"an",
"object",
"or",
"return",
"None",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L437-L463 | train | 33,189 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | bulk_update | def bulk_update(manager, model_objs, fields_to_update):
"""
Bulk updates a list of model objects that are already saved.
:type model_objs: list of :class:`Models<django:django.db.models.Model>`
:param model_objs: A list of model objects that have been updated.
fields_to_update: A list of fields to be updated. Only these fields will be updated
:signals: Emits a post_bulk_operation signal when completed.
Examples:
.. code-block:: python
# Create a couple test models
model_obj1 = TestModel.objects.create(int_field=1, float_field=2.0, char_field='Hi')
model_obj2 = TestModel.objects.create(int_field=3, float_field=4.0, char_field='Hello')
# Change their fields and do a bulk update
model_obj1.int_field = 10
model_obj1.float_field = 20.0
model_obj2.int_field = 30
model_obj2.float_field = 40.0
bulk_update(TestModel.objects, [model_obj1, model_obj2], ['int_field', 'float_field'])
# Reload the models and view their changes
model_obj1 = TestModel.objects.get(id=model_obj1.id)
print(model_obj1.int_field, model_obj1.float_field)
10, 20.0
model_obj2 = TestModel.objects.get(id=model_obj2.id)
print(model_obj2.int_field, model_obj2.float_field)
10, 20.0
"""
# Add the pk to the value fields so we can join
value_fields = [manager.model._meta.pk.attname] + fields_to_update
# Build the row values
row_values = [
[_get_prepped_model_field(model_obj, field_name) for field_name in value_fields]
for model_obj in model_objs
]
# If we do not have any values or fields to update just return
if len(row_values) == 0 or len(fields_to_update) == 0:
return
# Create a map of db types
db_types = [
manager.model._meta.get_field(field).db_type(connection)
for field in value_fields
]
# Build the value fields sql
value_fields_sql = ', '.join(
'"{field}"'.format(field=manager.model._meta.get_field(field).column)
for field in value_fields
)
# Build the set sql
update_fields_sql = ', '.join([
'"{field}" = "new_values"."{field}"'.format(
field=manager.model._meta.get_field(field).column
)
for field in fields_to_update
])
# Build the values sql
values_sql = ', '.join([
'({0})'.format(
', '.join([
'%s::{0}'.format(
db_types[i]
) if not row_number and i else '%s'
for i, _ in enumerate(row)
])
)
for row_number, row in enumerate(row_values)
])
# Start building the query
update_sql = (
'UPDATE {table} '
'SET {update_fields_sql} '
'FROM (VALUES {values_sql}) AS new_values ({value_fields_sql}) '
'WHERE "{table}"."{pk_field}" = "new_values"."{pk_field}"'
).format(
table=manager.model._meta.db_table,
pk_field=manager.model._meta.pk.column,
update_fields_sql=update_fields_sql,
values_sql=values_sql,
value_fields_sql=value_fields_sql
)
# Combine all the row values
update_sql_params = list(itertools.chain(*row_values))
# Run the update query
with connection.cursor() as cursor:
cursor.execute(update_sql, update_sql_params)
# call the bulk operation signal
post_bulk_operation.send(sender=manager.model, model=manager.model) | python | def bulk_update(manager, model_objs, fields_to_update):
"""
Bulk updates a list of model objects that are already saved.
:type model_objs: list of :class:`Models<django:django.db.models.Model>`
:param model_objs: A list of model objects that have been updated.
fields_to_update: A list of fields to be updated. Only these fields will be updated
:signals: Emits a post_bulk_operation signal when completed.
Examples:
.. code-block:: python
# Create a couple test models
model_obj1 = TestModel.objects.create(int_field=1, float_field=2.0, char_field='Hi')
model_obj2 = TestModel.objects.create(int_field=3, float_field=4.0, char_field='Hello')
# Change their fields and do a bulk update
model_obj1.int_field = 10
model_obj1.float_field = 20.0
model_obj2.int_field = 30
model_obj2.float_field = 40.0
bulk_update(TestModel.objects, [model_obj1, model_obj2], ['int_field', 'float_field'])
# Reload the models and view their changes
model_obj1 = TestModel.objects.get(id=model_obj1.id)
print(model_obj1.int_field, model_obj1.float_field)
10, 20.0
model_obj2 = TestModel.objects.get(id=model_obj2.id)
print(model_obj2.int_field, model_obj2.float_field)
10, 20.0
"""
# Add the pk to the value fields so we can join
value_fields = [manager.model._meta.pk.attname] + fields_to_update
# Build the row values
row_values = [
[_get_prepped_model_field(model_obj, field_name) for field_name in value_fields]
for model_obj in model_objs
]
# If we do not have any values or fields to update just return
if len(row_values) == 0 or len(fields_to_update) == 0:
return
# Create a map of db types
db_types = [
manager.model._meta.get_field(field).db_type(connection)
for field in value_fields
]
# Build the value fields sql
value_fields_sql = ', '.join(
'"{field}"'.format(field=manager.model._meta.get_field(field).column)
for field in value_fields
)
# Build the set sql
update_fields_sql = ', '.join([
'"{field}" = "new_values"."{field}"'.format(
field=manager.model._meta.get_field(field).column
)
for field in fields_to_update
])
# Build the values sql
values_sql = ', '.join([
'({0})'.format(
', '.join([
'%s::{0}'.format(
db_types[i]
) if not row_number and i else '%s'
for i, _ in enumerate(row)
])
)
for row_number, row in enumerate(row_values)
])
# Start building the query
update_sql = (
'UPDATE {table} '
'SET {update_fields_sql} '
'FROM (VALUES {values_sql}) AS new_values ({value_fields_sql}) '
'WHERE "{table}"."{pk_field}" = "new_values"."{pk_field}"'
).format(
table=manager.model._meta.db_table,
pk_field=manager.model._meta.pk.column,
update_fields_sql=update_fields_sql,
values_sql=values_sql,
value_fields_sql=value_fields_sql
)
# Combine all the row values
update_sql_params = list(itertools.chain(*row_values))
# Run the update query
with connection.cursor() as cursor:
cursor.execute(update_sql, update_sql_params)
# call the bulk operation signal
post_bulk_operation.send(sender=manager.model, model=manager.model) | [
"def",
"bulk_update",
"(",
"manager",
",",
"model_objs",
",",
"fields_to_update",
")",
":",
"# Add the pk to the value fields so we can join",
"value_fields",
"=",
"[",
"manager",
".",
"model",
".",
"_meta",
".",
"pk",
".",
"attname",
"]",
"+",
"fields_to_update",
... | Bulk updates a list of model objects that are already saved.
:type model_objs: list of :class:`Models<django:django.db.models.Model>`
:param model_objs: A list of model objects that have been updated.
fields_to_update: A list of fields to be updated. Only these fields will be updated
:signals: Emits a post_bulk_operation signal when completed.
Examples:
.. code-block:: python
# Create a couple test models
model_obj1 = TestModel.objects.create(int_field=1, float_field=2.0, char_field='Hi')
model_obj2 = TestModel.objects.create(int_field=3, float_field=4.0, char_field='Hello')
# Change their fields and do a bulk update
model_obj1.int_field = 10
model_obj1.float_field = 20.0
model_obj2.int_field = 30
model_obj2.float_field = 40.0
bulk_update(TestModel.objects, [model_obj1, model_obj2], ['int_field', 'float_field'])
# Reload the models and view their changes
model_obj1 = TestModel.objects.get(id=model_obj1.id)
print(model_obj1.int_field, model_obj1.float_field)
10, 20.0
model_obj2 = TestModel.objects.get(id=model_obj2.id)
print(model_obj2.int_field, model_obj2.float_field)
10, 20.0 | [
"Bulk",
"updates",
"a",
"list",
"of",
"model",
"objects",
"that",
"are",
"already",
"saved",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L491-L596 | train | 33,190 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | upsert | def upsert(manager, defaults=None, updates=None, **kwargs):
"""
Performs an update on an object or an insert if the object does not exist.
:type defaults: dict
:param defaults: These values are set when the object is created, but are irrelevant
when the object already exists. This field should only be used when values only need to
be set during creation.
:type updates: dict
:param updates: These values are updated when the object is updated. They also override any
values provided in the defaults when inserting the object.
:param kwargs: These values provide the arguments used when checking for the existence of
the object. They are used in a similar manner to Django's get_or_create function.
:returns: A tuple of the upserted object and a Boolean that is True if it was created (False otherwise)
Examples:
.. code-block:: python
# Upsert a test model with an int value of 1. Use default values that will be given to it when created
model_obj, created = upsert(TestModel.objects, int_field=1, defaults={'float_field': 2.0})
print(created)
True
print(model_obj.int_field, model_obj.float_field)
1, 2.0
# Do an upsert on that same model with different default fields. Since it already exists, the defaults
# are not used
model_obj, created = upsert(TestModel.objects, int_field=1, defaults={'float_field': 3.0})
print(created)
False
print(model_obj.int_field, model_obj.float_field)
1, 2.0
# In order to update the float field in an existing object, use the updates dictionary
model_obj, created = upsert(TestModel.objects, int_field=1, updates={'float_field': 3.0})
print(created)
False
print(model_obj.int_field, model_obj.float_field)
1, 3.0
# You can use updates on a newly created object that will also be used as initial values.
model_obj, created = upsert(TestModel.objects, int_field=2, updates={'float_field': 4.0})
print(created)
True
print(model_obj.int_field, model_obj.float_field)
2, 4.0
"""
defaults = defaults or {}
# Override any defaults with updates
defaults.update(updates or {})
# Do a get or create
obj, created = manager.get_or_create(defaults=defaults, **kwargs)
# Update any necessary fields
if updates is not None and not created and any(getattr(obj, k) != updates[k] for k in updates):
for k, v in updates.items():
setattr(obj, k, v)
obj.save(update_fields=updates)
return obj, created | python | def upsert(manager, defaults=None, updates=None, **kwargs):
"""
Performs an update on an object or an insert if the object does not exist.
:type defaults: dict
:param defaults: These values are set when the object is created, but are irrelevant
when the object already exists. This field should only be used when values only need to
be set during creation.
:type updates: dict
:param updates: These values are updated when the object is updated. They also override any
values provided in the defaults when inserting the object.
:param kwargs: These values provide the arguments used when checking for the existence of
the object. They are used in a similar manner to Django's get_or_create function.
:returns: A tuple of the upserted object and a Boolean that is True if it was created (False otherwise)
Examples:
.. code-block:: python
# Upsert a test model with an int value of 1. Use default values that will be given to it when created
model_obj, created = upsert(TestModel.objects, int_field=1, defaults={'float_field': 2.0})
print(created)
True
print(model_obj.int_field, model_obj.float_field)
1, 2.0
# Do an upsert on that same model with different default fields. Since it already exists, the defaults
# are not used
model_obj, created = upsert(TestModel.objects, int_field=1, defaults={'float_field': 3.0})
print(created)
False
print(model_obj.int_field, model_obj.float_field)
1, 2.0
# In order to update the float field in an existing object, use the updates dictionary
model_obj, created = upsert(TestModel.objects, int_field=1, updates={'float_field': 3.0})
print(created)
False
print(model_obj.int_field, model_obj.float_field)
1, 3.0
# You can use updates on a newly created object that will also be used as initial values.
model_obj, created = upsert(TestModel.objects, int_field=2, updates={'float_field': 4.0})
print(created)
True
print(model_obj.int_field, model_obj.float_field)
2, 4.0
"""
defaults = defaults or {}
# Override any defaults with updates
defaults.update(updates or {})
# Do a get or create
obj, created = manager.get_or_create(defaults=defaults, **kwargs)
# Update any necessary fields
if updates is not None and not created and any(getattr(obj, k) != updates[k] for k in updates):
for k, v in updates.items():
setattr(obj, k, v)
obj.save(update_fields=updates)
return obj, created | [
"def",
"upsert",
"(",
"manager",
",",
"defaults",
"=",
"None",
",",
"updates",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"defaults",
"or",
"{",
"}",
"# Override any defaults with updates",
"defaults",
".",
"update",
"(",
"updates",
"... | Performs an update on an object or an insert if the object does not exist.
:type defaults: dict
:param defaults: These values are set when the object is created, but are irrelevant
when the object already exists. This field should only be used when values only need to
be set during creation.
:type updates: dict
:param updates: These values are updated when the object is updated. They also override any
values provided in the defaults when inserting the object.
:param kwargs: These values provide the arguments used when checking for the existence of
the object. They are used in a similar manner to Django's get_or_create function.
:returns: A tuple of the upserted object and a Boolean that is True if it was created (False otherwise)
Examples:
.. code-block:: python
# Upsert a test model with an int value of 1. Use default values that will be given to it when created
model_obj, created = upsert(TestModel.objects, int_field=1, defaults={'float_field': 2.0})
print(created)
True
print(model_obj.int_field, model_obj.float_field)
1, 2.0
# Do an upsert on that same model with different default fields. Since it already exists, the defaults
# are not used
model_obj, created = upsert(TestModel.objects, int_field=1, defaults={'float_field': 3.0})
print(created)
False
print(model_obj.int_field, model_obj.float_field)
1, 2.0
# In order to update the float field in an existing object, use the updates dictionary
model_obj, created = upsert(TestModel.objects, int_field=1, updates={'float_field': 3.0})
print(created)
False
print(model_obj.int_field, model_obj.float_field)
1, 3.0
# You can use updates on a newly created object that will also be used as initial values.
model_obj, created = upsert(TestModel.objects, int_field=2, updates={'float_field': 4.0})
print(created)
True
print(model_obj.int_field, model_obj.float_field)
2, 4.0 | [
"Performs",
"an",
"update",
"on",
"an",
"object",
"or",
"an",
"insert",
"if",
"the",
"object",
"does",
"not",
"exist",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L599-L664 | train | 33,191 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | ManagerUtilsQuerySet.bulk_create | def bulk_create(self, *args, **kwargs):
"""
Overrides Django's bulk_create function to emit a post_bulk_operation signal when bulk_create
is finished.
"""
ret_val = super(ManagerUtilsQuerySet, self).bulk_create(*args, **kwargs)
post_bulk_operation.send(sender=self.model, model=self.model)
return ret_val | python | def bulk_create(self, *args, **kwargs):
"""
Overrides Django's bulk_create function to emit a post_bulk_operation signal when bulk_create
is finished.
"""
ret_val = super(ManagerUtilsQuerySet, self).bulk_create(*args, **kwargs)
post_bulk_operation.send(sender=self.model, model=self.model)
return ret_val | [
"def",
"bulk_create",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret_val",
"=",
"super",
"(",
"ManagerUtilsQuerySet",
",",
"self",
")",
".",
"bulk_create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"post_bulk_operation",
"... | Overrides Django's bulk_create function to emit a post_bulk_operation signal when bulk_create
is finished. | [
"Overrides",
"Django",
"s",
"bulk_create",
"function",
"to",
"emit",
"a",
"post_bulk_operation",
"signal",
"when",
"bulk_create",
"is",
"finished",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L686-L693 | train | 33,192 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | ManagerUtilsQuerySet.update | def update(self, **kwargs):
"""
Overrides Django's update method to emit a post_bulk_operation signal when it completes.
"""
ret_val = super(ManagerUtilsQuerySet, self).update(**kwargs)
post_bulk_operation.send(sender=self.model, model=self.model)
return ret_val | python | def update(self, **kwargs):
"""
Overrides Django's update method to emit a post_bulk_operation signal when it completes.
"""
ret_val = super(ManagerUtilsQuerySet, self).update(**kwargs)
post_bulk_operation.send(sender=self.model, model=self.model)
return ret_val | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"ret_val",
"=",
"super",
"(",
"ManagerUtilsQuerySet",
",",
"self",
")",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"post_bulk_operation",
".",
"send",
"(",
"sender",
"=",
"self",
".",
... | Overrides Django's update method to emit a post_bulk_operation signal when it completes. | [
"Overrides",
"Django",
"s",
"update",
"method",
"to",
"emit",
"a",
"post_bulk_operation",
"signal",
"when",
"it",
"completes",
"."
] | 1f111cb4846ed6cd6b78eca320a9dcc27826bf97 | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L708-L714 | train | 33,193 |
aaugustin/django-sesame | sesame/middleware.py | AuthenticationMiddleware.process_request | def process_request(self, request):
"""
Log user in if `request` contains a valid login token.
Return a HTTP redirect response that removes the token from the URL
after a successful login when sessions are enabled, else ``None``.
"""
token = request.GET.get(TOKEN_NAME)
user = None if token is None else authenticate(url_auth_token=token)
# If the sessions framework is enabled and the token is valid,
# persist the login in session.
if hasattr(request, 'session') and user is not None:
login(request, user)
# Once we persist the login in the session, if the authentication
# middleware is enabled, it will set request.user in future
# requests. We can get rid of the token in the URL by redirecting
# to the same URL with the token removed. We only do this for GET
# requests because redirecting POST requests doesn't work well. We
# don't do this on Safari because it triggers the over-zealous
# "Protection Against First Party Bounce Trackers" of ITP 2.0.
if (
hasattr(request, 'user') and
request.method == 'GET' and
not self.is_safari(request)
):
return self.get_redirect(request)
# If the authentication middleware isn't enabled, set request.user.
# (This attribute is overwritten by the authentication middleware
# if it runs after this one.)
if not hasattr(request, 'user'):
request.user = user if user is not None else AnonymousUser() | python | def process_request(self, request):
"""
Log user in if `request` contains a valid login token.
Return a HTTP redirect response that removes the token from the URL
after a successful login when sessions are enabled, else ``None``.
"""
token = request.GET.get(TOKEN_NAME)
user = None if token is None else authenticate(url_auth_token=token)
# If the sessions framework is enabled and the token is valid,
# persist the login in session.
if hasattr(request, 'session') and user is not None:
login(request, user)
# Once we persist the login in the session, if the authentication
# middleware is enabled, it will set request.user in future
# requests. We can get rid of the token in the URL by redirecting
# to the same URL with the token removed. We only do this for GET
# requests because redirecting POST requests doesn't work well. We
# don't do this on Safari because it triggers the over-zealous
# "Protection Against First Party Bounce Trackers" of ITP 2.0.
if (
hasattr(request, 'user') and
request.method == 'GET' and
not self.is_safari(request)
):
return self.get_redirect(request)
# If the authentication middleware isn't enabled, set request.user.
# (This attribute is overwritten by the authentication middleware
# if it runs after this one.)
if not hasattr(request, 'user'):
request.user = user if user is not None else AnonymousUser() | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"token",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"TOKEN_NAME",
")",
"user",
"=",
"None",
"if",
"token",
"is",
"None",
"else",
"authenticate",
"(",
"url_auth_token",
"=",
"token",
")",
... | Log user in if `request` contains a valid login token.
Return a HTTP redirect response that removes the token from the URL
after a successful login when sessions are enabled, else ``None``. | [
"Log",
"user",
"in",
"if",
"request",
"contains",
"a",
"valid",
"login",
"token",
"."
] | 4bf902c637b0674b8fc78bc95937271948c99282 | https://github.com/aaugustin/django-sesame/blob/4bf902c637b0674b8fc78bc95937271948c99282/sesame/middleware.py#L23-L56 | train | 33,194 |
aaugustin/django-sesame | sesame/middleware.py | AuthenticationMiddleware.get_redirect | def get_redirect(request):
"""
Create a HTTP redirect response that removes the token from the URL.
"""
params = request.GET.copy()
params.pop(TOKEN_NAME)
url = request.path
if params:
url += '?' + urlencode(params)
return redirect(url) | python | def get_redirect(request):
"""
Create a HTTP redirect response that removes the token from the URL.
"""
params = request.GET.copy()
params.pop(TOKEN_NAME)
url = request.path
if params:
url += '?' + urlencode(params)
return redirect(url) | [
"def",
"get_redirect",
"(",
"request",
")",
":",
"params",
"=",
"request",
".",
"GET",
".",
"copy",
"(",
")",
"params",
".",
"pop",
"(",
"TOKEN_NAME",
")",
"url",
"=",
"request",
".",
"path",
"if",
"params",
":",
"url",
"+=",
"'?'",
"+",
"urlencode",... | Create a HTTP redirect response that removes the token from the URL. | [
"Create",
"a",
"HTTP",
"redirect",
"response",
"that",
"removes",
"the",
"token",
"from",
"the",
"URL",
"."
] | 4bf902c637b0674b8fc78bc95937271948c99282 | https://github.com/aaugustin/django-sesame/blob/4bf902c637b0674b8fc78bc95937271948c99282/sesame/middleware.py#L70-L80 | train | 33,195 |
aaugustin/django-sesame | sesame/backends.py | UrlAuthBackendMixin.sign | def sign(self, data):
"""
Create an URL-safe, signed token from ``data``.
"""
data = signing.b64_encode(data).decode()
return self.signer.sign(data) | python | def sign(self, data):
"""
Create an URL-safe, signed token from ``data``.
"""
data = signing.b64_encode(data).decode()
return self.signer.sign(data) | [
"def",
"sign",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"signing",
".",
"b64_encode",
"(",
"data",
")",
".",
"decode",
"(",
")",
"return",
"self",
".",
"signer",
".",
"sign",
"(",
"data",
")"
] | Create an URL-safe, signed token from ``data``. | [
"Create",
"an",
"URL",
"-",
"safe",
"signed",
"token",
"from",
"data",
"."
] | 4bf902c637b0674b8fc78bc95937271948c99282 | https://github.com/aaugustin/django-sesame/blob/4bf902c637b0674b8fc78bc95937271948c99282/sesame/backends.py#L50-L56 | train | 33,196 |
aaugustin/django-sesame | sesame/backends.py | UrlAuthBackendMixin.unsign | def unsign(self, token):
"""
Extract the data from a signed ``token``.
"""
if self.max_age is None:
data = self.signer.unsign(token)
else:
data = self.signer.unsign(token, max_age=self.max_age)
return signing.b64_decode(data.encode()) | python | def unsign(self, token):
"""
Extract the data from a signed ``token``.
"""
if self.max_age is None:
data = self.signer.unsign(token)
else:
data = self.signer.unsign(token, max_age=self.max_age)
return signing.b64_decode(data.encode()) | [
"def",
"unsign",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"max_age",
"is",
"None",
":",
"data",
"=",
"self",
".",
"signer",
".",
"unsign",
"(",
"token",
")",
"else",
":",
"data",
"=",
"self",
".",
"signer",
".",
"unsign",
"(",
"tok... | Extract the data from a signed ``token``. | [
"Extract",
"the",
"data",
"from",
"a",
"signed",
"token",
"."
] | 4bf902c637b0674b8fc78bc95937271948c99282 | https://github.com/aaugustin/django-sesame/blob/4bf902c637b0674b8fc78bc95937271948c99282/sesame/backends.py#L58-L67 | train | 33,197 |
aaugustin/django-sesame | sesame/backends.py | UrlAuthBackendMixin.get_revocation_key | def get_revocation_key(self, user):
"""
When the value returned by this method changes, this revocates tokens.
It always includes the password so that changing the password revokes
existing tokens.
In addition, for one-time tokens, it also contains the last login
datetime so that logging in revokes existing tokens.
"""
value = ''
if self.invalidate_on_password_change:
value += user.password
if self.one_time:
value += str(user.last_login)
return value | python | def get_revocation_key(self, user):
"""
When the value returned by this method changes, this revocates tokens.
It always includes the password so that changing the password revokes
existing tokens.
In addition, for one-time tokens, it also contains the last login
datetime so that logging in revokes existing tokens.
"""
value = ''
if self.invalidate_on_password_change:
value += user.password
if self.one_time:
value += str(user.last_login)
return value | [
"def",
"get_revocation_key",
"(",
"self",
",",
"user",
")",
":",
"value",
"=",
"''",
"if",
"self",
".",
"invalidate_on_password_change",
":",
"value",
"+=",
"user",
".",
"password",
"if",
"self",
".",
"one_time",
":",
"value",
"+=",
"str",
"(",
"user",
"... | When the value returned by this method changes, this revocates tokens.
It always includes the password so that changing the password revokes
existing tokens.
In addition, for one-time tokens, it also contains the last login
datetime so that logging in revokes existing tokens. | [
"When",
"the",
"value",
"returned",
"by",
"this",
"method",
"changes",
"this",
"revocates",
"tokens",
"."
] | 4bf902c637b0674b8fc78bc95937271948c99282 | https://github.com/aaugustin/django-sesame/blob/4bf902c637b0674b8fc78bc95937271948c99282/sesame/backends.py#L79-L95 | train | 33,198 |
aaugustin/django-sesame | sesame/backends.py | UrlAuthBackendMixin.create_token | def create_token(self, user):
"""
Create a signed token from a user.
"""
# The password is expected to be a secure hash but we hash it again
# for additional safety. We default to MD5 to minimize the length of
# the token. (Remember, if an attacker obtains the URL, he can already
# log in. This isn't high security.)
h = crypto.pbkdf2(
self.get_revocation_key(user),
self.salt,
self.iterations,
digest=self.digest,
)
return self.sign(self.packer.pack_pk(user.pk) + h) | python | def create_token(self, user):
"""
Create a signed token from a user.
"""
# The password is expected to be a secure hash but we hash it again
# for additional safety. We default to MD5 to minimize the length of
# the token. (Remember, if an attacker obtains the URL, he can already
# log in. This isn't high security.)
h = crypto.pbkdf2(
self.get_revocation_key(user),
self.salt,
self.iterations,
digest=self.digest,
)
return self.sign(self.packer.pack_pk(user.pk) + h) | [
"def",
"create_token",
"(",
"self",
",",
"user",
")",
":",
"# The password is expected to be a secure hash but we hash it again",
"# for additional safety. We default to MD5 to minimize the length of",
"# the token. (Remember, if an attacker obtains the URL, he can already",
"# log in. This is... | Create a signed token from a user. | [
"Create",
"a",
"signed",
"token",
"from",
"a",
"user",
"."
] | 4bf902c637b0674b8fc78bc95937271948c99282 | https://github.com/aaugustin/django-sesame/blob/4bf902c637b0674b8fc78bc95937271948c99282/sesame/backends.py#L97-L112 | train | 33,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.