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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
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 =... | 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 =... | [
"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 |
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 |
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... | 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... | [
"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 |
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 |
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 |
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 |
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 |
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 |
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 |
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... | 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... | [
"def",
"load_windowstime",
"(",
"buf",
",",
"pos",
")",
":",
"unix_epoch",
"=",
"11644473600",
"val1",
",",
"pos",
"=",
"load_le32",
"(",
"buf",
",",
"pos",
")",
"val2",
",",
"pos",
"=",
"load_le32",
"(",
"buf",
",",
"pos",
")",
"secs",
",",
"n1secs"... | Load LE64 windows timestamp | [
"Load",
"LE64",
"windows",
"timestamp"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2647-L2656 | train |
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 |
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.pac... | 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.pac... | [
"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 |
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 onl... | 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 onl... | [
"def",
"rar3_decompress",
"(",
"vers",
",",
"meth",
",",
"data",
",",
"declen",
"=",
"0",
",",
"flags",
"=",
"0",
",",
"crc",
"=",
"0",
",",
"psw",
"=",
"None",
",",
"salt",
"=",
"None",
")",
":",
"if",
"meth",
"==",
"RAR_M0",
"and",
"(",
"flag... | 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 |
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 ... | 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 ... | [
"def",
"to_datetime",
"(",
"t",
")",
":",
"if",
"t",
"is",
"None",
":",
"return",
"None",
"year",
",",
"mon",
",",
"day",
",",
"h",
",",
"m",
",",
"s",
"=",
"t",
"try",
":",
"return",
"datetime",
"(",
"year",
",",
"mon",
",",
"day",
",",
"h",... | 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 |
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
... | 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
... | [
"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 |
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... | 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... | [
"def",
"custom_popen",
"(",
"cmd",
")",
":",
"creationflags",
"=",
"0",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"creationflags",
"=",
"0x08000000",
"try",
":",
"p",
"=",
"Popen",
"(",
"cmd",
",",
"bufsize",
"=",
"0",
",",
"stdout",
"=",
"... | 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 |
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 |
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
... | 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
... | [
"def",
"check_returncode",
"(",
"p",
",",
"out",
")",
":",
"code",
"=",
"p",
".",
"returncode",
"if",
"code",
"==",
"0",
":",
"return",
"errmap",
"=",
"[",
"None",
",",
"RarWarning",
",",
"RarFatalError",
",",
"RarCRCError",
",",
"RarLockedArchiveError",
... | 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 |
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... | 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... | [
"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 |
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 |
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()... | 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()... | [
"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 |
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.
""... | 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.
""... | [
"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 |
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
... | 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
... | [
"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 |
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
... | 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
... | [
"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 |
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 |
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:
... | 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:
... | [
"def",
"getinfo",
"(",
"self",
",",
"member",
")",
":",
"if",
"isinstance",
"(",
"member",
",",
"RarInfo",
")",
":",
"fname",
"=",
"member",
".",
"filename",
"else",
":",
"fname",
"=",
"member",
"if",
"PATH_SEP",
"==",
"'/'",
":",
"fname2",
"=",
"fna... | Return RarInfo for filename | [
"Return",
"RarInfo",
"for",
"filename"
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L955-L975 | train |
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 |
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])
... | 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])
... | [
"def",
"open",
"(",
"self",
",",
"inf",
",",
"psw",
")",
":",
"if",
"inf",
".",
"file_redir",
":",
"if",
"inf",
".",
"file_redir",
"[",
"0",
"]",
"in",
"(",
"RAR5_XREDIR_FILE_COPY",
",",
"RAR5_XREDIR_HARD_LINK",
")",
":",
"inf",
"=",
"self",
".",
"ge... | 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 |
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 |
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 |
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 |
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 >> flagb... | 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 >> flagb... | [
"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 |
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
... | 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
... | [
"def",
"read",
"(",
"self",
",",
"cnt",
"=",
"None",
")",
":",
"if",
"cnt",
"is",
"None",
"or",
"cnt",
"<",
"0",
":",
"cnt",
"=",
"self",
".",
"_remain",
"elif",
"cnt",
">",
"self",
".",
"_remain",
":",
"cnt",
"=",
"self",
".",
"_remain",
"if",... | 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 |
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:
... | 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:
... | [
"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 |
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.
"""
# disa... | 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.
"""
# disa... | [
"def",
"seek",
"(",
"self",
",",
"ofs",
",",
"whence",
"=",
"0",
")",
":",
"self",
".",
"_md_context",
"=",
"NoHashContext",
"(",
")",
"fsize",
"=",
"self",
".",
"_inf",
".",
"file_size",
"cur_ofs",
"=",
"self",
".",
"tell",
"(",
")",
"if",
"whence... | 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 |
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 |
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.... | 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.... | [
"def",
"_read",
"(",
"self",
",",
"cnt",
")",
":",
"data",
"=",
"self",
".",
"_fd",
".",
"read",
"(",
"cnt",
")",
"if",
"len",
"(",
"data",
")",
"==",
"cnt",
"or",
"not",
"data",
":",
"return",
"data",
"buf",
"=",
"[",
"data",
"]",
"cnt",
"-=... | Read from pipe. | [
"Read",
"from",
"pipe",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2181-L2198 | train |
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
... | 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
... | [
"def",
"_skip",
"(",
"self",
",",
"cnt",
")",
":",
"while",
"cnt",
">",
"0",
":",
"if",
"self",
".",
"_cur_avail",
"==",
"0",
":",
"if",
"not",
"self",
".",
"_open_next",
"(",
")",
":",
"break",
"if",
"cnt",
">",
"self",
".",
"_cur_avail",
":",
... | 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 |
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 cn... | 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 cn... | [
"def",
"_read",
"(",
"self",
",",
"cnt",
")",
":",
"buf",
"=",
"[",
"]",
"while",
"cnt",
">",
"0",
":",
"if",
"self",
".",
"_cur_avail",
"==",
"0",
":",
"if",
"not",
"self",
".",
"_open_next",
"(",
")",
":",
"break",
"if",
"cnt",
">",
"self",
... | 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 |
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 ... | 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 ... | [
"def",
"readinto",
"(",
"self",
",",
"buf",
")",
":",
"got",
"=",
"0",
"vbuf",
"=",
"memoryview",
"(",
"buf",
")",
"while",
"got",
"<",
"len",
"(",
"buf",
")",
":",
"if",
"self",
".",
"_cur_avail",
"==",
"0",
":",
"if",
"not",
"self",
".",
"_op... | 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 |
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
... | 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
... | [
"def",
"read",
"(",
"self",
",",
"cnt",
"=",
"None",
")",
":",
"if",
"cnt",
">",
"8",
"*",
"1024",
":",
"raise",
"BadRarFile",
"(",
"'Bad count to header decrypt - wrong password?'",
")",
"if",
"cnt",
"<=",
"len",
"(",
"self",
".",
"buf",
")",
":",
"re... | Read and decrypt. | [
"Read",
"and",
"decrypt",
"."
] | 2704344e8d7a1658c96c8ed8f449d7ba01bedea3 | https://github.com/markokr/rarfile/blob/2704344e8d7a1658c96c8ed8f449d7ba01bedea3/rarfile.py#L2365-L2394 | train |
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 + ... | 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 + ... | [
"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 |
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()... | 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()... | [
"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 |
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... | 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... | [
"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 |
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))) & 0xFFF... | 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))) & 0xFFF... | [
"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 |
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_SELECTIZ... | 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_SELECTIZ... | [
"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 |
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.
... | 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.
... | [
"def",
"parse_tags",
"(",
"tagstring",
")",
":",
"if",
"not",
"tagstring",
":",
"return",
"[",
"]",
"tagstring",
"=",
"force_text",
"(",
"tagstring",
")",
"words",
"=",
"[",
"]",
"buffer",
"=",
"[",
"]",
"to_be_split",
"=",
"[",
"]",
"i",
"=",
"iter"... | 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 `djan... | [
"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 |
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... | 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... | [
"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... | [
"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 |
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))
... | 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))
... | [
"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 |
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._co... | 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._co... | [
"def",
"get",
"(",
"cls",
",",
"key",
",",
"section",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"section",
"=",
"section",
"or",
"cls",
".",
"_default_sect",
"if",
"section",
"not",
"in",
"cls",
".",
"_conf",
":",
"cls",
".",
"_load",
"(",
"secti... | 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 |
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 |
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:
... | 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:
... | [
"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 |
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 |
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
"""
... | 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
"""
... | [
"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 |
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 |
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 |
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 |
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.ex... | 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.ex... | [
"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 |
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 |
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)
... | 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)
... | [
"def",
"_to_json_default",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"obj",
".",
"isoformat",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"uuid",
".",
"UUID",
")",
":",
"return",
"s... | 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 |
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 f... | 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 f... | [
"def",
"_from_json_object_hook",
"(",
"obj",
")",
":",
"for",
"key",
",",
"value",
"in",
"obj",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"dt_result",
"=",
"datetime_regex",
".",
"match",
"(",
"value",
")",
... | 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 |
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(pa... | 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(pa... | [
"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 |
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 |
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 |
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_... | 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_... | [
"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 |
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 |
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_res... | 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_res... | [
"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 |
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... | 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... | [
"def",
"get_spark_session",
"(",
"enable_hive",
"=",
"False",
",",
"app_name",
"=",
"'marvin-engine'",
",",
"configs",
"=",
"[",
"]",
")",
":",
"import",
"findspark",
"findspark",
".",
"init",
"(",
")",
"from",
"pyspark",
".",
"sql",
"import",
"SparkSession"... | 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 |
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 |
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, a... | 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, a... | [
"def",
"_trychar",
"(",
"char",
",",
"fallback",
",",
"asciimode",
"=",
"None",
")",
":",
"if",
"asciimode",
"is",
"True",
":",
"return",
"fallback",
"if",
"hasattr",
"(",
"sys",
".",
"stdout",
",",
"'encoding'",
")",
"and",
"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', 'u... | [
"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 |
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 |
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 |
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='u... | 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='u... | [
"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(la... | [
"clears",
"all",
"measurements",
"allowing",
"the",
"object",
"to",
"be",
"reused"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L180-L203 | train |
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... | 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... | [
"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.fact... | [
"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 |
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
... | 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
... | [
"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.
E... | [
"The",
"mean",
"of",
"the",
"best",
"results",
"of",
"each",
"trial",
"."
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L289-L310 | train |
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 ... | 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 ... | [
"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.
Examp... | [
"The",
"standard",
"deviation",
"of",
"the",
"best",
"results",
"of",
"each",
"trial",
"."
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L312-L334 | train |
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
>>> t... | 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
>>> t... | [
"def",
"report",
"(",
"self",
",",
"verbose",
"=",
"1",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"verbose",
">=",
"2",
":",
"lines",
".",
"append",
"(",
"self",
".",
"_status_line",
"(",
"tense",
"=",
"'past'",
")",
")",
"if",
"verbose",
">=",
"3"... | 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)
... | [
"Creates",
"a",
"human",
"readable",
"report"
] | 625449f5359f757fb0ab8093b228dc8f37b8ffaf | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L383-L421 | train |
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(__fi... | 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(__fi... | [
"def",
"parse_description",
"(",
")",
":",
"from",
"os",
".",
"path",
"import",
"dirname",
",",
"join",
",",
"exists",
"readme_fpath",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"'README.rst'",
")",
"if",
"exists",
"(",
"readme_fpath",
")",
... | 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 |
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
impor... | 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
impor... | [
"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 |
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 ImportErro... | 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 ImportErro... | [
"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 |
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:
... | 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:
... | [
"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 |
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... | 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... | [
"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 |
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.... | 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.... | [
"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 |
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:
return... | 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:
return... | [
"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 |
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 tha... | 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 tha... | [
"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... | [
"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 |
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
... | 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
... | [
"def",
"_get_upserts_distinct",
"(",
"queryset",
",",
"model_objs_updated",
",",
"model_objs_created",
",",
"unique_fields",
")",
":",
"created_models",
"=",
"[",
"]",
"if",
"model_objs_created",
":",
"created_models",
".",
"extend",
"(",
"queryset",
".",
"extra",
... | 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 |
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_c... | 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_c... | [
"def",
"_get_model_objs_to_update_and_create",
"(",
"model_objs",
",",
"unique_fields",
",",
"update_fields",
",",
"extant_model_objs",
")",
":",
"model_objs_to_update",
",",
"model_objs_to_create",
"=",
"list",
"(",
")",
",",
"list",
"(",
")",
"for",
"model_obj",
"... | 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 |
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... | 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... | [
"def",
"_get_prepped_model_field",
"(",
"model_obj",
",",
"field",
")",
":",
"field",
"=",
"model_obj",
".",
"_meta",
".",
"get_field",
"(",
"field",
")",
"value",
"=",
"field",
".",
"get_db_prep_save",
"(",
"getattr",
"(",
"model_obj",
",",
"field",
".",
... | 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 |
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 = g... | 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 = g... | [
"def",
"get_or_none",
"(",
"queryset",
",",
"**",
"query_params",
")",
":",
"try",
":",
"obj",
"=",
"queryset",
".",
"get",
"(",
"**",
"query_params",
")",
"except",
"queryset",
".",
"model",
".",
"DoesNotExist",
":",
"obj",
"=",
"None",
"return",
"obj"
... | 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)
prin... | [
"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 |
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... | 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... | [
"def",
"bulk_update",
"(",
"manager",
",",
"model_objs",
",",
"fields_to_update",
")",
":",
"value_fields",
"=",
"[",
"manager",
".",
"model",
".",
"_meta",
".",
"pk",
".",
"attname",
"]",
"+",
"fields_to_update",
"row_values",
"=",
"[",
"[",
"_get_prepped_m... | 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: Em... | [
"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 |
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 sho... | 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 sho... | [
"def",
"upsert",
"(",
"manager",
",",
"defaults",
"=",
"None",
",",
"updates",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"defaults",
"=",
"defaults",
"or",
"{",
"}",
"defaults",
".",
"update",
"(",
"updates",
"or",
"{",
"}",
")",
"obj",
",",
"cre... | 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 crea... | [
"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 |
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, ... | 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, ... | [
"def",
"bulk_create",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"ret_val",
"=",
"super",
"(",
"ManagerUtilsQuerySet",
",",
"self",
")",
".",
"bulk_create",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"post_bulk_operation",
".",
"send"... | 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 |
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",
".",
"model",
... | 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 |
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)
... | 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)
... | [
"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 |
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 |
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 |
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 |
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
dateti... | 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
dateti... | [
"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 |
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 ca... | 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 ca... | [
"def",
"create_token",
"(",
"self",
",",
"user",
")",
":",
"h",
"=",
"crypto",
".",
"pbkdf2",
"(",
"self",
".",
"get_revocation_key",
"(",
"user",
")",
",",
"self",
".",
"salt",
",",
"self",
".",
"iterations",
",",
"digest",
"=",
"self",
".",
"digest... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.