partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
_init_pathinfo
|
Return a set containing all existing directory entries from sys.path
|
capybara/virtualenv/lib/python2.7/site.py
|
def _init_pathinfo():
"""Return a set containing all existing directory entries from sys.path"""
d = set()
for dir in sys.path:
try:
if os.path.isdir(dir):
dir, dircase = makepath(dir)
d.add(dircase)
except TypeError:
continue
return d
|
def _init_pathinfo():
"""Return a set containing all existing directory entries from sys.path"""
d = set()
for dir in sys.path:
try:
if os.path.isdir(dir):
dir, dircase = makepath(dir)
d.add(dircase)
except TypeError:
continue
return d
|
[
"Return",
"a",
"set",
"containing",
"all",
"existing",
"directory",
"entries",
"from",
"sys",
".",
"path"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L143-L153
|
[
"def",
"_init_pathinfo",
"(",
")",
":",
"d",
"=",
"set",
"(",
")",
"for",
"dir",
"in",
"sys",
".",
"path",
":",
"try",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dir",
")",
":",
"dir",
",",
"dircase",
"=",
"makepath",
"(",
"dir",
")",
"d",
".",
"add",
"(",
"dircase",
")",
"except",
"TypeError",
":",
"continue",
"return",
"d"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
addpackage
|
Add a new path to known_paths by combining sitedir and 'name' or execute
sitedir if it starts with 'import
|
capybara/virtualenv/lib/python2.7/site.py
|
def addpackage(sitedir, name, known_paths):
"""Add a new path to known_paths by combining sitedir and 'name' or execute
sitedir if it starts with 'import'"""
if known_paths is None:
_init_pathinfo()
reset = 1
else:
reset = 0
fullname = os.path.join(sitedir, name)
try:
f = open(fullname, "rU")
except IOError:
return
try:
for line in f:
if line.startswith("#"):
continue
if line.startswith("import"):
exec(line)
continue
line = line.rstrip()
dir, dircase = makepath(sitedir, line)
if not dircase in known_paths and os.path.exists(dir):
sys.path.append(dir)
known_paths.add(dircase)
finally:
f.close()
if reset:
known_paths = None
return known_paths
|
def addpackage(sitedir, name, known_paths):
"""Add a new path to known_paths by combining sitedir and 'name' or execute
sitedir if it starts with 'import'"""
if known_paths is None:
_init_pathinfo()
reset = 1
else:
reset = 0
fullname = os.path.join(sitedir, name)
try:
f = open(fullname, "rU")
except IOError:
return
try:
for line in f:
if line.startswith("#"):
continue
if line.startswith("import"):
exec(line)
continue
line = line.rstrip()
dir, dircase = makepath(sitedir, line)
if not dircase in known_paths and os.path.exists(dir):
sys.path.append(dir)
known_paths.add(dircase)
finally:
f.close()
if reset:
known_paths = None
return known_paths
|
[
"Add",
"a",
"new",
"path",
"to",
"known_paths",
"by",
"combining",
"sitedir",
"and",
"name",
"or",
"execute",
"sitedir",
"if",
"it",
"starts",
"with",
"import"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L155-L184
|
[
"def",
"addpackage",
"(",
"sitedir",
",",
"name",
",",
"known_paths",
")",
":",
"if",
"known_paths",
"is",
"None",
":",
"_init_pathinfo",
"(",
")",
"reset",
"=",
"1",
"else",
":",
"reset",
"=",
"0",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sitedir",
",",
"name",
")",
"try",
":",
"f",
"=",
"open",
"(",
"fullname",
",",
"\"rU\"",
")",
"except",
"IOError",
":",
"return",
"try",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"continue",
"if",
"line",
".",
"startswith",
"(",
"\"import\"",
")",
":",
"exec",
"(",
"line",
")",
"continue",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"dir",
",",
"dircase",
"=",
"makepath",
"(",
"sitedir",
",",
"line",
")",
"if",
"not",
"dircase",
"in",
"known_paths",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"dir",
")",
":",
"sys",
".",
"path",
".",
"append",
"(",
"dir",
")",
"known_paths",
".",
"add",
"(",
"dircase",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"if",
"reset",
":",
"known_paths",
"=",
"None",
"return",
"known_paths"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
addsitedir
|
Add 'sitedir' argument to sys.path if missing and handle .pth files in
'sitedir
|
capybara/virtualenv/lib/python2.7/site.py
|
def addsitedir(sitedir, known_paths=None):
"""Add 'sitedir' argument to sys.path if missing and handle .pth files in
'sitedir'"""
if known_paths is None:
known_paths = _init_pathinfo()
reset = 1
else:
reset = 0
sitedir, sitedircase = makepath(sitedir)
if not sitedircase in known_paths:
sys.path.append(sitedir) # Add path component
try:
names = os.listdir(sitedir)
except os.error:
return
names.sort()
for name in names:
if name.endswith(os.extsep + "pth"):
addpackage(sitedir, name, known_paths)
if reset:
known_paths = None
return known_paths
|
def addsitedir(sitedir, known_paths=None):
"""Add 'sitedir' argument to sys.path if missing and handle .pth files in
'sitedir'"""
if known_paths is None:
known_paths = _init_pathinfo()
reset = 1
else:
reset = 0
sitedir, sitedircase = makepath(sitedir)
if not sitedircase in known_paths:
sys.path.append(sitedir) # Add path component
try:
names = os.listdir(sitedir)
except os.error:
return
names.sort()
for name in names:
if name.endswith(os.extsep + "pth"):
addpackage(sitedir, name, known_paths)
if reset:
known_paths = None
return known_paths
|
[
"Add",
"sitedir",
"argument",
"to",
"sys",
".",
"path",
"if",
"missing",
"and",
"handle",
".",
"pth",
"files",
"in",
"sitedir"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L186-L207
|
[
"def",
"addsitedir",
"(",
"sitedir",
",",
"known_paths",
"=",
"None",
")",
":",
"if",
"known_paths",
"is",
"None",
":",
"known_paths",
"=",
"_init_pathinfo",
"(",
")",
"reset",
"=",
"1",
"else",
":",
"reset",
"=",
"0",
"sitedir",
",",
"sitedircase",
"=",
"makepath",
"(",
"sitedir",
")",
"if",
"not",
"sitedircase",
"in",
"known_paths",
":",
"sys",
".",
"path",
".",
"append",
"(",
"sitedir",
")",
"# Add path component",
"try",
":",
"names",
"=",
"os",
".",
"listdir",
"(",
"sitedir",
")",
"except",
"os",
".",
"error",
":",
"return",
"names",
".",
"sort",
"(",
")",
"for",
"name",
"in",
"names",
":",
"if",
"name",
".",
"endswith",
"(",
"os",
".",
"extsep",
"+",
"\"pth\"",
")",
":",
"addpackage",
"(",
"sitedir",
",",
"name",
",",
"known_paths",
")",
"if",
"reset",
":",
"known_paths",
"=",
"None",
"return",
"known_paths"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
addsitepackages
|
Add site-packages (and possibly site-python) to sys.path
|
capybara/virtualenv/lib/python2.7/site.py
|
def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
"""Add site-packages (and possibly site-python) to sys.path"""
prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
if exec_prefix != sys_prefix:
prefixes.append(os.path.join(exec_prefix, "local"))
for prefix in prefixes:
if prefix:
if sys.platform in ('os2emx', 'riscos') or _is_jython:
sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
elif _is_pypy:
sitedirs = [os.path.join(prefix, 'site-packages')]
elif sys.platform == 'darwin' and prefix == sys_prefix:
if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
os.path.join(prefix, "Extras", "lib", "python")]
else: # any other Python distros on OSX work this way
sitedirs = [os.path.join(prefix, "lib",
"python" + sys.version[:3], "site-packages")]
elif os.sep == '/':
sitedirs = [os.path.join(prefix,
"lib",
"python" + sys.version[:3],
"site-packages"),
os.path.join(prefix, "lib", "site-python"),
os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")]
lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
if (os.path.exists(lib64_dir) and
os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
if _is_64bit:
sitedirs.insert(0, lib64_dir)
else:
sitedirs.append(lib64_dir)
try:
# sys.getobjects only available in --with-pydebug build
sys.getobjects
sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
except AttributeError:
pass
# Debian-specific dist-packages directories:
sitedirs.append(os.path.join(prefix, "local/lib",
"python" + sys.version[:3],
"dist-packages"))
if sys.version[0] == '2':
sitedirs.append(os.path.join(prefix, "lib",
"python" + sys.version[:3],
"dist-packages"))
else:
sitedirs.append(os.path.join(prefix, "lib",
"python" + sys.version[0],
"dist-packages"))
sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
else:
sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
if sys.platform == 'darwin':
# for framework builds *only* we add the standard Apple
# locations. Currently only per-user, but /Library and
# /Network/Library could be added too
if 'Python.framework' in prefix:
home = os.environ.get('HOME')
if home:
sitedirs.append(
os.path.join(home,
'Library',
'Python',
sys.version[:3],
'site-packages'))
for sitedir in sitedirs:
if os.path.isdir(sitedir):
addsitedir(sitedir, known_paths)
return None
|
def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
"""Add site-packages (and possibly site-python) to sys.path"""
prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
if exec_prefix != sys_prefix:
prefixes.append(os.path.join(exec_prefix, "local"))
for prefix in prefixes:
if prefix:
if sys.platform in ('os2emx', 'riscos') or _is_jython:
sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
elif _is_pypy:
sitedirs = [os.path.join(prefix, 'site-packages')]
elif sys.platform == 'darwin' and prefix == sys_prefix:
if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
os.path.join(prefix, "Extras", "lib", "python")]
else: # any other Python distros on OSX work this way
sitedirs = [os.path.join(prefix, "lib",
"python" + sys.version[:3], "site-packages")]
elif os.sep == '/':
sitedirs = [os.path.join(prefix,
"lib",
"python" + sys.version[:3],
"site-packages"),
os.path.join(prefix, "lib", "site-python"),
os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")]
lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
if (os.path.exists(lib64_dir) and
os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
if _is_64bit:
sitedirs.insert(0, lib64_dir)
else:
sitedirs.append(lib64_dir)
try:
# sys.getobjects only available in --with-pydebug build
sys.getobjects
sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
except AttributeError:
pass
# Debian-specific dist-packages directories:
sitedirs.append(os.path.join(prefix, "local/lib",
"python" + sys.version[:3],
"dist-packages"))
if sys.version[0] == '2':
sitedirs.append(os.path.join(prefix, "lib",
"python" + sys.version[:3],
"dist-packages"))
else:
sitedirs.append(os.path.join(prefix, "lib",
"python" + sys.version[0],
"dist-packages"))
sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
else:
sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
if sys.platform == 'darwin':
# for framework builds *only* we add the standard Apple
# locations. Currently only per-user, but /Library and
# /Network/Library could be added too
if 'Python.framework' in prefix:
home = os.environ.get('HOME')
if home:
sitedirs.append(
os.path.join(home,
'Library',
'Python',
sys.version[:3],
'site-packages'))
for sitedir in sitedirs:
if os.path.isdir(sitedir):
addsitedir(sitedir, known_paths)
return None
|
[
"Add",
"site",
"-",
"packages",
"(",
"and",
"possibly",
"site",
"-",
"python",
")",
"to",
"sys",
".",
"path"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L209-L283
|
[
"def",
"addsitepackages",
"(",
"known_paths",
",",
"sys_prefix",
"=",
"sys",
".",
"prefix",
",",
"exec_prefix",
"=",
"sys",
".",
"exec_prefix",
")",
":",
"prefixes",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"sys_prefix",
",",
"\"local\"",
")",
",",
"sys_prefix",
"]",
"if",
"exec_prefix",
"!=",
"sys_prefix",
":",
"prefixes",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"exec_prefix",
",",
"\"local\"",
")",
")",
"for",
"prefix",
"in",
"prefixes",
":",
"if",
"prefix",
":",
"if",
"sys",
".",
"platform",
"in",
"(",
"'os2emx'",
",",
"'riscos'",
")",
"or",
"_is_jython",
":",
"sitedirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"Lib\"",
",",
"\"site-packages\"",
")",
"]",
"elif",
"_is_pypy",
":",
"sitedirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"'site-packages'",
")",
"]",
"elif",
"sys",
".",
"platform",
"==",
"'darwin'",
"and",
"prefix",
"==",
"sys_prefix",
":",
"if",
"prefix",
".",
"startswith",
"(",
"\"/System/Library/Frameworks/\"",
")",
":",
"# Apple's Python",
"sitedirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"\"/Library/Python\"",
",",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"site-packages\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"Extras\"",
",",
"\"lib\"",
",",
"\"python\"",
")",
"]",
"else",
":",
"# any other Python distros on OSX work this way",
"sitedirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"lib\"",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"site-packages\"",
")",
"]",
"elif",
"os",
".",
"sep",
"==",
"'/'",
":",
"sitedirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"lib\"",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"site-packages\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"lib\"",
",",
"\"site-python\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"lib-dynload\"",
")",
"]",
"lib64_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"lib64\"",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"site-packages\"",
")",
"if",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"lib64_dir",
")",
"and",
"os",
".",
"path",
".",
"realpath",
"(",
"lib64_dir",
")",
"not",
"in",
"[",
"os",
".",
"path",
".",
"realpath",
"(",
"p",
")",
"for",
"p",
"in",
"sitedirs",
"]",
")",
":",
"if",
"_is_64bit",
":",
"sitedirs",
".",
"insert",
"(",
"0",
",",
"lib64_dir",
")",
"else",
":",
"sitedirs",
".",
"append",
"(",
"lib64_dir",
")",
"try",
":",
"# sys.getobjects only available in --with-pydebug build",
"sys",
".",
"getobjects",
"sitedirs",
".",
"insert",
"(",
"0",
",",
"os",
".",
"path",
".",
"join",
"(",
"sitedirs",
"[",
"0",
"]",
",",
"'debug'",
")",
")",
"except",
"AttributeError",
":",
"pass",
"# Debian-specific dist-packages directories:",
"sitedirs",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"local/lib\"",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"dist-packages\"",
")",
")",
"if",
"sys",
".",
"version",
"[",
"0",
"]",
"==",
"'2'",
":",
"sitedirs",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"lib\"",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"dist-packages\"",
")",
")",
"else",
":",
"sitedirs",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"lib\"",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
"0",
"]",
",",
"\"dist-packages\"",
")",
")",
"sitedirs",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"lib\"",
",",
"\"dist-python\"",
")",
")",
"else",
":",
"sitedirs",
"=",
"[",
"prefix",
",",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
"\"lib\"",
",",
"\"site-packages\"",
")",
"]",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"# for framework builds *only* we add the standard Apple",
"# locations. Currently only per-user, but /Library and",
"# /Network/Library could be added too",
"if",
"'Python.framework'",
"in",
"prefix",
":",
"home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'HOME'",
")",
"if",
"home",
":",
"sitedirs",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"'Library'",
",",
"'Python'",
",",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"'site-packages'",
")",
")",
"for",
"sitedir",
"in",
"sitedirs",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"sitedir",
")",
":",
"addsitedir",
"(",
"sitedir",
",",
"known_paths",
")",
"return",
"None"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
check_enableusersite
|
Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var),
process uid/gid equal to effective uid/gid.
None: Disabled for security reasons
False: Disabled by user (command line option)
True: Safe and enabled
|
capybara/virtualenv/lib/python2.7/site.py
|
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var),
process uid/gid equal to effective uid/gid.
None: Disabled for security reasons
False: Disabled by user (command line option)
True: Safe and enabled
"""
if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
return False
if hasattr(os, "getuid") and hasattr(os, "geteuid"):
# check process uid == effective uid
if os.geteuid() != os.getuid():
return None
if hasattr(os, "getgid") and hasattr(os, "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
|
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var),
process uid/gid equal to effective uid/gid.
None: Disabled for security reasons
False: Disabled by user (command line option)
True: Safe and enabled
"""
if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
return False
if hasattr(os, "getuid") and hasattr(os, "geteuid"):
# check process uid == effective uid
if os.geteuid() != os.getuid():
return None
if hasattr(os, "getgid") and hasattr(os, "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
|
[
"Check",
"if",
"user",
"site",
"directory",
"is",
"safe",
"for",
"inclusion"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L285-L307
|
[
"def",
"check_enableusersite",
"(",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"'flags'",
")",
"and",
"getattr",
"(",
"sys",
".",
"flags",
",",
"'no_user_site'",
",",
"False",
")",
":",
"return",
"False",
"if",
"hasattr",
"(",
"os",
",",
"\"getuid\"",
")",
"and",
"hasattr",
"(",
"os",
",",
"\"geteuid\"",
")",
":",
"# check process uid == effective uid",
"if",
"os",
".",
"geteuid",
"(",
")",
"!=",
"os",
".",
"getuid",
"(",
")",
":",
"return",
"None",
"if",
"hasattr",
"(",
"os",
",",
"\"getgid\"",
")",
"and",
"hasattr",
"(",
"os",
",",
"\"getegid\"",
")",
":",
"# check process gid == effective gid",
"if",
"os",
".",
"getegid",
"(",
")",
"!=",
"os",
".",
"getgid",
"(",
")",
":",
"return",
"None",
"return",
"True"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
addusersitepackages
|
Add a per user site-package to sys.path
Each user has its own python directory with site-packages in the
home directory.
USER_BASE is the root directory for all Python versions
USER_SITE is the user specific site-packages directory
USER_SITE/.. can be used for data.
|
capybara/virtualenv/lib/python2.7/site.py
|
def addusersitepackages(known_paths):
"""Add a per user site-package to sys.path
Each user has its own python directory with site-packages in the
home directory.
USER_BASE is the root directory for all Python versions
USER_SITE is the user specific site-packages directory
USER_SITE/.. can be used for data.
"""
global USER_BASE, USER_SITE, ENABLE_USER_SITE
env_base = os.environ.get("PYTHONUSERBASE", None)
def joinuser(*args):
return os.path.expanduser(os.path.join(*args))
#if sys.platform in ('os2emx', 'riscos'):
# # Don't know what to put here
# USER_BASE = ''
# USER_SITE = ''
if os.name == "nt":
base = os.environ.get("APPDATA") or "~"
if env_base:
USER_BASE = env_base
else:
USER_BASE = joinuser(base, "Python")
USER_SITE = os.path.join(USER_BASE,
"Python" + sys.version[0] + sys.version[2],
"site-packages")
else:
if env_base:
USER_BASE = env_base
else:
USER_BASE = joinuser("~", ".local")
USER_SITE = os.path.join(USER_BASE, "lib",
"python" + sys.version[:3],
"site-packages")
if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
addsitedir(USER_SITE, known_paths)
if ENABLE_USER_SITE:
for dist_libdir in ("lib", "local/lib"):
user_site = os.path.join(USER_BASE, dist_libdir,
"python" + sys.version[:3],
"dist-packages")
if os.path.isdir(user_site):
addsitedir(user_site, known_paths)
return known_paths
|
def addusersitepackages(known_paths):
"""Add a per user site-package to sys.path
Each user has its own python directory with site-packages in the
home directory.
USER_BASE is the root directory for all Python versions
USER_SITE is the user specific site-packages directory
USER_SITE/.. can be used for data.
"""
global USER_BASE, USER_SITE, ENABLE_USER_SITE
env_base = os.environ.get("PYTHONUSERBASE", None)
def joinuser(*args):
return os.path.expanduser(os.path.join(*args))
#if sys.platform in ('os2emx', 'riscos'):
# # Don't know what to put here
# USER_BASE = ''
# USER_SITE = ''
if os.name == "nt":
base = os.environ.get("APPDATA") or "~"
if env_base:
USER_BASE = env_base
else:
USER_BASE = joinuser(base, "Python")
USER_SITE = os.path.join(USER_BASE,
"Python" + sys.version[0] + sys.version[2],
"site-packages")
else:
if env_base:
USER_BASE = env_base
else:
USER_BASE = joinuser("~", ".local")
USER_SITE = os.path.join(USER_BASE, "lib",
"python" + sys.version[:3],
"site-packages")
if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
addsitedir(USER_SITE, known_paths)
if ENABLE_USER_SITE:
for dist_libdir in ("lib", "local/lib"):
user_site = os.path.join(USER_BASE, dist_libdir,
"python" + sys.version[:3],
"dist-packages")
if os.path.isdir(user_site):
addsitedir(user_site, known_paths)
return known_paths
|
[
"Add",
"a",
"per",
"user",
"site",
"-",
"package",
"to",
"sys",
".",
"path"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L309-L358
|
[
"def",
"addusersitepackages",
"(",
"known_paths",
")",
":",
"global",
"USER_BASE",
",",
"USER_SITE",
",",
"ENABLE_USER_SITE",
"env_base",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PYTHONUSERBASE\"",
",",
"None",
")",
"def",
"joinuser",
"(",
"*",
"args",
")",
":",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"*",
"args",
")",
")",
"#if sys.platform in ('os2emx', 'riscos'):",
"# # Don't know what to put here",
"# USER_BASE = ''",
"# USER_SITE = ''",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"base",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"APPDATA\"",
")",
"or",
"\"~\"",
"if",
"env_base",
":",
"USER_BASE",
"=",
"env_base",
"else",
":",
"USER_BASE",
"=",
"joinuser",
"(",
"base",
",",
"\"Python\"",
")",
"USER_SITE",
"=",
"os",
".",
"path",
".",
"join",
"(",
"USER_BASE",
",",
"\"Python\"",
"+",
"sys",
".",
"version",
"[",
"0",
"]",
"+",
"sys",
".",
"version",
"[",
"2",
"]",
",",
"\"site-packages\"",
")",
"else",
":",
"if",
"env_base",
":",
"USER_BASE",
"=",
"env_base",
"else",
":",
"USER_BASE",
"=",
"joinuser",
"(",
"\"~\"",
",",
"\".local\"",
")",
"USER_SITE",
"=",
"os",
".",
"path",
".",
"join",
"(",
"USER_BASE",
",",
"\"lib\"",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"site-packages\"",
")",
"if",
"ENABLE_USER_SITE",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"USER_SITE",
")",
":",
"addsitedir",
"(",
"USER_SITE",
",",
"known_paths",
")",
"if",
"ENABLE_USER_SITE",
":",
"for",
"dist_libdir",
"in",
"(",
"\"lib\"",
",",
"\"local/lib\"",
")",
":",
"user_site",
"=",
"os",
".",
"path",
".",
"join",
"(",
"USER_BASE",
",",
"dist_libdir",
",",
"\"python\"",
"+",
"sys",
".",
"version",
"[",
":",
"3",
"]",
",",
"\"dist-packages\"",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"user_site",
")",
":",
"addsitedir",
"(",
"user_site",
",",
"known_paths",
")",
"return",
"known_paths"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
setBEGINLIBPATH
|
The OS/2 EMX port has optional extension modules that do double duty
as DLLs (and must use the .DLL file extension) for other extensions.
The library search path needs to be amended so these will be found
during module import. Use BEGINLIBPATH so that these are at the start
of the library search path.
|
capybara/virtualenv/lib/python2.7/site.py
|
def setBEGINLIBPATH():
"""The OS/2 EMX port has optional extension modules that do double duty
as DLLs (and must use the .DLL file extension) for other extensions.
The library search path needs to be amended so these will be found
during module import. Use BEGINLIBPATH so that these are at the start
of the library search path.
"""
dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
libpath = os.environ['BEGINLIBPATH'].split(';')
if libpath[-1]:
libpath.append(dllpath)
else:
libpath[-1] = dllpath
os.environ['BEGINLIBPATH'] = ';'.join(libpath)
|
def setBEGINLIBPATH():
"""The OS/2 EMX port has optional extension modules that do double duty
as DLLs (and must use the .DLL file extension) for other extensions.
The library search path needs to be amended so these will be found
during module import. Use BEGINLIBPATH so that these are at the start
of the library search path.
"""
dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
libpath = os.environ['BEGINLIBPATH'].split(';')
if libpath[-1]:
libpath.append(dllpath)
else:
libpath[-1] = dllpath
os.environ['BEGINLIBPATH'] = ';'.join(libpath)
|
[
"The",
"OS",
"/",
"2",
"EMX",
"port",
"has",
"optional",
"extension",
"modules",
"that",
"do",
"double",
"duty",
"as",
"DLLs",
"(",
"and",
"must",
"use",
"the",
".",
"DLL",
"file",
"extension",
")",
"for",
"other",
"extensions",
".",
"The",
"library",
"search",
"path",
"needs",
"to",
"be",
"amended",
"so",
"these",
"will",
"be",
"found",
"during",
"module",
"import",
".",
"Use",
"BEGINLIBPATH",
"so",
"that",
"these",
"are",
"at",
"the",
"start",
"of",
"the",
"library",
"search",
"path",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L362-L376
|
[
"def",
"setBEGINLIBPATH",
"(",
")",
":",
"dllpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"prefix",
",",
"\"Lib\"",
",",
"\"lib-dynload\"",
")",
"libpath",
"=",
"os",
".",
"environ",
"[",
"'BEGINLIBPATH'",
"]",
".",
"split",
"(",
"';'",
")",
"if",
"libpath",
"[",
"-",
"1",
"]",
":",
"libpath",
".",
"append",
"(",
"dllpath",
")",
"else",
":",
"libpath",
"[",
"-",
"1",
"]",
"=",
"dllpath",
"os",
".",
"environ",
"[",
"'BEGINLIBPATH'",
"]",
"=",
"';'",
".",
"join",
"(",
"libpath",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
setquit
|
Define new built-ins 'quit' and 'exit'.
These are simply strings that display a hint on how to exit.
|
capybara/virtualenv/lib/python2.7/site.py
|
def setquit():
"""Define new built-ins 'quit' and 'exit'.
These are simply strings that display a hint on how to exit.
"""
if os.sep == ':':
eof = 'Cmd-Q'
elif os.sep == '\\':
eof = 'Ctrl-Z plus Return'
else:
eof = 'Ctrl-D (i.e. EOF)'
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
builtins.quit = Quitter('quit')
builtins.exit = Quitter('exit')
|
def setquit():
"""Define new built-ins 'quit' and 'exit'.
These are simply strings that display a hint on how to exit.
"""
if os.sep == ':':
eof = 'Cmd-Q'
elif os.sep == '\\':
eof = 'Ctrl-Z plus Return'
else:
eof = 'Ctrl-D (i.e. EOF)'
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
builtins.quit = Quitter('quit')
builtins.exit = Quitter('exit')
|
[
"Define",
"new",
"built",
"-",
"ins",
"quit",
"and",
"exit",
".",
"These",
"are",
"simply",
"strings",
"that",
"display",
"a",
"hint",
"on",
"how",
"to",
"exit",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L379-L405
|
[
"def",
"setquit",
"(",
")",
":",
"if",
"os",
".",
"sep",
"==",
"':'",
":",
"eof",
"=",
"'Cmd-Q'",
"elif",
"os",
".",
"sep",
"==",
"'\\\\'",
":",
"eof",
"=",
"'Ctrl-Z plus Return'",
"else",
":",
"eof",
"=",
"'Ctrl-D (i.e. EOF)'",
"class",
"Quitter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"name",
"=",
"name",
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'Use %s() or %s to exit'",
"%",
"(",
"self",
".",
"name",
",",
"eof",
")",
"def",
"__call__",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"# Shells like IDLE catch the SystemExit, but listen when their",
"# stdin wrapper is closed.",
"try",
":",
"sys",
".",
"stdin",
".",
"close",
"(",
")",
"except",
":",
"pass",
"raise",
"SystemExit",
"(",
"code",
")",
"builtins",
".",
"quit",
"=",
"Quitter",
"(",
"'quit'",
")",
"builtins",
".",
"exit",
"=",
"Quitter",
"(",
"'exit'",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
setcopyright
|
Set 'copyright' and 'credits' in __builtin__
|
capybara/virtualenv/lib/python2.7/site.py
|
def setcopyright():
"""Set 'copyright' and 'credits' in __builtin__"""
builtins.copyright = _Printer("copyright", sys.copyright)
if _is_jython:
builtins.credits = _Printer(
"credits",
"Jython is maintained by the Jython developers (www.jython.org).")
elif _is_pypy:
builtins.credits = _Printer(
"credits",
"PyPy is maintained by the PyPy developers: http://pypy.org/")
else:
builtins.credits = _Printer("credits", """\
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.""")
here = os.path.dirname(os.__file__)
builtins.license = _Printer(
"license", "See http://www.python.org/%.3s/license.html" % sys.version,
["LICENSE.txt", "LICENSE"],
[os.path.join(here, os.pardir), here, os.curdir])
|
def setcopyright():
"""Set 'copyright' and 'credits' in __builtin__"""
builtins.copyright = _Printer("copyright", sys.copyright)
if _is_jython:
builtins.credits = _Printer(
"credits",
"Jython is maintained by the Jython developers (www.jython.org).")
elif _is_pypy:
builtins.credits = _Printer(
"credits",
"PyPy is maintained by the PyPy developers: http://pypy.org/")
else:
builtins.credits = _Printer("credits", """\
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.""")
here = os.path.dirname(os.__file__)
builtins.license = _Printer(
"license", "See http://www.python.org/%.3s/license.html" % sys.version,
["LICENSE.txt", "LICENSE"],
[os.path.join(here, os.pardir), here, os.curdir])
|
[
"Set",
"copyright",
"and",
"credits",
"in",
"__builtin__"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L472-L491
|
[
"def",
"setcopyright",
"(",
")",
":",
"builtins",
".",
"copyright",
"=",
"_Printer",
"(",
"\"copyright\"",
",",
"sys",
".",
"copyright",
")",
"if",
"_is_jython",
":",
"builtins",
".",
"credits",
"=",
"_Printer",
"(",
"\"credits\"",
",",
"\"Jython is maintained by the Jython developers (www.jython.org).\"",
")",
"elif",
"_is_pypy",
":",
"builtins",
".",
"credits",
"=",
"_Printer",
"(",
"\"credits\"",
",",
"\"PyPy is maintained by the PyPy developers: http://pypy.org/\"",
")",
"else",
":",
"builtins",
".",
"credits",
"=",
"_Printer",
"(",
"\"credits\"",
",",
"\"\"\"\\\n Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\n for supporting Python development. See www.python.org for more information.\"\"\"",
")",
"here",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"__file__",
")",
"builtins",
".",
"license",
"=",
"_Printer",
"(",
"\"license\"",
",",
"\"See http://www.python.org/%.3s/license.html\"",
"%",
"sys",
".",
"version",
",",
"[",
"\"LICENSE.txt\"",
",",
"\"LICENSE\"",
"]",
",",
"[",
"os",
".",
"path",
".",
"join",
"(",
"here",
",",
"os",
".",
"pardir",
")",
",",
"here",
",",
"os",
".",
"curdir",
"]",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
aliasmbcs
|
On Windows, some default encodings are not provided by Python,
while they are always available as "mbcs" in each locale. Make
them usable by aliasing to "mbcs" in such a case.
|
capybara/virtualenv/lib/python2.7/site.py
|
def aliasmbcs():
"""On Windows, some default encodings are not provided by Python,
while they are always available as "mbcs" in each locale. Make
them usable by aliasing to "mbcs" in such a case."""
if sys.platform == 'win32':
import locale, codecs
enc = locale.getdefaultlocale()[1]
if enc.startswith('cp'): # "cp***" ?
try:
codecs.lookup(enc)
except LookupError:
import encodings
encodings._cache[enc] = encodings._unknown
encodings.aliases.aliases[enc] = 'mbcs'
|
def aliasmbcs():
"""On Windows, some default encodings are not provided by Python,
while they are always available as "mbcs" in each locale. Make
them usable by aliasing to "mbcs" in such a case."""
if sys.platform == 'win32':
import locale, codecs
enc = locale.getdefaultlocale()[1]
if enc.startswith('cp'): # "cp***" ?
try:
codecs.lookup(enc)
except LookupError:
import encodings
encodings._cache[enc] = encodings._unknown
encodings.aliases.aliases[enc] = 'mbcs'
|
[
"On",
"Windows",
"some",
"default",
"encodings",
"are",
"not",
"provided",
"by",
"Python",
"while",
"they",
"are",
"always",
"available",
"as",
"mbcs",
"in",
"each",
"locale",
".",
"Make",
"them",
"usable",
"by",
"aliasing",
"to",
"mbcs",
"in",
"such",
"a",
"case",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L510-L523
|
[
"def",
"aliasmbcs",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"import",
"locale",
",",
"codecs",
"enc",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"[",
"1",
"]",
"if",
"enc",
".",
"startswith",
"(",
"'cp'",
")",
":",
"# \"cp***\" ?",
"try",
":",
"codecs",
".",
"lookup",
"(",
"enc",
")",
"except",
"LookupError",
":",
"import",
"encodings",
"encodings",
".",
"_cache",
"[",
"enc",
"]",
"=",
"encodings",
".",
"_unknown",
"encodings",
".",
"aliases",
".",
"aliases",
"[",
"enc",
"]",
"=",
"'mbcs'"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
setencoding
|
Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this.
|
capybara/virtualenv/lib/python2.7/site.py
|
def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "ascii" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding)
|
def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "ascii" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding)
|
[
"Set",
"the",
"string",
"encoding",
"used",
"by",
"the",
"Unicode",
"implementation",
".",
"The",
"default",
"is",
"ascii",
"but",
"if",
"you",
"re",
"willing",
"to",
"experiment",
"you",
"can",
"change",
"this",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L525-L542
|
[
"def",
"setencoding",
"(",
")",
":",
"encoding",
"=",
"\"ascii\"",
"# Default value set by _PyUnicode_Init()",
"if",
"0",
":",
"# Enable to support locale aware default string encodings.",
"import",
"locale",
"loc",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"if",
"loc",
"[",
"1",
"]",
":",
"encoding",
"=",
"loc",
"[",
"1",
"]",
"if",
"0",
":",
"# Enable to switch off string to Unicode coercion and implicit",
"# Unicode to string conversion.",
"encoding",
"=",
"\"undefined\"",
"if",
"encoding",
"!=",
"\"ascii\"",
":",
"# On Non-Unicode builds this will raise an AttributeError...",
"sys",
".",
"setdefaultencoding",
"(",
"encoding",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
force_global_eggs_after_local_site_packages
|
Force easy_installed eggs in the global environment to get placed
in sys.path after all packages inside the virtualenv. This
maintains the "least surprise" result that packages in the
virtualenv always mask global packages, never the other way
around.
|
capybara/virtualenv/lib/python2.7/site.py
|
def force_global_eggs_after_local_site_packages():
"""
Force easy_installed eggs in the global environment to get placed
in sys.path after all packages inside the virtualenv. This
maintains the "least surprise" result that packages in the
virtualenv always mask global packages, never the other way
around.
"""
egginsert = getattr(sys, '__egginsert', 0)
for i, path in enumerate(sys.path):
if i > egginsert and path.startswith(sys.prefix):
egginsert = i
sys.__egginsert = egginsert + 1
|
def force_global_eggs_after_local_site_packages():
"""
Force easy_installed eggs in the global environment to get placed
in sys.path after all packages inside the virtualenv. This
maintains the "least surprise" result that packages in the
virtualenv always mask global packages, never the other way
around.
"""
egginsert = getattr(sys, '__egginsert', 0)
for i, path in enumerate(sys.path):
if i > egginsert and path.startswith(sys.prefix):
egginsert = i
sys.__egginsert = egginsert + 1
|
[
"Force",
"easy_installed",
"eggs",
"in",
"the",
"global",
"environment",
"to",
"get",
"placed",
"in",
"sys",
".",
"path",
"after",
"all",
"packages",
"inside",
"the",
"virtualenv",
".",
"This",
"maintains",
"the",
"least",
"surprise",
"result",
"that",
"packages",
"in",
"the",
"virtualenv",
"always",
"mask",
"global",
"packages",
"never",
"the",
"other",
"way",
"around",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L627-L640
|
[
"def",
"force_global_eggs_after_local_site_packages",
"(",
")",
":",
"egginsert",
"=",
"getattr",
"(",
"sys",
",",
"'__egginsert'",
",",
"0",
")",
"for",
"i",
",",
"path",
"in",
"enumerate",
"(",
"sys",
".",
"path",
")",
":",
"if",
"i",
">",
"egginsert",
"and",
"path",
".",
"startswith",
"(",
"sys",
".",
"prefix",
")",
":",
"egginsert",
"=",
"i",
"sys",
".",
"__egginsert",
"=",
"egginsert",
"+",
"1"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
fixclasspath
|
Adjust the special classpath sys.path entries for Jython. These
entries should follow the base virtualenv lib directories.
|
capybara/virtualenv/lib/python2.7/site.py
|
def fixclasspath():
"""Adjust the special classpath sys.path entries for Jython. These
entries should follow the base virtualenv lib directories.
"""
paths = []
classpaths = []
for path in sys.path:
if path == '__classpath__' or path.startswith('__pyclasspath__'):
classpaths.append(path)
else:
paths.append(path)
sys.path = paths
sys.path.extend(classpaths)
|
def fixclasspath():
"""Adjust the special classpath sys.path entries for Jython. These
entries should follow the base virtualenv lib directories.
"""
paths = []
classpaths = []
for path in sys.path:
if path == '__classpath__' or path.startswith('__pyclasspath__'):
classpaths.append(path)
else:
paths.append(path)
sys.path = paths
sys.path.extend(classpaths)
|
[
"Adjust",
"the",
"special",
"classpath",
"sys",
".",
"path",
"entries",
"for",
"Jython",
".",
"These",
"entries",
"should",
"follow",
"the",
"base",
"virtualenv",
"lib",
"directories",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site.py#L646-L658
|
[
"def",
"fixclasspath",
"(",
")",
":",
"paths",
"=",
"[",
"]",
"classpaths",
"=",
"[",
"]",
"for",
"path",
"in",
"sys",
".",
"path",
":",
"if",
"path",
"==",
"'__classpath__'",
"or",
"path",
".",
"startswith",
"(",
"'__pyclasspath__'",
")",
":",
"classpaths",
".",
"append",
"(",
"path",
")",
"else",
":",
"paths",
".",
"append",
"(",
"path",
")",
"sys",
".",
"path",
"=",
"paths",
"sys",
".",
"path",
".",
"extend",
"(",
"classpaths",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Popen_nonblocking
|
Open a subprocess without blocking. Return a process handle with any
output streams replaced by queues of lines from that stream.
Usage::
proc = Popen_nonblocking(..., stdout=subprocess.PIPE)
try:
out_line = proc.stdout.get_nowait()
except queue.Empty:
"no output available"
else:
handle_output(out_line)
|
jaraco/util/subprocess.py
|
def Popen_nonblocking(*args, **kwargs):
"""
Open a subprocess without blocking. Return a process handle with any
output streams replaced by queues of lines from that stream.
Usage::
proc = Popen_nonblocking(..., stdout=subprocess.PIPE)
try:
out_line = proc.stdout.get_nowait()
except queue.Empty:
"no output available"
else:
handle_output(out_line)
"""
kwargs.setdefault('close_fds', 'posix' in sys.builtin_module_names)
kwargs.setdefault('bufsize', 1)
proc = subprocess.Popen(*args, **kwargs)
if proc.stdout:
q = queue.Queue()
t = threading.Thread(
target=enqueue_lines,
args=(proc.stdout, q))
proc.stdout = q
# thread dies with the parent
t.daemon = True
t.start()
if proc.stderr:
q = queue.Queue()
t = threading.Thread(
target=enqueue_lines,
args=(proc.stderr, q))
proc.stderr = q
t.daemon = True
t.start()
return proc
|
def Popen_nonblocking(*args, **kwargs):
"""
Open a subprocess without blocking. Return a process handle with any
output streams replaced by queues of lines from that stream.
Usage::
proc = Popen_nonblocking(..., stdout=subprocess.PIPE)
try:
out_line = proc.stdout.get_nowait()
except queue.Empty:
"no output available"
else:
handle_output(out_line)
"""
kwargs.setdefault('close_fds', 'posix' in sys.builtin_module_names)
kwargs.setdefault('bufsize', 1)
proc = subprocess.Popen(*args, **kwargs)
if proc.stdout:
q = queue.Queue()
t = threading.Thread(
target=enqueue_lines,
args=(proc.stdout, q))
proc.stdout = q
# thread dies with the parent
t.daemon = True
t.start()
if proc.stderr:
q = queue.Queue()
t = threading.Thread(
target=enqueue_lines,
args=(proc.stderr, q))
proc.stderr = q
t.daemon = True
t.start()
return proc
|
[
"Open",
"a",
"subprocess",
"without",
"blocking",
".",
"Return",
"a",
"process",
"handle",
"with",
"any",
"output",
"streams",
"replaced",
"by",
"queues",
"of",
"lines",
"from",
"that",
"stream",
"."
] |
jaraco/jaraco.util
|
python
|
https://github.com/jaraco/jaraco.util/blob/f21071c64f165a5cf844db15e39356e1a47f4b02/jaraco/util/subprocess.py#L17-L52
|
[
"def",
"Popen_nonblocking",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'close_fds'",
",",
"'posix'",
"in",
"sys",
".",
"builtin_module_names",
")",
"kwargs",
".",
"setdefault",
"(",
"'bufsize'",
",",
"1",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"proc",
".",
"stdout",
":",
"q",
"=",
"queue",
".",
"Queue",
"(",
")",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"enqueue_lines",
",",
"args",
"=",
"(",
"proc",
".",
"stdout",
",",
"q",
")",
")",
"proc",
".",
"stdout",
"=",
"q",
"# thread dies with the parent",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")",
"if",
"proc",
".",
"stderr",
":",
"q",
"=",
"queue",
".",
"Queue",
"(",
")",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"enqueue_lines",
",",
"args",
"=",
"(",
"proc",
".",
"stderr",
",",
"q",
")",
")",
"proc",
".",
"stderr",
"=",
"q",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")",
"return",
"proc"
] |
f21071c64f165a5cf844db15e39356e1a47f4b02
|
test
|
have_pyrex
|
Return True if Cython or Pyrex can be imported.
|
capybara/virtualenv/lib/python2.7/site-packages/setuptools/extension.py
|
def have_pyrex():
"""
Return True if Cython or Pyrex can be imported.
"""
pyrex_impls = 'Cython.Distutils.build_ext', 'Pyrex.Distutils.build_ext'
for pyrex_impl in pyrex_impls:
try:
# from (pyrex_impl) import build_ext
__import__(pyrex_impl, fromlist=['build_ext']).build_ext
return True
except Exception:
pass
return False
|
def have_pyrex():
"""
Return True if Cython or Pyrex can be imported.
"""
pyrex_impls = 'Cython.Distutils.build_ext', 'Pyrex.Distutils.build_ext'
for pyrex_impl in pyrex_impls:
try:
# from (pyrex_impl) import build_ext
__import__(pyrex_impl, fromlist=['build_ext']).build_ext
return True
except Exception:
pass
return False
|
[
"Return",
"True",
"if",
"Cython",
"or",
"Pyrex",
"can",
"be",
"imported",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/extension.py#L15-L27
|
[
"def",
"have_pyrex",
"(",
")",
":",
"pyrex_impls",
"=",
"'Cython.Distutils.build_ext'",
",",
"'Pyrex.Distutils.build_ext'",
"for",
"pyrex_impl",
"in",
"pyrex_impls",
":",
"try",
":",
"# from (pyrex_impl) import build_ext",
"__import__",
"(",
"pyrex_impl",
",",
"fromlist",
"=",
"[",
"'build_ext'",
"]",
")",
".",
"build_ext",
"return",
"True",
"except",
"Exception",
":",
"pass",
"return",
"False"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Extension._convert_pyx_sources_to_lang
|
Replace sources with .pyx extensions to sources with the target
language extension. This mechanism allows language authors to supply
pre-converted sources but to prefer the .pyx sources.
|
capybara/virtualenv/lib/python2.7/site-packages/setuptools/extension.py
|
def _convert_pyx_sources_to_lang(self):
"""
Replace sources with .pyx extensions to sources with the target
language extension. This mechanism allows language authors to supply
pre-converted sources but to prefer the .pyx sources.
"""
if have_pyrex():
# the build has Cython, so allow it to compile the .pyx files
return
lang = self.language or ''
target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
sub = functools.partial(re.sub, '.pyx$', target_ext)
self.sources = list(map(sub, self.sources))
|
def _convert_pyx_sources_to_lang(self):
"""
Replace sources with .pyx extensions to sources with the target
language extension. This mechanism allows language authors to supply
pre-converted sources but to prefer the .pyx sources.
"""
if have_pyrex():
# the build has Cython, so allow it to compile the .pyx files
return
lang = self.language or ''
target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
sub = functools.partial(re.sub, '.pyx$', target_ext)
self.sources = list(map(sub, self.sources))
|
[
"Replace",
"sources",
"with",
".",
"pyx",
"extensions",
"to",
"sources",
"with",
"the",
"target",
"language",
"extension",
".",
"This",
"mechanism",
"allows",
"language",
"authors",
"to",
"supply",
"pre",
"-",
"converted",
"sources",
"but",
"to",
"prefer",
"the",
".",
"pyx",
"sources",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/extension.py#L37-L49
|
[
"def",
"_convert_pyx_sources_to_lang",
"(",
"self",
")",
":",
"if",
"have_pyrex",
"(",
")",
":",
"# the build has Cython, so allow it to compile the .pyx files",
"return",
"lang",
"=",
"self",
".",
"language",
"or",
"''",
"target_ext",
"=",
"'.cpp'",
"if",
"lang",
".",
"lower",
"(",
")",
"==",
"'c++'",
"else",
"'.c'",
"sub",
"=",
"functools",
".",
"partial",
"(",
"re",
".",
"sub",
",",
"'.pyx$'",
",",
"target_ext",
")",
"self",
".",
"sources",
"=",
"list",
"(",
"map",
"(",
"sub",
",",
"self",
".",
"sources",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
DebuggedApplication.debug_application
|
Run the application and conserve the traceback frames.
|
capybara/virtualenv/lib/python2.7/site-packages/werkzeug/debug/__init__.py
|
def debug_application(self, environ, start_response):
"""Run the application and conserve the traceback frames."""
app_iter = None
try:
app_iter = self.app(environ, start_response)
for item in app_iter:
yield item
if hasattr(app_iter, 'close'):
app_iter.close()
except Exception:
if hasattr(app_iter, 'close'):
app_iter.close()
traceback = get_current_traceback(skip=1, show_hidden_frames=
self.show_hidden_frames,
ignore_system_exceptions=True)
for frame in traceback.frames:
self.frames[frame.id] = frame
self.tracebacks[traceback.id] = traceback
try:
start_response('500 INTERNAL SERVER ERROR', [
('Content-Type', 'text/html; charset=utf-8'),
# Disable Chrome's XSS protection, the debug
# output can cause false-positives.
('X-XSS-Protection', '0'),
])
except Exception:
# if we end up here there has been output but an error
# occurred. in that situation we can do nothing fancy any
# more, better log something into the error log and fall
# back gracefully.
environ['wsgi.errors'].write(
'Debugging middleware caught exception in streamed '
'response at a point where response headers were already '
'sent.\n')
else:
yield traceback.render_full(evalex=self.evalex,
secret=self.secret) \
.encode('utf-8', 'replace')
traceback.log(environ['wsgi.errors'])
|
def debug_application(self, environ, start_response):
"""Run the application and conserve the traceback frames."""
app_iter = None
try:
app_iter = self.app(environ, start_response)
for item in app_iter:
yield item
if hasattr(app_iter, 'close'):
app_iter.close()
except Exception:
if hasattr(app_iter, 'close'):
app_iter.close()
traceback = get_current_traceback(skip=1, show_hidden_frames=
self.show_hidden_frames,
ignore_system_exceptions=True)
for frame in traceback.frames:
self.frames[frame.id] = frame
self.tracebacks[traceback.id] = traceback
try:
start_response('500 INTERNAL SERVER ERROR', [
('Content-Type', 'text/html; charset=utf-8'),
# Disable Chrome's XSS protection, the debug
# output can cause false-positives.
('X-XSS-Protection', '0'),
])
except Exception:
# if we end up here there has been output but an error
# occurred. in that situation we can do nothing fancy any
# more, better log something into the error log and fall
# back gracefully.
environ['wsgi.errors'].write(
'Debugging middleware caught exception in streamed '
'response at a point where response headers were already '
'sent.\n')
else:
yield traceback.render_full(evalex=self.evalex,
secret=self.secret) \
.encode('utf-8', 'replace')
traceback.log(environ['wsgi.errors'])
|
[
"Run",
"the",
"application",
"and",
"conserve",
"the",
"traceback",
"frames",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/werkzeug/debug/__init__.py#L84-L124
|
[
"def",
"debug_application",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"app_iter",
"=",
"None",
"try",
":",
"app_iter",
"=",
"self",
".",
"app",
"(",
"environ",
",",
"start_response",
")",
"for",
"item",
"in",
"app_iter",
":",
"yield",
"item",
"if",
"hasattr",
"(",
"app_iter",
",",
"'close'",
")",
":",
"app_iter",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"if",
"hasattr",
"(",
"app_iter",
",",
"'close'",
")",
":",
"app_iter",
".",
"close",
"(",
")",
"traceback",
"=",
"get_current_traceback",
"(",
"skip",
"=",
"1",
",",
"show_hidden_frames",
"=",
"self",
".",
"show_hidden_frames",
",",
"ignore_system_exceptions",
"=",
"True",
")",
"for",
"frame",
"in",
"traceback",
".",
"frames",
":",
"self",
".",
"frames",
"[",
"frame",
".",
"id",
"]",
"=",
"frame",
"self",
".",
"tracebacks",
"[",
"traceback",
".",
"id",
"]",
"=",
"traceback",
"try",
":",
"start_response",
"(",
"'500 INTERNAL SERVER ERROR'",
",",
"[",
"(",
"'Content-Type'",
",",
"'text/html; charset=utf-8'",
")",
",",
"# Disable Chrome's XSS protection, the debug",
"# output can cause false-positives.",
"(",
"'X-XSS-Protection'",
",",
"'0'",
")",
",",
"]",
")",
"except",
"Exception",
":",
"# if we end up here there has been output but an error",
"# occurred. in that situation we can do nothing fancy any",
"# more, better log something into the error log and fall",
"# back gracefully.",
"environ",
"[",
"'wsgi.errors'",
"]",
".",
"write",
"(",
"'Debugging middleware caught exception in streamed '",
"'response at a point where response headers were already '",
"'sent.\\n'",
")",
"else",
":",
"yield",
"traceback",
".",
"render_full",
"(",
"evalex",
"=",
"self",
".",
"evalex",
",",
"secret",
"=",
"self",
".",
"secret",
")",
".",
"encode",
"(",
"'utf-8'",
",",
"'replace'",
")",
"traceback",
".",
"log",
"(",
"environ",
"[",
"'wsgi.errors'",
"]",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
DebuggedApplication.get_resource
|
Return a static resource from the shared folder.
|
capybara/virtualenv/lib/python2.7/site-packages/werkzeug/debug/__init__.py
|
def get_resource(self, request, filename):
"""Return a static resource from the shared folder."""
filename = join(dirname(__file__), 'shared', basename(filename))
if isfile(filename):
mimetype = mimetypes.guess_type(filename)[0] \
or 'application/octet-stream'
f = open(filename, 'rb')
try:
return Response(f.read(), mimetype=mimetype)
finally:
f.close()
return Response('Not Found', status=404)
|
def get_resource(self, request, filename):
"""Return a static resource from the shared folder."""
filename = join(dirname(__file__), 'shared', basename(filename))
if isfile(filename):
mimetype = mimetypes.guess_type(filename)[0] \
or 'application/octet-stream'
f = open(filename, 'rb')
try:
return Response(f.read(), mimetype=mimetype)
finally:
f.close()
return Response('Not Found', status=404)
|
[
"Return",
"a",
"static",
"resource",
"from",
"the",
"shared",
"folder",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/werkzeug/debug/__init__.py#L146-L157
|
[
"def",
"get_resource",
"(",
"self",
",",
"request",
",",
"filename",
")",
":",
"filename",
"=",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"'shared'",
",",
"basename",
"(",
"filename",
")",
")",
"if",
"isfile",
"(",
"filename",
")",
":",
"mimetype",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"[",
"0",
"]",
"or",
"'application/octet-stream'",
"f",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"try",
":",
"return",
"Response",
"(",
"f",
".",
"read",
"(",
")",
",",
"mimetype",
"=",
"mimetype",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"return",
"Response",
"(",
"'Not Found'",
",",
"status",
"=",
"404",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
user_agent
|
Return a string representing the user agent.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/download.py
|
def user_agent():
"""
Return a string representing the user agent.
"""
data = {
"installer": {"name": "pip", "version": pip.__version__},
"python": platform.python_version(),
"implementation": {
"name": platform.python_implementation(),
},
}
if data["implementation"]["name"] == 'CPython':
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'PyPy':
if sys.pypy_version_info.releaselevel == 'final':
pypy_version_info = sys.pypy_version_info[:3]
else:
pypy_version_info = sys.pypy_version_info
data["implementation"]["version"] = ".".join(
[str(x) for x in pypy_version_info]
)
elif data["implementation"]["name"] == 'Jython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'IronPython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
if sys.platform.startswith("linux"):
distro = dict(filter(
lambda x: x[1],
zip(["name", "version", "id"], platform.linux_distribution()),
))
libc = dict(filter(
lambda x: x[1],
zip(["lib", "version"], platform.libc_ver()),
))
if libc:
distro["libc"] = libc
if distro:
data["distro"] = distro
if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
data["distro"] = {"name": "OS X", "version": platform.mac_ver()[0]}
if platform.system():
data.setdefault("system", {})["name"] = platform.system()
if platform.release():
data.setdefault("system", {})["release"] = platform.release()
if platform.machine():
data["cpu"] = platform.machine()
return "{data[installer][name]}/{data[installer][version]} {json}".format(
data=data,
json=json.dumps(data, separators=(",", ":"), sort_keys=True),
)
|
def user_agent():
"""
Return a string representing the user agent.
"""
data = {
"installer": {"name": "pip", "version": pip.__version__},
"python": platform.python_version(),
"implementation": {
"name": platform.python_implementation(),
},
}
if data["implementation"]["name"] == 'CPython':
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'PyPy':
if sys.pypy_version_info.releaselevel == 'final':
pypy_version_info = sys.pypy_version_info[:3]
else:
pypy_version_info = sys.pypy_version_info
data["implementation"]["version"] = ".".join(
[str(x) for x in pypy_version_info]
)
elif data["implementation"]["name"] == 'Jython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
elif data["implementation"]["name"] == 'IronPython':
# Complete Guess
data["implementation"]["version"] = platform.python_version()
if sys.platform.startswith("linux"):
distro = dict(filter(
lambda x: x[1],
zip(["name", "version", "id"], platform.linux_distribution()),
))
libc = dict(filter(
lambda x: x[1],
zip(["lib", "version"], platform.libc_ver()),
))
if libc:
distro["libc"] = libc
if distro:
data["distro"] = distro
if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
data["distro"] = {"name": "OS X", "version": platform.mac_ver()[0]}
if platform.system():
data.setdefault("system", {})["name"] = platform.system()
if platform.release():
data.setdefault("system", {})["release"] = platform.release()
if platform.machine():
data["cpu"] = platform.machine()
return "{data[installer][name]}/{data[installer][version]} {json}".format(
data=data,
json=json.dumps(data, separators=(",", ":"), sort_keys=True),
)
|
[
"Return",
"a",
"string",
"representing",
"the",
"user",
"agent",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/download.py#L60-L118
|
[
"def",
"user_agent",
"(",
")",
":",
"data",
"=",
"{",
"\"installer\"",
":",
"{",
"\"name\"",
":",
"\"pip\"",
",",
"\"version\"",
":",
"pip",
".",
"__version__",
"}",
",",
"\"python\"",
":",
"platform",
".",
"python_version",
"(",
")",
",",
"\"implementation\"",
":",
"{",
"\"name\"",
":",
"platform",
".",
"python_implementation",
"(",
")",
",",
"}",
",",
"}",
"if",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"name\"",
"]",
"==",
"'CPython'",
":",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"version\"",
"]",
"=",
"platform",
".",
"python_version",
"(",
")",
"elif",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"name\"",
"]",
"==",
"'PyPy'",
":",
"if",
"sys",
".",
"pypy_version_info",
".",
"releaselevel",
"==",
"'final'",
":",
"pypy_version_info",
"=",
"sys",
".",
"pypy_version_info",
"[",
":",
"3",
"]",
"else",
":",
"pypy_version_info",
"=",
"sys",
".",
"pypy_version_info",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"version\"",
"]",
"=",
"\".\"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"pypy_version_info",
"]",
")",
"elif",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"name\"",
"]",
"==",
"'Jython'",
":",
"# Complete Guess",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"version\"",
"]",
"=",
"platform",
".",
"python_version",
"(",
")",
"elif",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"name\"",
"]",
"==",
"'IronPython'",
":",
"# Complete Guess",
"data",
"[",
"\"implementation\"",
"]",
"[",
"\"version\"",
"]",
"=",
"platform",
".",
"python_version",
"(",
")",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
":",
"distro",
"=",
"dict",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"zip",
"(",
"[",
"\"name\"",
",",
"\"version\"",
",",
"\"id\"",
"]",
",",
"platform",
".",
"linux_distribution",
"(",
")",
")",
",",
")",
")",
"libc",
"=",
"dict",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"zip",
"(",
"[",
"\"lib\"",
",",
"\"version\"",
"]",
",",
"platform",
".",
"libc_ver",
"(",
")",
")",
",",
")",
")",
"if",
"libc",
":",
"distro",
"[",
"\"libc\"",
"]",
"=",
"libc",
"if",
"distro",
":",
"data",
"[",
"\"distro\"",
"]",
"=",
"distro",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"darwin\"",
")",
"and",
"platform",
".",
"mac_ver",
"(",
")",
"[",
"0",
"]",
":",
"data",
"[",
"\"distro\"",
"]",
"=",
"{",
"\"name\"",
":",
"\"OS X\"",
",",
"\"version\"",
":",
"platform",
".",
"mac_ver",
"(",
")",
"[",
"0",
"]",
"}",
"if",
"platform",
".",
"system",
"(",
")",
":",
"data",
".",
"setdefault",
"(",
"\"system\"",
",",
"{",
"}",
")",
"[",
"\"name\"",
"]",
"=",
"platform",
".",
"system",
"(",
")",
"if",
"platform",
".",
"release",
"(",
")",
":",
"data",
".",
"setdefault",
"(",
"\"system\"",
",",
"{",
"}",
")",
"[",
"\"release\"",
"]",
"=",
"platform",
".",
"release",
"(",
")",
"if",
"platform",
".",
"machine",
"(",
")",
":",
"data",
"[",
"\"cpu\"",
"]",
"=",
"platform",
".",
"machine",
"(",
")",
"return",
"\"{data[installer][name]}/{data[installer][version]} {json}\"",
".",
"format",
"(",
"data",
"=",
"data",
",",
"json",
"=",
"json",
".",
"dumps",
"(",
"data",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\":\"",
")",
",",
"sort_keys",
"=",
"True",
")",
",",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
get_file_content
|
Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/download.py
|
def get_file_content(url, comes_from=None, session=None):
"""Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode."""
if session is None:
raise TypeError(
"get_file_content() missing 1 required keyword argument: 'session'"
)
match = _scheme_re.search(url)
if match:
scheme = match.group(1).lower()
if (scheme == 'file' and comes_from and
comes_from.startswith('http')):
raise InstallationError(
'Requirements file %s references URL %s, which is local'
% (comes_from, url))
if scheme == 'file':
path = url.split(':', 1)[1]
path = path.replace('\\', '/')
match = _url_slash_drive_re.match(path)
if match:
path = match.group(1) + ':' + path.split('|', 1)[1]
path = urllib_parse.unquote(path)
if path.startswith('/'):
path = '/' + path.lstrip('/')
url = path
else:
# FIXME: catch some errors
resp = session.get(url)
resp.raise_for_status()
if six.PY3:
return resp.url, resp.text
else:
return resp.url, resp.content
try:
with open(url) as f:
content = f.read()
except IOError as exc:
raise InstallationError(
'Could not open requirements file: %s' % str(exc)
)
return url, content
|
def get_file_content(url, comes_from=None, session=None):
"""Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode."""
if session is None:
raise TypeError(
"get_file_content() missing 1 required keyword argument: 'session'"
)
match = _scheme_re.search(url)
if match:
scheme = match.group(1).lower()
if (scheme == 'file' and comes_from and
comes_from.startswith('http')):
raise InstallationError(
'Requirements file %s references URL %s, which is local'
% (comes_from, url))
if scheme == 'file':
path = url.split(':', 1)[1]
path = path.replace('\\', '/')
match = _url_slash_drive_re.match(path)
if match:
path = match.group(1) + ':' + path.split('|', 1)[1]
path = urllib_parse.unquote(path)
if path.startswith('/'):
path = '/' + path.lstrip('/')
url = path
else:
# FIXME: catch some errors
resp = session.get(url)
resp.raise_for_status()
if six.PY3:
return resp.url, resp.text
else:
return resp.url, resp.content
try:
with open(url) as f:
content = f.read()
except IOError as exc:
raise InstallationError(
'Could not open requirements file: %s' % str(exc)
)
return url, content
|
[
"Gets",
"the",
"content",
"of",
"a",
"file",
";",
"it",
"may",
"be",
"a",
"filename",
"file",
":",
"URL",
"or",
"http",
":",
"URL",
".",
"Returns",
"(",
"location",
"content",
")",
".",
"Content",
"is",
"unicode",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/download.py#L376-L418
|
[
"def",
"get_file_content",
"(",
"url",
",",
"comes_from",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"if",
"session",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"get_file_content() missing 1 required keyword argument: 'session'\"",
")",
"match",
"=",
"_scheme_re",
".",
"search",
"(",
"url",
")",
"if",
"match",
":",
"scheme",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
"if",
"(",
"scheme",
"==",
"'file'",
"and",
"comes_from",
"and",
"comes_from",
".",
"startswith",
"(",
"'http'",
")",
")",
":",
"raise",
"InstallationError",
"(",
"'Requirements file %s references URL %s, which is local'",
"%",
"(",
"comes_from",
",",
"url",
")",
")",
"if",
"scheme",
"==",
"'file'",
":",
"path",
"=",
"url",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"1",
"]",
"path",
"=",
"path",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"match",
"=",
"_url_slash_drive_re",
".",
"match",
"(",
"path",
")",
"if",
"match",
":",
"path",
"=",
"match",
".",
"group",
"(",
"1",
")",
"+",
"':'",
"+",
"path",
".",
"split",
"(",
"'|'",
",",
"1",
")",
"[",
"1",
"]",
"path",
"=",
"urllib_parse",
".",
"unquote",
"(",
"path",
")",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"path",
"=",
"'/'",
"+",
"path",
".",
"lstrip",
"(",
"'/'",
")",
"url",
"=",
"path",
"else",
":",
"# FIXME: catch some errors",
"resp",
"=",
"session",
".",
"get",
"(",
"url",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"if",
"six",
".",
"PY3",
":",
"return",
"resp",
".",
"url",
",",
"resp",
".",
"text",
"else",
":",
"return",
"resp",
".",
"url",
",",
"resp",
".",
"content",
"try",
":",
"with",
"open",
"(",
"url",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"except",
"IOError",
"as",
"exc",
":",
"raise",
"InstallationError",
"(",
"'Could not open requirements file: %s'",
"%",
"str",
"(",
"exc",
")",
")",
"return",
"url",
",",
"content"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
is_url
|
Returns true if the name looks like a URL
|
capybara/virtualenv/lib/python2.7/site-packages/pip/download.py
|
def is_url(name):
"""Returns true if the name looks like a URL"""
if ':' not in name:
return False
scheme = name.split(':', 1)[0].lower()
return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes
|
def is_url(name):
"""Returns true if the name looks like a URL"""
if ':' not in name:
return False
scheme = name.split(':', 1)[0].lower()
return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes
|
[
"Returns",
"true",
"if",
"the",
"name",
"looks",
"like",
"a",
"URL"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/download.py#L425-L430
|
[
"def",
"is_url",
"(",
"name",
")",
":",
"if",
"':'",
"not",
"in",
"name",
":",
"return",
"False",
"scheme",
"=",
"name",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"return",
"scheme",
"in",
"[",
"'http'",
",",
"'https'",
",",
"'file'",
",",
"'ftp'",
"]",
"+",
"vcs",
".",
"all_schemes"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
unpack_file_url
|
Unpack link into location.
If download_dir is provided and link points to a file, make a copy
of the link file inside download_dir.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/download.py
|
def unpack_file_url(link, location, download_dir=None):
"""Unpack link into location.
If download_dir is provided and link points to a file, make a copy
of the link file inside download_dir."""
link_path = url_to_path(link.url_without_fragment)
# If it's a url to a local directory
if os.path.isdir(link_path):
if os.path.isdir(location):
rmtree(location)
shutil.copytree(link_path, location, symlinks=True)
if download_dir:
logger.info('Link is a directory, ignoring download_dir')
return
# if link has a hash, let's confirm it matches
if link.hash:
link_path_hash = _get_hash_from_file(link_path, link)
_check_hash(link_path_hash, link)
# If a download dir is specified, is the file already there and valid?
already_downloaded_path = None
if download_dir:
already_downloaded_path = _check_download_dir(link, download_dir)
if already_downloaded_path:
from_path = already_downloaded_path
else:
from_path = link_path
content_type = mimetypes.guess_type(from_path)[0]
# unpack the archive to the build dir location. even when only downloading
# archives, they have to be unpacked to parse dependencies
unpack_file(from_path, location, content_type, link)
# a download dir is specified and not already downloaded
if download_dir and not already_downloaded_path:
_copy_file(from_path, download_dir, content_type, link)
|
def unpack_file_url(link, location, download_dir=None):
"""Unpack link into location.
If download_dir is provided and link points to a file, make a copy
of the link file inside download_dir."""
link_path = url_to_path(link.url_without_fragment)
# If it's a url to a local directory
if os.path.isdir(link_path):
if os.path.isdir(location):
rmtree(location)
shutil.copytree(link_path, location, symlinks=True)
if download_dir:
logger.info('Link is a directory, ignoring download_dir')
return
# if link has a hash, let's confirm it matches
if link.hash:
link_path_hash = _get_hash_from_file(link_path, link)
_check_hash(link_path_hash, link)
# If a download dir is specified, is the file already there and valid?
already_downloaded_path = None
if download_dir:
already_downloaded_path = _check_download_dir(link, download_dir)
if already_downloaded_path:
from_path = already_downloaded_path
else:
from_path = link_path
content_type = mimetypes.guess_type(from_path)[0]
# unpack the archive to the build dir location. even when only downloading
# archives, they have to be unpacked to parse dependencies
unpack_file(from_path, location, content_type, link)
# a download dir is specified and not already downloaded
if download_dir and not already_downloaded_path:
_copy_file(from_path, download_dir, content_type, link)
|
[
"Unpack",
"link",
"into",
"location",
".",
"If",
"download_dir",
"is",
"provided",
"and",
"link",
"points",
"to",
"a",
"file",
"make",
"a",
"copy",
"of",
"the",
"link",
"file",
"inside",
"download_dir",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/download.py#L688-L727
|
[
"def",
"unpack_file_url",
"(",
"link",
",",
"location",
",",
"download_dir",
"=",
"None",
")",
":",
"link_path",
"=",
"url_to_path",
"(",
"link",
".",
"url_without_fragment",
")",
"# If it's a url to a local directory",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"link_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"location",
")",
":",
"rmtree",
"(",
"location",
")",
"shutil",
".",
"copytree",
"(",
"link_path",
",",
"location",
",",
"symlinks",
"=",
"True",
")",
"if",
"download_dir",
":",
"logger",
".",
"info",
"(",
"'Link is a directory, ignoring download_dir'",
")",
"return",
"# if link has a hash, let's confirm it matches",
"if",
"link",
".",
"hash",
":",
"link_path_hash",
"=",
"_get_hash_from_file",
"(",
"link_path",
",",
"link",
")",
"_check_hash",
"(",
"link_path_hash",
",",
"link",
")",
"# If a download dir is specified, is the file already there and valid?",
"already_downloaded_path",
"=",
"None",
"if",
"download_dir",
":",
"already_downloaded_path",
"=",
"_check_download_dir",
"(",
"link",
",",
"download_dir",
")",
"if",
"already_downloaded_path",
":",
"from_path",
"=",
"already_downloaded_path",
"else",
":",
"from_path",
"=",
"link_path",
"content_type",
"=",
"mimetypes",
".",
"guess_type",
"(",
"from_path",
")",
"[",
"0",
"]",
"# unpack the archive to the build dir location. even when only downloading",
"# archives, they have to be unpacked to parse dependencies",
"unpack_file",
"(",
"from_path",
",",
"location",
",",
"content_type",
",",
"link",
")",
"# a download dir is specified and not already downloaded",
"if",
"download_dir",
"and",
"not",
"already_downloaded_path",
":",
"_copy_file",
"(",
"from_path",
",",
"download_dir",
",",
"content_type",
",",
"link",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
_download_http_url
|
Download link url into temp_dir using provided session
|
capybara/virtualenv/lib/python2.7/site-packages/pip/download.py
|
def _download_http_url(link, session, temp_dir):
"""Download link url into temp_dir using provided session"""
target_url = link.url.split('#', 1)[0]
try:
resp = session.get(
target_url,
# We use Accept-Encoding: identity here because requests
# defaults to accepting compressed responses. This breaks in
# a variety of ways depending on how the server is configured.
# - Some servers will notice that the file isn't a compressible
# file and will leave the file alone and with an empty
# Content-Encoding
# - Some servers will notice that the file is already
# compressed and will leave the file alone and will add a
# Content-Encoding: gzip header
# - Some servers won't notice anything at all and will take
# a file that's already been compressed and compress it again
# and set the Content-Encoding: gzip header
# By setting this to request only the identity encoding We're
# hoping to eliminate the third case. Hopefully there does not
# exist a server which when given a file will notice it is
# already compressed and that you're not asking for a
# compressed file and will then decompress it before sending
# because if that's the case I don't think it'll ever be
# possible to make this work.
headers={"Accept-Encoding": "identity"},
stream=True,
)
resp.raise_for_status()
except requests.HTTPError as exc:
logger.critical(
"HTTP error %s while getting %s", exc.response.status_code, link,
)
raise
content_type = resp.headers.get('content-type', '')
filename = link.filename # fallback
# Have a look at the Content-Disposition header for a better guess
content_disposition = resp.headers.get('content-disposition')
if content_disposition:
type, params = cgi.parse_header(content_disposition)
# We use ``or`` here because we don't want to use an "empty" value
# from the filename param.
filename = params.get('filename') or filename
ext = splitext(filename)[1]
if not ext:
ext = mimetypes.guess_extension(content_type)
if ext:
filename += ext
if not ext and link.url != resp.url:
ext = os.path.splitext(resp.url)[1]
if ext:
filename += ext
file_path = os.path.join(temp_dir, filename)
with open(file_path, 'wb') as content_file:
_download_url(resp, link, content_file)
return file_path, content_type
|
def _download_http_url(link, session, temp_dir):
"""Download link url into temp_dir using provided session"""
target_url = link.url.split('#', 1)[0]
try:
resp = session.get(
target_url,
# We use Accept-Encoding: identity here because requests
# defaults to accepting compressed responses. This breaks in
# a variety of ways depending on how the server is configured.
# - Some servers will notice that the file isn't a compressible
# file and will leave the file alone and with an empty
# Content-Encoding
# - Some servers will notice that the file is already
# compressed and will leave the file alone and will add a
# Content-Encoding: gzip header
# - Some servers won't notice anything at all and will take
# a file that's already been compressed and compress it again
# and set the Content-Encoding: gzip header
# By setting this to request only the identity encoding We're
# hoping to eliminate the third case. Hopefully there does not
# exist a server which when given a file will notice it is
# already compressed and that you're not asking for a
# compressed file and will then decompress it before sending
# because if that's the case I don't think it'll ever be
# possible to make this work.
headers={"Accept-Encoding": "identity"},
stream=True,
)
resp.raise_for_status()
except requests.HTTPError as exc:
logger.critical(
"HTTP error %s while getting %s", exc.response.status_code, link,
)
raise
content_type = resp.headers.get('content-type', '')
filename = link.filename # fallback
# Have a look at the Content-Disposition header for a better guess
content_disposition = resp.headers.get('content-disposition')
if content_disposition:
type, params = cgi.parse_header(content_disposition)
# We use ``or`` here because we don't want to use an "empty" value
# from the filename param.
filename = params.get('filename') or filename
ext = splitext(filename)[1]
if not ext:
ext = mimetypes.guess_extension(content_type)
if ext:
filename += ext
if not ext and link.url != resp.url:
ext = os.path.splitext(resp.url)[1]
if ext:
filename += ext
file_path = os.path.join(temp_dir, filename)
with open(file_path, 'wb') as content_file:
_download_url(resp, link, content_file)
return file_path, content_type
|
[
"Download",
"link",
"url",
"into",
"temp_dir",
"using",
"provided",
"session"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/download.py#L831-L887
|
[
"def",
"_download_http_url",
"(",
"link",
",",
"session",
",",
"temp_dir",
")",
":",
"target_url",
"=",
"link",
".",
"url",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"[",
"0",
"]",
"try",
":",
"resp",
"=",
"session",
".",
"get",
"(",
"target_url",
",",
"# We use Accept-Encoding: identity here because requests",
"# defaults to accepting compressed responses. This breaks in",
"# a variety of ways depending on how the server is configured.",
"# - Some servers will notice that the file isn't a compressible",
"# file and will leave the file alone and with an empty",
"# Content-Encoding",
"# - Some servers will notice that the file is already",
"# compressed and will leave the file alone and will add a",
"# Content-Encoding: gzip header",
"# - Some servers won't notice anything at all and will take",
"# a file that's already been compressed and compress it again",
"# and set the Content-Encoding: gzip header",
"# By setting this to request only the identity encoding We're",
"# hoping to eliminate the third case. Hopefully there does not",
"# exist a server which when given a file will notice it is",
"# already compressed and that you're not asking for a",
"# compressed file and will then decompress it before sending",
"# because if that's the case I don't think it'll ever be",
"# possible to make this work.",
"headers",
"=",
"{",
"\"Accept-Encoding\"",
":",
"\"identity\"",
"}",
",",
"stream",
"=",
"True",
",",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"exc",
":",
"logger",
".",
"critical",
"(",
"\"HTTP error %s while getting %s\"",
",",
"exc",
".",
"response",
".",
"status_code",
",",
"link",
",",
")",
"raise",
"content_type",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'content-type'",
",",
"''",
")",
"filename",
"=",
"link",
".",
"filename",
"# fallback",
"# Have a look at the Content-Disposition header for a better guess",
"content_disposition",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'content-disposition'",
")",
"if",
"content_disposition",
":",
"type",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"content_disposition",
")",
"# We use ``or`` here because we don't want to use an \"empty\" value",
"# from the filename param.",
"filename",
"=",
"params",
".",
"get",
"(",
"'filename'",
")",
"or",
"filename",
"ext",
"=",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"if",
"not",
"ext",
":",
"ext",
"=",
"mimetypes",
".",
"guess_extension",
"(",
"content_type",
")",
"if",
"ext",
":",
"filename",
"+=",
"ext",
"if",
"not",
"ext",
"and",
"link",
".",
"url",
"!=",
"resp",
".",
"url",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"resp",
".",
"url",
")",
"[",
"1",
"]",
"if",
"ext",
":",
"filename",
"+=",
"ext",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"filename",
")",
"with",
"open",
"(",
"file_path",
",",
"'wb'",
")",
"as",
"content_file",
":",
"_download_url",
"(",
"resp",
",",
"link",
",",
"content_file",
")",
"return",
"file_path",
",",
"content_type"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
_check_download_dir
|
Check download_dir for previously downloaded file with correct hash
If a correct file is found return its path else None
|
capybara/virtualenv/lib/python2.7/site-packages/pip/download.py
|
def _check_download_dir(link, download_dir):
""" Check download_dir for previously downloaded file with correct hash
If a correct file is found return its path else None
"""
download_path = os.path.join(download_dir, link.filename)
if os.path.exists(download_path):
# If already downloaded, does its hash match?
logger.info('File was already downloaded %s', download_path)
if link.hash:
download_hash = _get_hash_from_file(download_path, link)
try:
_check_hash(download_hash, link)
except HashMismatch:
logger.warning(
'Previously-downloaded file %s has bad hash, '
're-downloading.',
download_path
)
os.unlink(download_path)
return None
return download_path
return None
|
def _check_download_dir(link, download_dir):
""" Check download_dir for previously downloaded file with correct hash
If a correct file is found return its path else None
"""
download_path = os.path.join(download_dir, link.filename)
if os.path.exists(download_path):
# If already downloaded, does its hash match?
logger.info('File was already downloaded %s', download_path)
if link.hash:
download_hash = _get_hash_from_file(download_path, link)
try:
_check_hash(download_hash, link)
except HashMismatch:
logger.warning(
'Previously-downloaded file %s has bad hash, '
're-downloading.',
download_path
)
os.unlink(download_path)
return None
return download_path
return None
|
[
"Check",
"download_dir",
"for",
"previously",
"downloaded",
"file",
"with",
"correct",
"hash",
"If",
"a",
"correct",
"file",
"is",
"found",
"return",
"its",
"path",
"else",
"None"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/download.py#L890-L911
|
[
"def",
"_check_download_dir",
"(",
"link",
",",
"download_dir",
")",
":",
"download_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"download_dir",
",",
"link",
".",
"filename",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"download_path",
")",
":",
"# If already downloaded, does its hash match?",
"logger",
".",
"info",
"(",
"'File was already downloaded %s'",
",",
"download_path",
")",
"if",
"link",
".",
"hash",
":",
"download_hash",
"=",
"_get_hash_from_file",
"(",
"download_path",
",",
"link",
")",
"try",
":",
"_check_hash",
"(",
"download_hash",
",",
"link",
")",
"except",
"HashMismatch",
":",
"logger",
".",
"warning",
"(",
"'Previously-downloaded file %s has bad hash, '",
"'re-downloading.'",
",",
"download_path",
")",
"os",
".",
"unlink",
"(",
"download_path",
")",
"return",
"None",
"return",
"download_path",
"return",
"None"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
CurrencyHandler.currencyFormat
|
Handle currencyFormat subdirectives.
|
pricing/metaconfigure.py
|
def currencyFormat(_context, code, symbol, format,
currency_digits=True, decimal_quantization=True,
name=''):
"""Handle currencyFormat subdirectives."""
_context.action(
discriminator=('currency', name, code),
callable=_register_currency,
args=(name, code, symbol, format, currency_digits,
decimal_quantization)
)
|
def currencyFormat(_context, code, symbol, format,
currency_digits=True, decimal_quantization=True,
name=''):
"""Handle currencyFormat subdirectives."""
_context.action(
discriminator=('currency', name, code),
callable=_register_currency,
args=(name, code, symbol, format, currency_digits,
decimal_quantization)
)
|
[
"Handle",
"currencyFormat",
"subdirectives",
"."
] |
joeblackwaslike/pricing
|
python
|
https://github.com/joeblackwaslike/pricing/blob/be988b0851b4313af81f1db475bc33248700e39c/pricing/metaconfigure.py#L37-L46
|
[
"def",
"currencyFormat",
"(",
"_context",
",",
"code",
",",
"symbol",
",",
"format",
",",
"currency_digits",
"=",
"True",
",",
"decimal_quantization",
"=",
"True",
",",
"name",
"=",
"''",
")",
":",
"_context",
".",
"action",
"(",
"discriminator",
"=",
"(",
"'currency'",
",",
"name",
",",
"code",
")",
",",
"callable",
"=",
"_register_currency",
",",
"args",
"=",
"(",
"name",
",",
"code",
",",
"symbol",
",",
"format",
",",
"currency_digits",
",",
"decimal_quantization",
")",
")"
] |
be988b0851b4313af81f1db475bc33248700e39c
|
test
|
CurrencyHandler.exchange
|
Handle exchange subdirectives.
|
pricing/metaconfigure.py
|
def exchange(_context, component, backend, base, name=''):
"""Handle exchange subdirectives."""
_context.action(
discriminator=('currency', 'exchange', component),
callable=_register_exchange,
args=(name, component, backend, base)
)
|
def exchange(_context, component, backend, base, name=''):
"""Handle exchange subdirectives."""
_context.action(
discriminator=('currency', 'exchange', component),
callable=_register_exchange,
args=(name, component, backend, base)
)
|
[
"Handle",
"exchange",
"subdirectives",
"."
] |
joeblackwaslike/pricing
|
python
|
https://github.com/joeblackwaslike/pricing/blob/be988b0851b4313af81f1db475bc33248700e39c/pricing/metaconfigure.py#L49-L55
|
[
"def",
"exchange",
"(",
"_context",
",",
"component",
",",
"backend",
",",
"base",
",",
"name",
"=",
"''",
")",
":",
"_context",
".",
"action",
"(",
"discriminator",
"=",
"(",
"'currency'",
",",
"'exchange'",
",",
"component",
")",
",",
"callable",
"=",
"_register_exchange",
",",
"args",
"=",
"(",
"name",
",",
"component",
",",
"backend",
",",
"base",
")",
")"
] |
be988b0851b4313af81f1db475bc33248700e39c
|
test
|
print_results
|
Print the informations from installed distributions found.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/commands/show.py
|
def print_results(distributions, list_all_files):
"""
Print the informations from installed distributions found.
"""
results_printed = False
for dist in distributions:
results_printed = True
logger.info("---")
logger.info("Metadata-Version: %s" % dist.get('metadata-version'))
logger.info("Name: %s" % dist['name'])
logger.info("Version: %s" % dist['version'])
logger.info("Summary: %s" % dist.get('summary'))
logger.info("Home-page: %s" % dist.get('home-page'))
logger.info("Author: %s" % dist.get('author'))
logger.info("Author-email: %s" % dist.get('author-email'))
logger.info("License: %s" % dist.get('license'))
logger.info("Location: %s" % dist['location'])
logger.info("Requires: %s" % ', '.join(dist['requires']))
if list_all_files:
logger.info("Files:")
if dist['files'] is not None:
for line in dist['files']:
logger.info(" %s" % line.strip())
else:
logger.info("Cannot locate installed-files.txt")
if 'entry_points' in dist:
logger.info("Entry-points:")
for line in dist['entry_points']:
logger.info(" %s" % line.strip())
return results_printed
|
def print_results(distributions, list_all_files):
"""
Print the informations from installed distributions found.
"""
results_printed = False
for dist in distributions:
results_printed = True
logger.info("---")
logger.info("Metadata-Version: %s" % dist.get('metadata-version'))
logger.info("Name: %s" % dist['name'])
logger.info("Version: %s" % dist['version'])
logger.info("Summary: %s" % dist.get('summary'))
logger.info("Home-page: %s" % dist.get('home-page'))
logger.info("Author: %s" % dist.get('author'))
logger.info("Author-email: %s" % dist.get('author-email'))
logger.info("License: %s" % dist.get('license'))
logger.info("Location: %s" % dist['location'])
logger.info("Requires: %s" % ', '.join(dist['requires']))
if list_all_files:
logger.info("Files:")
if dist['files'] is not None:
for line in dist['files']:
logger.info(" %s" % line.strip())
else:
logger.info("Cannot locate installed-files.txt")
if 'entry_points' in dist:
logger.info("Entry-points:")
for line in dist['entry_points']:
logger.info(" %s" % line.strip())
return results_printed
|
[
"Print",
"the",
"informations",
"from",
"installed",
"distributions",
"found",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/commands/show.py#L101-L130
|
[
"def",
"print_results",
"(",
"distributions",
",",
"list_all_files",
")",
":",
"results_printed",
"=",
"False",
"for",
"dist",
"in",
"distributions",
":",
"results_printed",
"=",
"True",
"logger",
".",
"info",
"(",
"\"---\"",
")",
"logger",
".",
"info",
"(",
"\"Metadata-Version: %s\"",
"%",
"dist",
".",
"get",
"(",
"'metadata-version'",
")",
")",
"logger",
".",
"info",
"(",
"\"Name: %s\"",
"%",
"dist",
"[",
"'name'",
"]",
")",
"logger",
".",
"info",
"(",
"\"Version: %s\"",
"%",
"dist",
"[",
"'version'",
"]",
")",
"logger",
".",
"info",
"(",
"\"Summary: %s\"",
"%",
"dist",
".",
"get",
"(",
"'summary'",
")",
")",
"logger",
".",
"info",
"(",
"\"Home-page: %s\"",
"%",
"dist",
".",
"get",
"(",
"'home-page'",
")",
")",
"logger",
".",
"info",
"(",
"\"Author: %s\"",
"%",
"dist",
".",
"get",
"(",
"'author'",
")",
")",
"logger",
".",
"info",
"(",
"\"Author-email: %s\"",
"%",
"dist",
".",
"get",
"(",
"'author-email'",
")",
")",
"logger",
".",
"info",
"(",
"\"License: %s\"",
"%",
"dist",
".",
"get",
"(",
"'license'",
")",
")",
"logger",
".",
"info",
"(",
"\"Location: %s\"",
"%",
"dist",
"[",
"'location'",
"]",
")",
"logger",
".",
"info",
"(",
"\"Requires: %s\"",
"%",
"', '",
".",
"join",
"(",
"dist",
"[",
"'requires'",
"]",
")",
")",
"if",
"list_all_files",
":",
"logger",
".",
"info",
"(",
"\"Files:\"",
")",
"if",
"dist",
"[",
"'files'",
"]",
"is",
"not",
"None",
":",
"for",
"line",
"in",
"dist",
"[",
"'files'",
"]",
":",
"logger",
".",
"info",
"(",
"\" %s\"",
"%",
"line",
".",
"strip",
"(",
")",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"Cannot locate installed-files.txt\"",
")",
"if",
"'entry_points'",
"in",
"dist",
":",
"logger",
".",
"info",
"(",
"\"Entry-points:\"",
")",
"for",
"line",
"in",
"dist",
"[",
"'entry_points'",
"]",
":",
"logger",
".",
"info",
"(",
"\" %s\"",
"%",
"line",
".",
"strip",
"(",
")",
")",
"return",
"results_printed"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
HTTPResponse._decode
|
Decode the data passed in and potentially flush the decoder.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py
|
def _decode(self, data, decode_content, flush_decoder):
"""
Decode the data passed in and potentially flush the decoder.
"""
try:
if decode_content and self._decoder:
data = self._decoder.decompress(data)
except (IOError, zlib.error) as e:
content_encoding = self.headers.get('content-encoding', '').lower()
raise DecodeError(
"Received response with content-encoding: %s, but "
"failed to decode it." % content_encoding, e)
if flush_decoder and decode_content and self._decoder:
buf = self._decoder.decompress(binary_type())
data += buf + self._decoder.flush()
return data
|
def _decode(self, data, decode_content, flush_decoder):
"""
Decode the data passed in and potentially flush the decoder.
"""
try:
if decode_content and self._decoder:
data = self._decoder.decompress(data)
except (IOError, zlib.error) as e:
content_encoding = self.headers.get('content-encoding', '').lower()
raise DecodeError(
"Received response with content-encoding: %s, but "
"failed to decode it." % content_encoding, e)
if flush_decoder and decode_content and self._decoder:
buf = self._decoder.decompress(binary_type())
data += buf + self._decoder.flush()
return data
|
[
"Decode",
"the",
"data",
"passed",
"in",
"and",
"potentially",
"flush",
"the",
"decoder",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py#L186-L203
|
[
"def",
"_decode",
"(",
"self",
",",
"data",
",",
"decode_content",
",",
"flush_decoder",
")",
":",
"try",
":",
"if",
"decode_content",
"and",
"self",
".",
"_decoder",
":",
"data",
"=",
"self",
".",
"_decoder",
".",
"decompress",
"(",
"data",
")",
"except",
"(",
"IOError",
",",
"zlib",
".",
"error",
")",
"as",
"e",
":",
"content_encoding",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'content-encoding'",
",",
"''",
")",
".",
"lower",
"(",
")",
"raise",
"DecodeError",
"(",
"\"Received response with content-encoding: %s, but \"",
"\"failed to decode it.\"",
"%",
"content_encoding",
",",
"e",
")",
"if",
"flush_decoder",
"and",
"decode_content",
"and",
"self",
".",
"_decoder",
":",
"buf",
"=",
"self",
".",
"_decoder",
".",
"decompress",
"(",
"binary_type",
"(",
")",
")",
"data",
"+=",
"buf",
"+",
"self",
".",
"_decoder",
".",
"flush",
"(",
")",
"return",
"data"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
HTTPResponse.read
|
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
|
capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py
|
def read(self, amt=None, decode_content=None, cache_content=False):
"""
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
"""
self._init_decoder()
if decode_content is None:
decode_content = self.decode_content
if self._fp is None:
return
flush_decoder = False
try:
try:
if amt is None:
# cStringIO doesn't like amt=None
data = self._fp.read()
flush_decoder = True
else:
cache_content = False
data = self._fp.read(amt)
if amt != 0 and not data: # Platform-specific: Buggy versions of Python.
# Close the connection when no data is returned
#
# This is redundant to what httplib/http.client _should_
# already do. However, versions of python released before
# December 15, 2012 (http://bugs.python.org/issue16298) do
# not properly close the connection in all cases. There is
# no harm in redundantly calling close.
self._fp.close()
flush_decoder = True
except SocketTimeout:
# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
# there is yet no clean way to get at it from this context.
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except BaseSSLError as e:
# FIXME: Is there a better way to differentiate between SSLErrors?
if 'read operation timed out' not in str(e): # Defensive:
# This shouldn't happen but just in case we're missing an edge
# case, let's avoid swallowing SSL errors.
raise
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except HTTPException as e:
# This includes IncompleteRead.
raise ProtocolError('Connection broken: %r' % e, e)
self._fp_bytes_read += len(data)
data = self._decode(data, decode_content, flush_decoder)
if cache_content:
self._body = data
return data
finally:
if self._original_response and self._original_response.isclosed():
self.release_conn()
|
def read(self, amt=None, decode_content=None, cache_content=False):
"""
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
"""
self._init_decoder()
if decode_content is None:
decode_content = self.decode_content
if self._fp is None:
return
flush_decoder = False
try:
try:
if amt is None:
# cStringIO doesn't like amt=None
data = self._fp.read()
flush_decoder = True
else:
cache_content = False
data = self._fp.read(amt)
if amt != 0 and not data: # Platform-specific: Buggy versions of Python.
# Close the connection when no data is returned
#
# This is redundant to what httplib/http.client _should_
# already do. However, versions of python released before
# December 15, 2012 (http://bugs.python.org/issue16298) do
# not properly close the connection in all cases. There is
# no harm in redundantly calling close.
self._fp.close()
flush_decoder = True
except SocketTimeout:
# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
# there is yet no clean way to get at it from this context.
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except BaseSSLError as e:
# FIXME: Is there a better way to differentiate between SSLErrors?
if 'read operation timed out' not in str(e): # Defensive:
# This shouldn't happen but just in case we're missing an edge
# case, let's avoid swallowing SSL errors.
raise
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
except HTTPException as e:
# This includes IncompleteRead.
raise ProtocolError('Connection broken: %r' % e, e)
self._fp_bytes_read += len(data)
data = self._decode(data, decode_content, flush_decoder)
if cache_content:
self._body = data
return data
finally:
if self._original_response and self._original_response.isclosed():
self.release_conn()
|
[
"Similar",
"to",
":",
"meth",
":",
"httplib",
".",
"HTTPResponse",
".",
"read",
"but",
"with",
"two",
"additional",
"parameters",
":",
"decode_content",
"and",
"cache_content",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py#L205-L284
|
[
"def",
"read",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
",",
"cache_content",
"=",
"False",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"if",
"decode_content",
"is",
"None",
":",
"decode_content",
"=",
"self",
".",
"decode_content",
"if",
"self",
".",
"_fp",
"is",
"None",
":",
"return",
"flush_decoder",
"=",
"False",
"try",
":",
"try",
":",
"if",
"amt",
"is",
"None",
":",
"# cStringIO doesn't like amt=None",
"data",
"=",
"self",
".",
"_fp",
".",
"read",
"(",
")",
"flush_decoder",
"=",
"True",
"else",
":",
"cache_content",
"=",
"False",
"data",
"=",
"self",
".",
"_fp",
".",
"read",
"(",
"amt",
")",
"if",
"amt",
"!=",
"0",
"and",
"not",
"data",
":",
"# Platform-specific: Buggy versions of Python.",
"# Close the connection when no data is returned",
"#",
"# This is redundant to what httplib/http.client _should_",
"# already do. However, versions of python released before",
"# December 15, 2012 (http://bugs.python.org/issue16298) do",
"# not properly close the connection in all cases. There is",
"# no harm in redundantly calling close.",
"self",
".",
"_fp",
".",
"close",
"(",
")",
"flush_decoder",
"=",
"True",
"except",
"SocketTimeout",
":",
"# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but",
"# there is yet no clean way to get at it from this context.",
"raise",
"ReadTimeoutError",
"(",
"self",
".",
"_pool",
",",
"None",
",",
"'Read timed out.'",
")",
"except",
"BaseSSLError",
"as",
"e",
":",
"# FIXME: Is there a better way to differentiate between SSLErrors?",
"if",
"'read operation timed out'",
"not",
"in",
"str",
"(",
"e",
")",
":",
"# Defensive:",
"# This shouldn't happen but just in case we're missing an edge",
"# case, let's avoid swallowing SSL errors.",
"raise",
"raise",
"ReadTimeoutError",
"(",
"self",
".",
"_pool",
",",
"None",
",",
"'Read timed out.'",
")",
"except",
"HTTPException",
"as",
"e",
":",
"# This includes IncompleteRead.",
"raise",
"ProtocolError",
"(",
"'Connection broken: %r'",
"%",
"e",
",",
"e",
")",
"self",
".",
"_fp_bytes_read",
"+=",
"len",
"(",
"data",
")",
"data",
"=",
"self",
".",
"_decode",
"(",
"data",
",",
"decode_content",
",",
"flush_decoder",
")",
"if",
"cache_content",
":",
"self",
".",
"_body",
"=",
"data",
"return",
"data",
"finally",
":",
"if",
"self",
".",
"_original_response",
"and",
"self",
".",
"_original_response",
".",
"isclosed",
"(",
")",
":",
"self",
".",
"release_conn",
"(",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
HTTPResponse.stream
|
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compressed data. However, the empty string will
never be returned.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py
|
def stream(self, amt=2**16, decode_content=None):
"""
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compressed data. However, the empty string will
never be returned.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
if self.chunked:
for line in self.read_chunked(amt, decode_content=decode_content):
yield line
else:
while not is_fp_closed(self._fp):
data = self.read(amt=amt, decode_content=decode_content)
if data:
yield data
|
def stream(self, amt=2**16, decode_content=None):
"""
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compressed data. However, the empty string will
never be returned.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
if self.chunked:
for line in self.read_chunked(amt, decode_content=decode_content):
yield line
else:
while not is_fp_closed(self._fp):
data = self.read(amt=amt, decode_content=decode_content)
if data:
yield data
|
[
"A",
"generator",
"wrapper",
"for",
"the",
"read",
"()",
"method",
".",
"A",
"call",
"will",
"block",
"until",
"amt",
"bytes",
"have",
"been",
"read",
"from",
"the",
"connection",
"or",
"until",
"the",
"connection",
"is",
"closed",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py#L286-L310
|
[
"def",
"stream",
"(",
"self",
",",
"amt",
"=",
"2",
"**",
"16",
",",
"decode_content",
"=",
"None",
")",
":",
"if",
"self",
".",
"chunked",
":",
"for",
"line",
"in",
"self",
".",
"read_chunked",
"(",
"amt",
",",
"decode_content",
"=",
"decode_content",
")",
":",
"yield",
"line",
"else",
":",
"while",
"not",
"is_fp_closed",
"(",
"self",
".",
"_fp",
")",
":",
"data",
"=",
"self",
".",
"read",
"(",
"amt",
"=",
"amt",
",",
"decode_content",
"=",
"decode_content",
")",
"if",
"data",
":",
"yield",
"data"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
HTTPResponse.read_chunked
|
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py
|
def read_chunked(self, amt=None, decode_content=None):
"""
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
self._init_decoder()
# FIXME: Rewrite this method and make it a class with a better structured logic.
if not self.chunked:
raise ResponseNotChunked("Response is not chunked. "
"Header 'transfer-encoding: chunked' is missing.")
if self._original_response and self._original_response._method.upper() == 'HEAD':
# Don't bother reading the body of a HEAD request.
# FIXME: Can we do this somehow without accessing private httplib _method?
self._original_response.close()
return
while True:
self._update_chunk_length()
if self.chunk_left == 0:
break
chunk = self._handle_chunk(amt)
yield self._decode(chunk, decode_content=decode_content,
flush_decoder=True)
# Chunk content ends with \r\n: discard it.
while True:
line = self._fp.fp.readline()
if not line:
# Some sites may not end with '\r\n'.
break
if line == b'\r\n':
break
# We read everything; close the "file".
if self._original_response:
self._original_response.close()
self.release_conn()
|
def read_chunked(self, amt=None, decode_content=None):
"""
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
self._init_decoder()
# FIXME: Rewrite this method and make it a class with a better structured logic.
if not self.chunked:
raise ResponseNotChunked("Response is not chunked. "
"Header 'transfer-encoding: chunked' is missing.")
if self._original_response and self._original_response._method.upper() == 'HEAD':
# Don't bother reading the body of a HEAD request.
# FIXME: Can we do this somehow without accessing private httplib _method?
self._original_response.close()
return
while True:
self._update_chunk_length()
if self.chunk_left == 0:
break
chunk = self._handle_chunk(amt)
yield self._decode(chunk, decode_content=decode_content,
flush_decoder=True)
# Chunk content ends with \r\n: discard it.
while True:
line = self._fp.fp.readline()
if not line:
# Some sites may not end with '\r\n'.
break
if line == b'\r\n':
break
# We read everything; close the "file".
if self._original_response:
self._original_response.close()
self.release_conn()
|
[
"Similar",
"to",
":",
"meth",
":",
"HTTPResponse",
".",
"read",
"but",
"with",
"an",
"additional",
"parameter",
":",
"decode_content",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py#L425-L466
|
[
"def",
"read_chunked",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"# FIXME: Rewrite this method and make it a class with a better structured logic.",
"if",
"not",
"self",
".",
"chunked",
":",
"raise",
"ResponseNotChunked",
"(",
"\"Response is not chunked. \"",
"\"Header 'transfer-encoding: chunked' is missing.\"",
")",
"if",
"self",
".",
"_original_response",
"and",
"self",
".",
"_original_response",
".",
"_method",
".",
"upper",
"(",
")",
"==",
"'HEAD'",
":",
"# Don't bother reading the body of a HEAD request.",
"# FIXME: Can we do this somehow without accessing private httplib _method?",
"self",
".",
"_original_response",
".",
"close",
"(",
")",
"return",
"while",
"True",
":",
"self",
".",
"_update_chunk_length",
"(",
")",
"if",
"self",
".",
"chunk_left",
"==",
"0",
":",
"break",
"chunk",
"=",
"self",
".",
"_handle_chunk",
"(",
"amt",
")",
"yield",
"self",
".",
"_decode",
"(",
"chunk",
",",
"decode_content",
"=",
"decode_content",
",",
"flush_decoder",
"=",
"True",
")",
"# Chunk content ends with \\r\\n: discard it.",
"while",
"True",
":",
"line",
"=",
"self",
".",
"_fp",
".",
"fp",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"# Some sites may not end with '\\r\\n'.",
"break",
"if",
"line",
"==",
"b'\\r\\n'",
":",
"break",
"# We read everything; close the \"file\".",
"if",
"self",
".",
"_original_response",
":",
"self",
".",
"_original_response",
".",
"close",
"(",
")",
"self",
".",
"release_conn",
"(",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
_default_template_ctx_processor
|
Default template context processor. Injects `request`,
`session` and `g`.
|
capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py
|
def _default_template_ctx_processor():
"""Default template context processor. Injects `request`,
`session` and `g`.
"""
reqctx = _request_ctx_stack.top
appctx = _app_ctx_stack.top
rv = {}
if appctx is not None:
rv['g'] = appctx.g
if reqctx is not None:
rv['request'] = reqctx.request
rv['session'] = reqctx.session
return rv
|
def _default_template_ctx_processor():
"""Default template context processor. Injects `request`,
`session` and `g`.
"""
reqctx = _request_ctx_stack.top
appctx = _app_ctx_stack.top
rv = {}
if appctx is not None:
rv['g'] = appctx.g
if reqctx is not None:
rv['request'] = reqctx.request
rv['session'] = reqctx.session
return rv
|
[
"Default",
"template",
"context",
"processor",
".",
"Injects",
"request",
"session",
"and",
"g",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py#L21-L33
|
[
"def",
"_default_template_ctx_processor",
"(",
")",
":",
"reqctx",
"=",
"_request_ctx_stack",
".",
"top",
"appctx",
"=",
"_app_ctx_stack",
".",
"top",
"rv",
"=",
"{",
"}",
"if",
"appctx",
"is",
"not",
"None",
":",
"rv",
"[",
"'g'",
"]",
"=",
"appctx",
".",
"g",
"if",
"reqctx",
"is",
"not",
"None",
":",
"rv",
"[",
"'request'",
"]",
"=",
"reqctx",
".",
"request",
"rv",
"[",
"'session'",
"]",
"=",
"reqctx",
".",
"session",
"return",
"rv"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
_render
|
Renders the template and fires the signal
|
capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py
|
def _render(template, context, app):
"""Renders the template and fires the signal"""
rv = template.render(context)
template_rendered.send(app, template=template, context=context)
return rv
|
def _render(template, context, app):
"""Renders the template and fires the signal"""
rv = template.render(context)
template_rendered.send(app, template=template, context=context)
return rv
|
[
"Renders",
"the",
"template",
"and",
"fires",
"the",
"signal"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py#L108-L112
|
[
"def",
"_render",
"(",
"template",
",",
"context",
",",
"app",
")",
":",
"rv",
"=",
"template",
".",
"render",
"(",
"context",
")",
"template_rendered",
".",
"send",
"(",
"app",
",",
"template",
"=",
"template",
",",
"context",
"=",
"context",
")",
"return",
"rv"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
render_template
|
Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the first one existing will be rendered
:param context: the variables that should be available in the
context of the template.
|
capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py
|
def render_template(template_name_or_list, **context):
"""Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the first one existing will be rendered
:param context: the variables that should be available in the
context of the template.
"""
ctx = _app_ctx_stack.top
ctx.app.update_template_context(context)
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
context, ctx.app)
|
def render_template(template_name_or_list, **context):
"""Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the first one existing will be rendered
:param context: the variables that should be available in the
context of the template.
"""
ctx = _app_ctx_stack.top
ctx.app.update_template_context(context)
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
context, ctx.app)
|
[
"Renders",
"a",
"template",
"from",
"the",
"template",
"folder",
"with",
"the",
"given",
"context",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py#L115-L128
|
[
"def",
"render_template",
"(",
"template_name_or_list",
",",
"*",
"*",
"context",
")",
":",
"ctx",
"=",
"_app_ctx_stack",
".",
"top",
"ctx",
".",
"app",
".",
"update_template_context",
"(",
"context",
")",
"return",
"_render",
"(",
"ctx",
".",
"app",
".",
"jinja_env",
".",
"get_or_select_template",
"(",
"template_name_or_list",
")",
",",
"context",
",",
"ctx",
".",
"app",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
render_template_string
|
Renders a template from the given template source string
with the given context.
:param source: the sourcecode of the template to be
rendered
:param context: the variables that should be available in the
context of the template.
|
capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py
|
def render_template_string(source, **context):
"""Renders a template from the given template source string
with the given context.
:param source: the sourcecode of the template to be
rendered
:param context: the variables that should be available in the
context of the template.
"""
ctx = _app_ctx_stack.top
ctx.app.update_template_context(context)
return _render(ctx.app.jinja_env.from_string(source),
context, ctx.app)
|
def render_template_string(source, **context):
"""Renders a template from the given template source string
with the given context.
:param source: the sourcecode of the template to be
rendered
:param context: the variables that should be available in the
context of the template.
"""
ctx = _app_ctx_stack.top
ctx.app.update_template_context(context)
return _render(ctx.app.jinja_env.from_string(source),
context, ctx.app)
|
[
"Renders",
"a",
"template",
"from",
"the",
"given",
"template",
"source",
"string",
"with",
"the",
"given",
"context",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py#L131-L143
|
[
"def",
"render_template_string",
"(",
"source",
",",
"*",
"*",
"context",
")",
":",
"ctx",
"=",
"_app_ctx_stack",
".",
"top",
"ctx",
".",
"app",
".",
"update_template_context",
"(",
"context",
")",
"return",
"_render",
"(",
"ctx",
".",
"app",
".",
"jinja_env",
".",
"from_string",
"(",
"source",
")",
",",
"context",
",",
"ctx",
".",
"app",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
parse_version
|
Use parse_version from pkg_resources or distutils as available.
|
capybara/virtualenv/lib/python2.7/site-packages/wheel/install.py
|
def parse_version(version):
"""Use parse_version from pkg_resources or distutils as available."""
global parse_version
try:
from pkg_resources import parse_version
except ImportError:
from distutils.version import LooseVersion as parse_version
return parse_version(version)
|
def parse_version(version):
"""Use parse_version from pkg_resources or distutils as available."""
global parse_version
try:
from pkg_resources import parse_version
except ImportError:
from distutils.version import LooseVersion as parse_version
return parse_version(version)
|
[
"Use",
"parse_version",
"from",
"pkg_resources",
"or",
"distutils",
"as",
"available",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/install.py#L42-L49
|
[
"def",
"parse_version",
"(",
"version",
")",
":",
"global",
"parse_version",
"try",
":",
"from",
"pkg_resources",
"import",
"parse_version",
"except",
"ImportError",
":",
"from",
"distutils",
".",
"version",
"import",
"LooseVersion",
"as",
"parse_version",
"return",
"parse_version",
"(",
"version",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
WheelFile.install
|
Install the wheel into site-packages.
|
capybara/virtualenv/lib/python2.7/site-packages/wheel/install.py
|
def install(self, force=False, overrides={}):
"""
Install the wheel into site-packages.
"""
# Utility to get the target directory for a particular key
def get_path(key):
return overrides.get(key) or self.install_paths[key]
# The base target location is either purelib or platlib
if self.parsed_wheel_info['Root-Is-Purelib'] == 'true':
root = get_path('purelib')
else:
root = get_path('platlib')
# Parse all the names in the archive
name_trans = {}
for info in self.zipfile.infolist():
name = info.filename
# Zip files can contain entries representing directories.
# These end in a '/'.
# We ignore these, as we create directories on demand.
if name.endswith('/'):
continue
# Pathnames in a zipfile namelist are always /-separated.
# In theory, paths could start with ./ or have other oddities
# but this won't happen in practical cases of well-formed wheels.
# We'll cover the simple case of an initial './' as it's both easy
# to do and more common than most other oddities.
if name.startswith('./'):
name = name[2:]
# Split off the base directory to identify files that are to be
# installed in non-root locations
basedir, sep, filename = name.partition('/')
if sep and basedir == self.datadir_name:
# Data file. Target destination is elsewhere
key, sep, filename = filename.partition('/')
if not sep:
raise ValueError("Invalid filename in wheel: {0}".format(name))
target = get_path(key)
else:
# Normal file. Target destination is root
key = ''
target = root
filename = name
# Map the actual filename from the zipfile to its intended target
# directory and the pathname relative to that directory.
dest = os.path.normpath(os.path.join(target, filename))
name_trans[info] = (key, target, filename, dest)
# We're now ready to start processing the actual install. The process
# is as follows:
# 1. Prechecks - is the wheel valid, is its declared architecture
# OK, etc. [[Responsibility of the caller]]
# 2. Overwrite check - do any of the files to be installed already
# exist?
# 3. Actual install - put the files in their target locations.
# 4. Update RECORD - write a suitably modified RECORD file to
# reflect the actual installed paths.
if not force:
for info, v in name_trans.items():
k = info.filename
key, target, filename, dest = v
if os.path.exists(dest):
raise ValueError("Wheel file {0} would overwrite {1}. Use force if this is intended".format(k, dest))
# Get the name of our executable, for use when replacing script
# wrapper hashbang lines.
# We encode it using getfilesystemencoding, as that is "the name of
# the encoding used to convert Unicode filenames into system file
# names".
exename = sys.executable.encode(sys.getfilesystemencoding())
record_data = []
record_name = self.distinfo_name + '/RECORD'
for info, (key, target, filename, dest) in name_trans.items():
name = info.filename
source = self.zipfile.open(info)
# Skip the RECORD file
if name == record_name:
continue
ddir = os.path.dirname(dest)
if not os.path.isdir(ddir):
os.makedirs(ddir)
destination = HashingFile(open(dest, 'wb'))
if key == 'scripts':
hashbang = source.readline()
if hashbang.startswith(b'#!python'):
hashbang = b'#!' + exename + binary(os.linesep)
destination.write(hashbang)
shutil.copyfileobj(source, destination)
reldest = os.path.relpath(dest, root)
reldest.replace(os.sep, '/')
record_data.append((reldest, destination.digest(), destination.length))
destination.close()
source.close()
# preserve attributes (especially +x bit for scripts)
attrs = info.external_attr >> 16
if attrs: # tends to be 0 if Windows.
os.chmod(dest, info.external_attr >> 16)
record_name = os.path.join(root, self.record_name)
writer = csv.writer(open_for_csv(record_name, 'w+'))
for reldest, digest, length in sorted(record_data):
writer.writerow((reldest, digest, length))
writer.writerow((self.record_name, '', ''))
|
def install(self, force=False, overrides={}):
"""
Install the wheel into site-packages.
"""
# Utility to get the target directory for a particular key
def get_path(key):
return overrides.get(key) or self.install_paths[key]
# The base target location is either purelib or platlib
if self.parsed_wheel_info['Root-Is-Purelib'] == 'true':
root = get_path('purelib')
else:
root = get_path('platlib')
# Parse all the names in the archive
name_trans = {}
for info in self.zipfile.infolist():
name = info.filename
# Zip files can contain entries representing directories.
# These end in a '/'.
# We ignore these, as we create directories on demand.
if name.endswith('/'):
continue
# Pathnames in a zipfile namelist are always /-separated.
# In theory, paths could start with ./ or have other oddities
# but this won't happen in practical cases of well-formed wheels.
# We'll cover the simple case of an initial './' as it's both easy
# to do and more common than most other oddities.
if name.startswith('./'):
name = name[2:]
# Split off the base directory to identify files that are to be
# installed in non-root locations
basedir, sep, filename = name.partition('/')
if sep and basedir == self.datadir_name:
# Data file. Target destination is elsewhere
key, sep, filename = filename.partition('/')
if not sep:
raise ValueError("Invalid filename in wheel: {0}".format(name))
target = get_path(key)
else:
# Normal file. Target destination is root
key = ''
target = root
filename = name
# Map the actual filename from the zipfile to its intended target
# directory and the pathname relative to that directory.
dest = os.path.normpath(os.path.join(target, filename))
name_trans[info] = (key, target, filename, dest)
# We're now ready to start processing the actual install. The process
# is as follows:
# 1. Prechecks - is the wheel valid, is its declared architecture
# OK, etc. [[Responsibility of the caller]]
# 2. Overwrite check - do any of the files to be installed already
# exist?
# 3. Actual install - put the files in their target locations.
# 4. Update RECORD - write a suitably modified RECORD file to
# reflect the actual installed paths.
if not force:
for info, v in name_trans.items():
k = info.filename
key, target, filename, dest = v
if os.path.exists(dest):
raise ValueError("Wheel file {0} would overwrite {1}. Use force if this is intended".format(k, dest))
# Get the name of our executable, for use when replacing script
# wrapper hashbang lines.
# We encode it using getfilesystemencoding, as that is "the name of
# the encoding used to convert Unicode filenames into system file
# names".
exename = sys.executable.encode(sys.getfilesystemencoding())
record_data = []
record_name = self.distinfo_name + '/RECORD'
for info, (key, target, filename, dest) in name_trans.items():
name = info.filename
source = self.zipfile.open(info)
# Skip the RECORD file
if name == record_name:
continue
ddir = os.path.dirname(dest)
if not os.path.isdir(ddir):
os.makedirs(ddir)
destination = HashingFile(open(dest, 'wb'))
if key == 'scripts':
hashbang = source.readline()
if hashbang.startswith(b'#!python'):
hashbang = b'#!' + exename + binary(os.linesep)
destination.write(hashbang)
shutil.copyfileobj(source, destination)
reldest = os.path.relpath(dest, root)
reldest.replace(os.sep, '/')
record_data.append((reldest, destination.digest(), destination.length))
destination.close()
source.close()
# preserve attributes (especially +x bit for scripts)
attrs = info.external_attr >> 16
if attrs: # tends to be 0 if Windows.
os.chmod(dest, info.external_attr >> 16)
record_name = os.path.join(root, self.record_name)
writer = csv.writer(open_for_csv(record_name, 'w+'))
for reldest, digest, length in sorted(record_data):
writer.writerow((reldest, digest, length))
writer.writerow((self.record_name, '', ''))
|
[
"Install",
"the",
"wheel",
"into",
"site",
"-",
"packages",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/install.py#L258-L366
|
[
"def",
"install",
"(",
"self",
",",
"force",
"=",
"False",
",",
"overrides",
"=",
"{",
"}",
")",
":",
"# Utility to get the target directory for a particular key",
"def",
"get_path",
"(",
"key",
")",
":",
"return",
"overrides",
".",
"get",
"(",
"key",
")",
"or",
"self",
".",
"install_paths",
"[",
"key",
"]",
"# The base target location is either purelib or platlib",
"if",
"self",
".",
"parsed_wheel_info",
"[",
"'Root-Is-Purelib'",
"]",
"==",
"'true'",
":",
"root",
"=",
"get_path",
"(",
"'purelib'",
")",
"else",
":",
"root",
"=",
"get_path",
"(",
"'platlib'",
")",
"# Parse all the names in the archive",
"name_trans",
"=",
"{",
"}",
"for",
"info",
"in",
"self",
".",
"zipfile",
".",
"infolist",
"(",
")",
":",
"name",
"=",
"info",
".",
"filename",
"# Zip files can contain entries representing directories.",
"# These end in a '/'.",
"# We ignore these, as we create directories on demand.",
"if",
"name",
".",
"endswith",
"(",
"'/'",
")",
":",
"continue",
"# Pathnames in a zipfile namelist are always /-separated.",
"# In theory, paths could start with ./ or have other oddities",
"# but this won't happen in practical cases of well-formed wheels.",
"# We'll cover the simple case of an initial './' as it's both easy",
"# to do and more common than most other oddities.",
"if",
"name",
".",
"startswith",
"(",
"'./'",
")",
":",
"name",
"=",
"name",
"[",
"2",
":",
"]",
"# Split off the base directory to identify files that are to be",
"# installed in non-root locations",
"basedir",
",",
"sep",
",",
"filename",
"=",
"name",
".",
"partition",
"(",
"'/'",
")",
"if",
"sep",
"and",
"basedir",
"==",
"self",
".",
"datadir_name",
":",
"# Data file. Target destination is elsewhere",
"key",
",",
"sep",
",",
"filename",
"=",
"filename",
".",
"partition",
"(",
"'/'",
")",
"if",
"not",
"sep",
":",
"raise",
"ValueError",
"(",
"\"Invalid filename in wheel: {0}\"",
".",
"format",
"(",
"name",
")",
")",
"target",
"=",
"get_path",
"(",
"key",
")",
"else",
":",
"# Normal file. Target destination is root",
"key",
"=",
"''",
"target",
"=",
"root",
"filename",
"=",
"name",
"# Map the actual filename from the zipfile to its intended target",
"# directory and the pathname relative to that directory.",
"dest",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target",
",",
"filename",
")",
")",
"name_trans",
"[",
"info",
"]",
"=",
"(",
"key",
",",
"target",
",",
"filename",
",",
"dest",
")",
"# We're now ready to start processing the actual install. The process",
"# is as follows:",
"# 1. Prechecks - is the wheel valid, is its declared architecture",
"# OK, etc. [[Responsibility of the caller]]",
"# 2. Overwrite check - do any of the files to be installed already",
"# exist?",
"# 3. Actual install - put the files in their target locations.",
"# 4. Update RECORD - write a suitably modified RECORD file to",
"# reflect the actual installed paths.",
"if",
"not",
"force",
":",
"for",
"info",
",",
"v",
"in",
"name_trans",
".",
"items",
"(",
")",
":",
"k",
"=",
"info",
".",
"filename",
"key",
",",
"target",
",",
"filename",
",",
"dest",
"=",
"v",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
":",
"raise",
"ValueError",
"(",
"\"Wheel file {0} would overwrite {1}. Use force if this is intended\"",
".",
"format",
"(",
"k",
",",
"dest",
")",
")",
"# Get the name of our executable, for use when replacing script",
"# wrapper hashbang lines.",
"# We encode it using getfilesystemencoding, as that is \"the name of",
"# the encoding used to convert Unicode filenames into system file",
"# names\".",
"exename",
"=",
"sys",
".",
"executable",
".",
"encode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
"record_data",
"=",
"[",
"]",
"record_name",
"=",
"self",
".",
"distinfo_name",
"+",
"'/RECORD'",
"for",
"info",
",",
"(",
"key",
",",
"target",
",",
"filename",
",",
"dest",
")",
"in",
"name_trans",
".",
"items",
"(",
")",
":",
"name",
"=",
"info",
".",
"filename",
"source",
"=",
"self",
".",
"zipfile",
".",
"open",
"(",
"info",
")",
"# Skip the RECORD file",
"if",
"name",
"==",
"record_name",
":",
"continue",
"ddir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dest",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"ddir",
")",
":",
"os",
".",
"makedirs",
"(",
"ddir",
")",
"destination",
"=",
"HashingFile",
"(",
"open",
"(",
"dest",
",",
"'wb'",
")",
")",
"if",
"key",
"==",
"'scripts'",
":",
"hashbang",
"=",
"source",
".",
"readline",
"(",
")",
"if",
"hashbang",
".",
"startswith",
"(",
"b'#!python'",
")",
":",
"hashbang",
"=",
"b'#!'",
"+",
"exename",
"+",
"binary",
"(",
"os",
".",
"linesep",
")",
"destination",
".",
"write",
"(",
"hashbang",
")",
"shutil",
".",
"copyfileobj",
"(",
"source",
",",
"destination",
")",
"reldest",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"dest",
",",
"root",
")",
"reldest",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"'/'",
")",
"record_data",
".",
"append",
"(",
"(",
"reldest",
",",
"destination",
".",
"digest",
"(",
")",
",",
"destination",
".",
"length",
")",
")",
"destination",
".",
"close",
"(",
")",
"source",
".",
"close",
"(",
")",
"# preserve attributes (especially +x bit for scripts)",
"attrs",
"=",
"info",
".",
"external_attr",
">>",
"16",
"if",
"attrs",
":",
"# tends to be 0 if Windows.",
"os",
".",
"chmod",
"(",
"dest",
",",
"info",
".",
"external_attr",
">>",
"16",
")",
"record_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"self",
".",
"record_name",
")",
"writer",
"=",
"csv",
".",
"writer",
"(",
"open_for_csv",
"(",
"record_name",
",",
"'w+'",
")",
")",
"for",
"reldest",
",",
"digest",
",",
"length",
"in",
"sorted",
"(",
"record_data",
")",
":",
"writer",
".",
"writerow",
"(",
"(",
"reldest",
",",
"digest",
",",
"length",
")",
")",
"writer",
".",
"writerow",
"(",
"(",
"self",
".",
"record_name",
",",
"''",
",",
"''",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
WheelFile.verify
|
Configure the VerifyingZipFile `zipfile` by verifying its signature
and setting expected hashes for every hash in RECORD.
Caller must complete the verification process by completely reading
every file in the archive (e.g. with extractall).
|
capybara/virtualenv/lib/python2.7/site-packages/wheel/install.py
|
def verify(self, zipfile=None):
"""Configure the VerifyingZipFile `zipfile` by verifying its signature
and setting expected hashes for every hash in RECORD.
Caller must complete the verification process by completely reading
every file in the archive (e.g. with extractall)."""
sig = None
if zipfile is None:
zipfile = self.zipfile
zipfile.strict = True
record_name = '/'.join((self.distinfo_name, 'RECORD'))
sig_name = '/'.join((self.distinfo_name, 'RECORD.jws'))
# tolerate s/mime signatures:
smime_sig_name = '/'.join((self.distinfo_name, 'RECORD.p7s'))
zipfile.set_expected_hash(record_name, None)
zipfile.set_expected_hash(sig_name, None)
zipfile.set_expected_hash(smime_sig_name, None)
record = zipfile.read(record_name)
record_digest = urlsafe_b64encode(hashlib.sha256(record).digest())
try:
sig = from_json(native(zipfile.read(sig_name)))
except KeyError: # no signature
pass
if sig:
headers, payload = signatures.verify(sig)
if payload['hash'] != "sha256=" + native(record_digest):
msg = "RECORD.sig claimed RECORD hash {0} != computed hash {1}."
raise BadWheelFile(msg.format(payload['hash'],
native(record_digest)))
reader = csv.reader((native(r) for r in record.splitlines()))
for row in reader:
filename = row[0]
hash = row[1]
if not hash:
if filename not in (record_name, sig_name):
sys.stderr.write("%s has no hash!\n" % filename)
continue
algo, data = row[1].split('=', 1)
assert algo == "sha256", "Unsupported hash algorithm"
zipfile.set_expected_hash(filename, urlsafe_b64decode(binary(data)))
|
def verify(self, zipfile=None):
"""Configure the VerifyingZipFile `zipfile` by verifying its signature
and setting expected hashes for every hash in RECORD.
Caller must complete the verification process by completely reading
every file in the archive (e.g. with extractall)."""
sig = None
if zipfile is None:
zipfile = self.zipfile
zipfile.strict = True
record_name = '/'.join((self.distinfo_name, 'RECORD'))
sig_name = '/'.join((self.distinfo_name, 'RECORD.jws'))
# tolerate s/mime signatures:
smime_sig_name = '/'.join((self.distinfo_name, 'RECORD.p7s'))
zipfile.set_expected_hash(record_name, None)
zipfile.set_expected_hash(sig_name, None)
zipfile.set_expected_hash(smime_sig_name, None)
record = zipfile.read(record_name)
record_digest = urlsafe_b64encode(hashlib.sha256(record).digest())
try:
sig = from_json(native(zipfile.read(sig_name)))
except KeyError: # no signature
pass
if sig:
headers, payload = signatures.verify(sig)
if payload['hash'] != "sha256=" + native(record_digest):
msg = "RECORD.sig claimed RECORD hash {0} != computed hash {1}."
raise BadWheelFile(msg.format(payload['hash'],
native(record_digest)))
reader = csv.reader((native(r) for r in record.splitlines()))
for row in reader:
filename = row[0]
hash = row[1]
if not hash:
if filename not in (record_name, sig_name):
sys.stderr.write("%s has no hash!\n" % filename)
continue
algo, data = row[1].split('=', 1)
assert algo == "sha256", "Unsupported hash algorithm"
zipfile.set_expected_hash(filename, urlsafe_b64decode(binary(data)))
|
[
"Configure",
"the",
"VerifyingZipFile",
"zipfile",
"by",
"verifying",
"its",
"signature",
"and",
"setting",
"expected",
"hashes",
"for",
"every",
"hash",
"in",
"RECORD",
".",
"Caller",
"must",
"complete",
"the",
"verification",
"process",
"by",
"completely",
"reading",
"every",
"file",
"in",
"the",
"archive",
"(",
"e",
".",
"g",
".",
"with",
"extractall",
")",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/install.py#L368-L410
|
[
"def",
"verify",
"(",
"self",
",",
"zipfile",
"=",
"None",
")",
":",
"sig",
"=",
"None",
"if",
"zipfile",
"is",
"None",
":",
"zipfile",
"=",
"self",
".",
"zipfile",
"zipfile",
".",
"strict",
"=",
"True",
"record_name",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"distinfo_name",
",",
"'RECORD'",
")",
")",
"sig_name",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"distinfo_name",
",",
"'RECORD.jws'",
")",
")",
"# tolerate s/mime signatures:",
"smime_sig_name",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"distinfo_name",
",",
"'RECORD.p7s'",
")",
")",
"zipfile",
".",
"set_expected_hash",
"(",
"record_name",
",",
"None",
")",
"zipfile",
".",
"set_expected_hash",
"(",
"sig_name",
",",
"None",
")",
"zipfile",
".",
"set_expected_hash",
"(",
"smime_sig_name",
",",
"None",
")",
"record",
"=",
"zipfile",
".",
"read",
"(",
"record_name",
")",
"record_digest",
"=",
"urlsafe_b64encode",
"(",
"hashlib",
".",
"sha256",
"(",
"record",
")",
".",
"digest",
"(",
")",
")",
"try",
":",
"sig",
"=",
"from_json",
"(",
"native",
"(",
"zipfile",
".",
"read",
"(",
"sig_name",
")",
")",
")",
"except",
"KeyError",
":",
"# no signature",
"pass",
"if",
"sig",
":",
"headers",
",",
"payload",
"=",
"signatures",
".",
"verify",
"(",
"sig",
")",
"if",
"payload",
"[",
"'hash'",
"]",
"!=",
"\"sha256=\"",
"+",
"native",
"(",
"record_digest",
")",
":",
"msg",
"=",
"\"RECORD.sig claimed RECORD hash {0} != computed hash {1}.\"",
"raise",
"BadWheelFile",
"(",
"msg",
".",
"format",
"(",
"payload",
"[",
"'hash'",
"]",
",",
"native",
"(",
"record_digest",
")",
")",
")",
"reader",
"=",
"csv",
".",
"reader",
"(",
"(",
"native",
"(",
"r",
")",
"for",
"r",
"in",
"record",
".",
"splitlines",
"(",
")",
")",
")",
"for",
"row",
"in",
"reader",
":",
"filename",
"=",
"row",
"[",
"0",
"]",
"hash",
"=",
"row",
"[",
"1",
"]",
"if",
"not",
"hash",
":",
"if",
"filename",
"not",
"in",
"(",
"record_name",
",",
"sig_name",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s has no hash!\\n\"",
"%",
"filename",
")",
"continue",
"algo",
",",
"data",
"=",
"row",
"[",
"1",
"]",
".",
"split",
"(",
"'='",
",",
"1",
")",
"assert",
"algo",
"==",
"\"sha256\"",
",",
"\"Unsupported hash algorithm\"",
"zipfile",
".",
"set_expected_hash",
"(",
"filename",
",",
"urlsafe_b64decode",
"(",
"binary",
"(",
"data",
")",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Identifiers.is_declared
|
Check if a name is declared in this or an outer scope.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py
|
def is_declared(self, name):
"""Check if a name is declared in this or an outer scope."""
if name in self.declared_locally or name in self.declared_parameter:
return True
return name in self.declared
|
def is_declared(self, name):
"""Check if a name is declared in this or an outer scope."""
if name in self.declared_locally or name in self.declared_parameter:
return True
return name in self.declared
|
[
"Check",
"if",
"a",
"name",
"is",
"declared",
"in",
"this",
"or",
"an",
"outer",
"scope",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py#L128-L132
|
[
"def",
"is_declared",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"declared_locally",
"or",
"name",
"in",
"self",
".",
"declared_parameter",
":",
"return",
"True",
"return",
"name",
"in",
"self",
".",
"declared"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Frame.inspect
|
Walk the node and check for identifiers. If the scope is hard (eg:
enforce on a python level) overrides from outer scopes are tracked
differently.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py
|
def inspect(self, nodes):
"""Walk the node and check for identifiers. If the scope is hard (eg:
enforce on a python level) overrides from outer scopes are tracked
differently.
"""
visitor = FrameIdentifierVisitor(self.identifiers)
for node in nodes:
visitor.visit(node)
|
def inspect(self, nodes):
"""Walk the node and check for identifiers. If the scope is hard (eg:
enforce on a python level) overrides from outer scopes are tracked
differently.
"""
visitor = FrameIdentifierVisitor(self.identifiers)
for node in nodes:
visitor.visit(node)
|
[
"Walk",
"the",
"node",
"and",
"check",
"for",
"identifiers",
".",
"If",
"the",
"scope",
"is",
"hard",
"(",
"eg",
":",
"enforce",
"on",
"a",
"python",
"level",
")",
"overrides",
"from",
"outer",
"scopes",
"are",
"tracked",
"differently",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py#L192-L199
|
[
"def",
"inspect",
"(",
"self",
",",
"nodes",
")",
":",
"visitor",
"=",
"FrameIdentifierVisitor",
"(",
"self",
".",
"identifiers",
")",
"for",
"node",
"in",
"nodes",
":",
"visitor",
".",
"visit",
"(",
"node",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
FrameIdentifierVisitor.visit_Name
|
All assignments to names go through this function.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py
|
def visit_Name(self, node):
"""All assignments to names go through this function."""
if node.ctx == 'store':
self.identifiers.declared_locally.add(node.name)
elif node.ctx == 'param':
self.identifiers.declared_parameter.add(node.name)
elif node.ctx == 'load' and not \
self.identifiers.is_declared(node.name):
self.identifiers.undeclared.add(node.name)
|
def visit_Name(self, node):
"""All assignments to names go through this function."""
if node.ctx == 'store':
self.identifiers.declared_locally.add(node.name)
elif node.ctx == 'param':
self.identifiers.declared_parameter.add(node.name)
elif node.ctx == 'load' and not \
self.identifiers.is_declared(node.name):
self.identifiers.undeclared.add(node.name)
|
[
"All",
"assignments",
"to",
"names",
"go",
"through",
"this",
"function",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py#L277-L285
|
[
"def",
"visit_Name",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"ctx",
"==",
"'store'",
":",
"self",
".",
"identifiers",
".",
"declared_locally",
".",
"add",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'param'",
":",
"self",
".",
"identifiers",
".",
"declared_parameter",
".",
"add",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'load'",
"and",
"not",
"self",
".",
"identifiers",
".",
"is_declared",
"(",
"node",
".",
"name",
")",
":",
"self",
".",
"identifiers",
".",
"undeclared",
".",
"add",
"(",
"node",
".",
"name",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
CodeGenerator.visit_Include
|
Handles includes.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py
|
def visit_Include(self, node, frame):
"""Handles includes."""
if node.with_context:
self.unoptimize_scope(frame)
if node.ignore_missing:
self.writeline('try:')
self.indent()
func_name = 'get_or_select_template'
if isinstance(node.template, nodes.Const):
if isinstance(node.template.value, string_types):
func_name = 'get_template'
elif isinstance(node.template.value, (tuple, list)):
func_name = 'select_template'
elif isinstance(node.template, (nodes.Tuple, nodes.List)):
func_name = 'select_template'
self.writeline('template = environment.%s(' % func_name, node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
if node.ignore_missing:
self.outdent()
self.writeline('except TemplateNotFound:')
self.indent()
self.writeline('pass')
self.outdent()
self.writeline('else:')
self.indent()
if node.with_context:
self.writeline('for event in template.root_render_func('
'template.new_context(context.parent, True, '
'locals())):')
else:
self.writeline('for event in template.module._body_stream:')
self.indent()
self.simple_write('event', frame)
self.outdent()
if node.ignore_missing:
self.outdent()
|
def visit_Include(self, node, frame):
"""Handles includes."""
if node.with_context:
self.unoptimize_scope(frame)
if node.ignore_missing:
self.writeline('try:')
self.indent()
func_name = 'get_or_select_template'
if isinstance(node.template, nodes.Const):
if isinstance(node.template.value, string_types):
func_name = 'get_template'
elif isinstance(node.template.value, (tuple, list)):
func_name = 'select_template'
elif isinstance(node.template, (nodes.Tuple, nodes.List)):
func_name = 'select_template'
self.writeline('template = environment.%s(' % func_name, node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
if node.ignore_missing:
self.outdent()
self.writeline('except TemplateNotFound:')
self.indent()
self.writeline('pass')
self.outdent()
self.writeline('else:')
self.indent()
if node.with_context:
self.writeline('for event in template.root_render_func('
'template.new_context(context.parent, True, '
'locals())):')
else:
self.writeline('for event in template.module._body_stream:')
self.indent()
self.simple_write('event', frame)
self.outdent()
if node.ignore_missing:
self.outdent()
|
[
"Handles",
"includes",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py#L922-L963
|
[
"def",
"visit_Include",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"if",
"node",
".",
"with_context",
":",
"self",
".",
"unoptimize_scope",
"(",
"frame",
")",
"if",
"node",
".",
"ignore_missing",
":",
"self",
".",
"writeline",
"(",
"'try:'",
")",
"self",
".",
"indent",
"(",
")",
"func_name",
"=",
"'get_or_select_template'",
"if",
"isinstance",
"(",
"node",
".",
"template",
",",
"nodes",
".",
"Const",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"template",
".",
"value",
",",
"string_types",
")",
":",
"func_name",
"=",
"'get_template'",
"elif",
"isinstance",
"(",
"node",
".",
"template",
".",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"func_name",
"=",
"'select_template'",
"elif",
"isinstance",
"(",
"node",
".",
"template",
",",
"(",
"nodes",
".",
"Tuple",
",",
"nodes",
".",
"List",
")",
")",
":",
"func_name",
"=",
"'select_template'",
"self",
".",
"writeline",
"(",
"'template = environment.%s('",
"%",
"func_name",
",",
"node",
")",
"self",
".",
"visit",
"(",
"node",
".",
"template",
",",
"frame",
")",
"self",
".",
"write",
"(",
"', %r)'",
"%",
"self",
".",
"name",
")",
"if",
"node",
".",
"ignore_missing",
":",
"self",
".",
"outdent",
"(",
")",
"self",
".",
"writeline",
"(",
"'except TemplateNotFound:'",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"writeline",
"(",
"'pass'",
")",
"self",
".",
"outdent",
"(",
")",
"self",
".",
"writeline",
"(",
"'else:'",
")",
"self",
".",
"indent",
"(",
")",
"if",
"node",
".",
"with_context",
":",
"self",
".",
"writeline",
"(",
"'for event in template.root_render_func('",
"'template.new_context(context.parent, True, '",
"'locals())):'",
")",
"else",
":",
"self",
".",
"writeline",
"(",
"'for event in template.module._body_stream:'",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"simple_write",
"(",
"'event'",
",",
"frame",
")",
"self",
".",
"outdent",
"(",
")",
"if",
"node",
".",
"ignore_missing",
":",
"self",
".",
"outdent",
"(",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
CodeGenerator.visit_FromImport
|
Visit named imports.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py
|
def visit_FromImport(self, node, frame):
"""Visit named imports."""
self.newline(node)
self.write('included_template = environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(context.parent, True)')
else:
self.write('module')
var_names = []
discarded_names = []
for name in node.names:
if isinstance(name, tuple):
name, alias = name
else:
alias = name
self.writeline('l_%s = getattr(included_template, '
'%r, missing)' % (alias, name))
self.writeline('if l_%s is missing:' % alias)
self.indent()
self.writeline('l_%s = environment.undefined(%r %% '
'included_template.__name__, '
'name=%r)' %
(alias, 'the template %%r (imported on %s) does '
'not export the requested name %s' % (
self.position(node),
repr(name)
), name))
self.outdent()
if frame.toplevel:
var_names.append(alias)
if not alias.startswith('_'):
discarded_names.append(alias)
frame.assigned_names.add(alias)
if var_names:
if len(var_names) == 1:
name = var_names[0]
self.writeline('context.vars[%r] = l_%s' % (name, name))
else:
self.writeline('context.vars.update({%s})' % ', '.join(
'%r: l_%s' % (name, name) for name in var_names
))
if discarded_names:
if len(discarded_names) == 1:
self.writeline('context.exported_vars.discard(%r)' %
discarded_names[0])
else:
self.writeline('context.exported_vars.difference_'
'update((%s))' % ', '.join(imap(repr, discarded_names)))
|
def visit_FromImport(self, node, frame):
"""Visit named imports."""
self.newline(node)
self.write('included_template = environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(context.parent, True)')
else:
self.write('module')
var_names = []
discarded_names = []
for name in node.names:
if isinstance(name, tuple):
name, alias = name
else:
alias = name
self.writeline('l_%s = getattr(included_template, '
'%r, missing)' % (alias, name))
self.writeline('if l_%s is missing:' % alias)
self.indent()
self.writeline('l_%s = environment.undefined(%r %% '
'included_template.__name__, '
'name=%r)' %
(alias, 'the template %%r (imported on %s) does '
'not export the requested name %s' % (
self.position(node),
repr(name)
), name))
self.outdent()
if frame.toplevel:
var_names.append(alias)
if not alias.startswith('_'):
discarded_names.append(alias)
frame.assigned_names.add(alias)
if var_names:
if len(var_names) == 1:
name = var_names[0]
self.writeline('context.vars[%r] = l_%s' % (name, name))
else:
self.writeline('context.vars.update({%s})' % ', '.join(
'%r: l_%s' % (name, name) for name in var_names
))
if discarded_names:
if len(discarded_names) == 1:
self.writeline('context.exported_vars.discard(%r)' %
discarded_names[0])
else:
self.writeline('context.exported_vars.difference_'
'update((%s))' % ', '.join(imap(repr, discarded_names)))
|
[
"Visit",
"named",
"imports",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py#L983-L1034
|
[
"def",
"visit_FromImport",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"self",
".",
"newline",
"(",
"node",
")",
"self",
".",
"write",
"(",
"'included_template = environment.get_template('",
")",
"self",
".",
"visit",
"(",
"node",
".",
"template",
",",
"frame",
")",
"self",
".",
"write",
"(",
"', %r).'",
"%",
"self",
".",
"name",
")",
"if",
"node",
".",
"with_context",
":",
"self",
".",
"write",
"(",
"'make_module(context.parent, True)'",
")",
"else",
":",
"self",
".",
"write",
"(",
"'module'",
")",
"var_names",
"=",
"[",
"]",
"discarded_names",
"=",
"[",
"]",
"for",
"name",
"in",
"node",
".",
"names",
":",
"if",
"isinstance",
"(",
"name",
",",
"tuple",
")",
":",
"name",
",",
"alias",
"=",
"name",
"else",
":",
"alias",
"=",
"name",
"self",
".",
"writeline",
"(",
"'l_%s = getattr(included_template, '",
"'%r, missing)'",
"%",
"(",
"alias",
",",
"name",
")",
")",
"self",
".",
"writeline",
"(",
"'if l_%s is missing:'",
"%",
"alias",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"writeline",
"(",
"'l_%s = environment.undefined(%r %% '",
"'included_template.__name__, '",
"'name=%r)'",
"%",
"(",
"alias",
",",
"'the template %%r (imported on %s) does '",
"'not export the requested name %s'",
"%",
"(",
"self",
".",
"position",
"(",
"node",
")",
",",
"repr",
"(",
"name",
")",
")",
",",
"name",
")",
")",
"self",
".",
"outdent",
"(",
")",
"if",
"frame",
".",
"toplevel",
":",
"var_names",
".",
"append",
"(",
"alias",
")",
"if",
"not",
"alias",
".",
"startswith",
"(",
"'_'",
")",
":",
"discarded_names",
".",
"append",
"(",
"alias",
")",
"frame",
".",
"assigned_names",
".",
"add",
"(",
"alias",
")",
"if",
"var_names",
":",
"if",
"len",
"(",
"var_names",
")",
"==",
"1",
":",
"name",
"=",
"var_names",
"[",
"0",
"]",
"self",
".",
"writeline",
"(",
"'context.vars[%r] = l_%s'",
"%",
"(",
"name",
",",
"name",
")",
")",
"else",
":",
"self",
".",
"writeline",
"(",
"'context.vars.update({%s})'",
"%",
"', '",
".",
"join",
"(",
"'%r: l_%s'",
"%",
"(",
"name",
",",
"name",
")",
"for",
"name",
"in",
"var_names",
")",
")",
"if",
"discarded_names",
":",
"if",
"len",
"(",
"discarded_names",
")",
"==",
"1",
":",
"self",
".",
"writeline",
"(",
"'context.exported_vars.discard(%r)'",
"%",
"discarded_names",
"[",
"0",
"]",
")",
"else",
":",
"self",
".",
"writeline",
"(",
"'context.exported_vars.difference_'",
"'update((%s))'",
"%",
"', '",
".",
"join",
"(",
"imap",
"(",
"repr",
",",
"discarded_names",
")",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
make_wheelfile_inner
|
Create a whl file from all the files under 'base_dir'.
Places .dist-info at the end of the archive.
|
capybara/virtualenv/lib/python2.7/site-packages/wheel/archive.py
|
def make_wheelfile_inner(base_name, base_dir='.'):
"""Create a whl file from all the files under 'base_dir'.
Places .dist-info at the end of the archive."""
zip_filename = base_name + ".whl"
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
# XXX support bz2, xz when available
zip = zipfile.ZipFile(open(zip_filename, "wb+"), "w",
compression=zipfile.ZIP_DEFLATED)
score = {'WHEEL': 1, 'METADATA': 2, 'RECORD': 3}
deferred = []
def writefile(path):
zip.write(path, path)
log.info("adding '%s'" % path)
for dirpath, dirnames, filenames in os.walk(base_dir):
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
if dirpath.endswith('.dist-info'):
deferred.append((score.get(name, 0), path))
else:
writefile(path)
deferred.sort()
for score, path in deferred:
writefile(path)
zip.close()
return zip_filename
|
def make_wheelfile_inner(base_name, base_dir='.'):
"""Create a whl file from all the files under 'base_dir'.
Places .dist-info at the end of the archive."""
zip_filename = base_name + ".whl"
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
# XXX support bz2, xz when available
zip = zipfile.ZipFile(open(zip_filename, "wb+"), "w",
compression=zipfile.ZIP_DEFLATED)
score = {'WHEEL': 1, 'METADATA': 2, 'RECORD': 3}
deferred = []
def writefile(path):
zip.write(path, path)
log.info("adding '%s'" % path)
for dirpath, dirnames, filenames in os.walk(base_dir):
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
if dirpath.endswith('.dist-info'):
deferred.append((score.get(name, 0), path))
else:
writefile(path)
deferred.sort()
for score, path in deferred:
writefile(path)
zip.close()
return zip_filename
|
[
"Create",
"a",
"whl",
"file",
"from",
"all",
"the",
"files",
"under",
"base_dir",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/archive.py#L25-L61
|
[
"def",
"make_wheelfile_inner",
"(",
"base_name",
",",
"base_dir",
"=",
"'.'",
")",
":",
"zip_filename",
"=",
"base_name",
"+",
"\".whl\"",
"log",
".",
"info",
"(",
"\"creating '%s' and adding '%s' to it\"",
",",
"zip_filename",
",",
"base_dir",
")",
"# XXX support bz2, xz when available",
"zip",
"=",
"zipfile",
".",
"ZipFile",
"(",
"open",
"(",
"zip_filename",
",",
"\"wb+\"",
")",
",",
"\"w\"",
",",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"score",
"=",
"{",
"'WHEEL'",
":",
"1",
",",
"'METADATA'",
":",
"2",
",",
"'RECORD'",
":",
"3",
"}",
"deferred",
"=",
"[",
"]",
"def",
"writefile",
"(",
"path",
")",
":",
"zip",
".",
"write",
"(",
"path",
",",
"path",
")",
"log",
".",
"info",
"(",
"\"adding '%s'\"",
"%",
"path",
")",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"base_dir",
")",
":",
"for",
"name",
"in",
"filenames",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"name",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"if",
"dirpath",
".",
"endswith",
"(",
"'.dist-info'",
")",
":",
"deferred",
".",
"append",
"(",
"(",
"score",
".",
"get",
"(",
"name",
",",
"0",
")",
",",
"path",
")",
")",
"else",
":",
"writefile",
"(",
"path",
")",
"deferred",
".",
"sort",
"(",
")",
"for",
"score",
",",
"path",
"in",
"deferred",
":",
"writefile",
"(",
"path",
")",
"zip",
".",
"close",
"(",
")",
"return",
"zip_filename"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
atomize
|
Decorate a function with a reentrant lock to prevent multiple
threads from calling said thread simultaneously.
|
jaraco/util/concurrency.py
|
def atomize(f, lock=None):
"""
Decorate a function with a reentrant lock to prevent multiple
threads from calling said thread simultaneously.
"""
lock = lock or threading.RLock()
@functools.wraps(f)
def exec_atomic(*args, **kwargs):
lock.acquire()
try:
return f(*args, **kwargs)
finally:
lock.release()
return exec_atomic
|
def atomize(f, lock=None):
"""
Decorate a function with a reentrant lock to prevent multiple
threads from calling said thread simultaneously.
"""
lock = lock or threading.RLock()
@functools.wraps(f)
def exec_atomic(*args, **kwargs):
lock.acquire()
try:
return f(*args, **kwargs)
finally:
lock.release()
return exec_atomic
|
[
"Decorate",
"a",
"function",
"with",
"a",
"reentrant",
"lock",
"to",
"prevent",
"multiple",
"threads",
"from",
"calling",
"said",
"thread",
"simultaneously",
"."
] |
jaraco/jaraco.util
|
python
|
https://github.com/jaraco/jaraco.util/blob/f21071c64f165a5cf844db15e39356e1a47f4b02/jaraco/util/concurrency.py#L7-L21
|
[
"def",
"atomize",
"(",
"f",
",",
"lock",
"=",
"None",
")",
":",
"lock",
"=",
"lock",
"or",
"threading",
".",
"RLock",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"exec_atomic",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"finally",
":",
"lock",
".",
"release",
"(",
")",
"return",
"exec_atomic"
] |
f21071c64f165a5cf844db15e39356e1a47f4b02
|
test
|
service_factory
|
Create service, start server.
:param app: application to instantiate a service
:param host: interface to bound provider
:param port: port to bound provider
:param report_message: message format to report port
:param provider_cls: server class provide a service
|
service_factory/factory.py
|
def service_factory(app, host, port,
report_message='service factory port {port}',
provider_cls=HTTPServiceProvider):
"""Create service, start server.
:param app: application to instantiate a service
:param host: interface to bound provider
:param port: port to bound provider
:param report_message: message format to report port
:param provider_cls: server class provide a service
"""
service = Service(app)
server = provider_cls(service, host, port, report_message)
server.serve_forever()
|
def service_factory(app, host, port,
report_message='service factory port {port}',
provider_cls=HTTPServiceProvider):
"""Create service, start server.
:param app: application to instantiate a service
:param host: interface to bound provider
:param port: port to bound provider
:param report_message: message format to report port
:param provider_cls: server class provide a service
"""
service = Service(app)
server = provider_cls(service, host, port, report_message)
server.serve_forever()
|
[
"Create",
"service",
"start",
"server",
"."
] |
proofit404/service-factory
|
python
|
https://github.com/proofit404/service-factory/blob/a09d4e097e5599244564a2a7f0611e58efb4156a/service_factory/factory.py#L19-L34
|
[
"def",
"service_factory",
"(",
"app",
",",
"host",
",",
"port",
",",
"report_message",
"=",
"'service factory port {port}'",
",",
"provider_cls",
"=",
"HTTPServiceProvider",
")",
":",
"service",
"=",
"Service",
"(",
"app",
")",
"server",
"=",
"provider_cls",
"(",
"service",
",",
"host",
",",
"port",
",",
"report_message",
")",
"server",
".",
"serve_forever",
"(",
")"
] |
a09d4e097e5599244564a2a7f0611e58efb4156a
|
test
|
unicode_urlencode
|
URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/utils.py
|
def unicode_urlencode(obj, charset='utf-8'):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
return text_type(url_quote(obj))
|
def unicode_urlencode(obj, charset='utf-8'):
"""URL escapes a single bytestring or unicode string with the
given charset if applicable to URL safe quoting under all rules
that need to be considered under all supported Python versions.
If non strings are provided they are converted to their unicode
representation first.
"""
if not isinstance(obj, string_types):
obj = text_type(obj)
if isinstance(obj, text_type):
obj = obj.encode(charset)
return text_type(url_quote(obj))
|
[
"URL",
"escapes",
"a",
"single",
"bytestring",
"or",
"unicode",
"string",
"with",
"the",
"given",
"charset",
"if",
"applicable",
"to",
"URL",
"safe",
"quoting",
"under",
"all",
"rules",
"that",
"need",
"to",
"be",
"considered",
"under",
"all",
"supported",
"Python",
"versions",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/utils.py#L279-L291
|
[
"def",
"unicode_urlencode",
"(",
"obj",
",",
"charset",
"=",
"'utf-8'",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"obj",
"=",
"text_type",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"text_type",
")",
":",
"obj",
"=",
"obj",
".",
"encode",
"(",
"charset",
")",
"return",
"text_type",
"(",
"url_quote",
"(",
"obj",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
matches_requirement
|
List of wheels matching a requirement.
:param req: The requirement to satisfy
:param wheels: List of wheels to search.
|
capybara/virtualenv/lib/python2.7/site-packages/wheel/util.py
|
def matches_requirement(req, wheels):
"""List of wheels matching a requirement.
:param req: The requirement to satisfy
:param wheels: List of wheels to search.
"""
try:
from pkg_resources import Distribution, Requirement
except ImportError:
raise RuntimeError("Cannot use requirements without pkg_resources")
req = Requirement.parse(req)
selected = []
for wf in wheels:
f = wf.parsed_filename
dist = Distribution(project_name=f.group("name"), version=f.group("ver"))
if dist in req:
selected.append(wf)
return selected
|
def matches_requirement(req, wheels):
"""List of wheels matching a requirement.
:param req: The requirement to satisfy
:param wheels: List of wheels to search.
"""
try:
from pkg_resources import Distribution, Requirement
except ImportError:
raise RuntimeError("Cannot use requirements without pkg_resources")
req = Requirement.parse(req)
selected = []
for wf in wheels:
f = wf.parsed_filename
dist = Distribution(project_name=f.group("name"), version=f.group("ver"))
if dist in req:
selected.append(wf)
return selected
|
[
"List",
"of",
"wheels",
"matching",
"a",
"requirement",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/util.py#L127-L146
|
[
"def",
"matches_requirement",
"(",
"req",
",",
"wheels",
")",
":",
"try",
":",
"from",
"pkg_resources",
"import",
"Distribution",
",",
"Requirement",
"except",
"ImportError",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot use requirements without pkg_resources\"",
")",
"req",
"=",
"Requirement",
".",
"parse",
"(",
"req",
")",
"selected",
"=",
"[",
"]",
"for",
"wf",
"in",
"wheels",
":",
"f",
"=",
"wf",
".",
"parsed_filename",
"dist",
"=",
"Distribution",
"(",
"project_name",
"=",
"f",
".",
"group",
"(",
"\"name\"",
")",
",",
"version",
"=",
"f",
".",
"group",
"(",
"\"ver\"",
")",
")",
"if",
"dist",
"in",
"req",
":",
"selected",
".",
"append",
"(",
"wf",
")",
"return",
"selected"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
RequirementCommand.populate_requirement_set
|
Marshal cmd line args into a requirement set.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/basecommand.py
|
def populate_requirement_set(requirement_set, args, options, finder,
session, name, wheel_cache):
"""
Marshal cmd line args into a requirement set.
"""
for req in args:
requirement_set.add_requirement(
InstallRequirement.from_line(
req, None, isolated=options.isolated_mode,
wheel_cache=wheel_cache
)
)
for req in options.editables:
requirement_set.add_requirement(
InstallRequirement.from_editable(
req,
default_vcs=options.default_vcs,
isolated=options.isolated_mode,
wheel_cache=wheel_cache
)
)
found_req_in_file = False
for filename in options.requirements:
for req in parse_requirements(
filename,
finder=finder, options=options, session=session,
wheel_cache=wheel_cache):
found_req_in_file = True
requirement_set.add_requirement(req)
if not (args or options.editables or found_req_in_file):
opts = {'name': name}
if options.find_links:
msg = ('You must give at least one requirement to '
'%(name)s (maybe you meant "pip %(name)s '
'%(links)s"?)' %
dict(opts, links=' '.join(options.find_links)))
else:
msg = ('You must give at least one requirement '
'to %(name)s (see "pip help %(name)s")' % opts)
logger.warning(msg)
|
def populate_requirement_set(requirement_set, args, options, finder,
session, name, wheel_cache):
"""
Marshal cmd line args into a requirement set.
"""
for req in args:
requirement_set.add_requirement(
InstallRequirement.from_line(
req, None, isolated=options.isolated_mode,
wheel_cache=wheel_cache
)
)
for req in options.editables:
requirement_set.add_requirement(
InstallRequirement.from_editable(
req,
default_vcs=options.default_vcs,
isolated=options.isolated_mode,
wheel_cache=wheel_cache
)
)
found_req_in_file = False
for filename in options.requirements:
for req in parse_requirements(
filename,
finder=finder, options=options, session=session,
wheel_cache=wheel_cache):
found_req_in_file = True
requirement_set.add_requirement(req)
if not (args or options.editables or found_req_in_file):
opts = {'name': name}
if options.find_links:
msg = ('You must give at least one requirement to '
'%(name)s (maybe you meant "pip %(name)s '
'%(links)s"?)' %
dict(opts, links=' '.join(options.find_links)))
else:
msg = ('You must give at least one requirement '
'to %(name)s (see "pip help %(name)s")' % opts)
logger.warning(msg)
|
[
"Marshal",
"cmd",
"line",
"args",
"into",
"a",
"requirement",
"set",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/basecommand.py#L259-L301
|
[
"def",
"populate_requirement_set",
"(",
"requirement_set",
",",
"args",
",",
"options",
",",
"finder",
",",
"session",
",",
"name",
",",
"wheel_cache",
")",
":",
"for",
"req",
"in",
"args",
":",
"requirement_set",
".",
"add_requirement",
"(",
"InstallRequirement",
".",
"from_line",
"(",
"req",
",",
"None",
",",
"isolated",
"=",
"options",
".",
"isolated_mode",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
")",
"for",
"req",
"in",
"options",
".",
"editables",
":",
"requirement_set",
".",
"add_requirement",
"(",
"InstallRequirement",
".",
"from_editable",
"(",
"req",
",",
"default_vcs",
"=",
"options",
".",
"default_vcs",
",",
"isolated",
"=",
"options",
".",
"isolated_mode",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
")",
"found_req_in_file",
"=",
"False",
"for",
"filename",
"in",
"options",
".",
"requirements",
":",
"for",
"req",
"in",
"parse_requirements",
"(",
"filename",
",",
"finder",
"=",
"finder",
",",
"options",
"=",
"options",
",",
"session",
"=",
"session",
",",
"wheel_cache",
"=",
"wheel_cache",
")",
":",
"found_req_in_file",
"=",
"True",
"requirement_set",
".",
"add_requirement",
"(",
"req",
")",
"if",
"not",
"(",
"args",
"or",
"options",
".",
"editables",
"or",
"found_req_in_file",
")",
":",
"opts",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"options",
".",
"find_links",
":",
"msg",
"=",
"(",
"'You must give at least one requirement to '",
"'%(name)s (maybe you meant \"pip %(name)s '",
"'%(links)s\"?)'",
"%",
"dict",
"(",
"opts",
",",
"links",
"=",
"' '",
".",
"join",
"(",
"options",
".",
"find_links",
")",
")",
")",
"else",
":",
"msg",
"=",
"(",
"'You must give at least one requirement '",
"'to %(name)s (see \"pip help %(name)s\")'",
"%",
"opts",
")",
"logger",
".",
"warning",
"(",
"msg",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Context.call
|
Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable is a :func:`contextfunction` or
:func:`environmentfunction`.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/runtime.py
|
def call(__self, __obj, *args, **kwargs):
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable is a :func:`contextfunction` or
:func:`environmentfunction`.
"""
if __debug__:
__traceback_hide__ = True
# Allow callable classes to take a context
fn = __obj.__call__
for fn_type in ('contextfunction',
'evalcontextfunction',
'environmentfunction'):
if hasattr(fn, fn_type):
__obj = fn
break
if isinstance(__obj, _context_function_types):
if getattr(__obj, 'contextfunction', 0):
args = (__self,) + args
elif getattr(__obj, 'evalcontextfunction', 0):
args = (__self.eval_ctx,) + args
elif getattr(__obj, 'environmentfunction', 0):
args = (__self.environment,) + args
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined('value was undefined because '
'a callable raised a '
'StopIteration exception')
|
def call(__self, __obj, *args, **kwargs):
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable is a :func:`contextfunction` or
:func:`environmentfunction`.
"""
if __debug__:
__traceback_hide__ = True
# Allow callable classes to take a context
fn = __obj.__call__
for fn_type in ('contextfunction',
'evalcontextfunction',
'environmentfunction'):
if hasattr(fn, fn_type):
__obj = fn
break
if isinstance(__obj, _context_function_types):
if getattr(__obj, 'contextfunction', 0):
args = (__self,) + args
elif getattr(__obj, 'evalcontextfunction', 0):
args = (__self.eval_ctx,) + args
elif getattr(__obj, 'environmentfunction', 0):
args = (__self.environment,) + args
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined('value was undefined because '
'a callable raised a '
'StopIteration exception')
|
[
"Call",
"the",
"callable",
"with",
"the",
"arguments",
"and",
"keyword",
"arguments",
"provided",
"but",
"inject",
"the",
"active",
"context",
"or",
"environment",
"as",
"first",
"argument",
"if",
"the",
"callable",
"is",
"a",
":",
"func",
":",
"contextfunction",
"or",
":",
"func",
":",
"environmentfunction",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/runtime.py#L167-L197
|
[
"def",
"call",
"(",
"__self",
",",
"__obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"__debug__",
":",
"__traceback_hide__",
"=",
"True",
"# Allow callable classes to take a context",
"fn",
"=",
"__obj",
".",
"__call__",
"for",
"fn_type",
"in",
"(",
"'contextfunction'",
",",
"'evalcontextfunction'",
",",
"'environmentfunction'",
")",
":",
"if",
"hasattr",
"(",
"fn",
",",
"fn_type",
")",
":",
"__obj",
"=",
"fn",
"break",
"if",
"isinstance",
"(",
"__obj",
",",
"_context_function_types",
")",
":",
"if",
"getattr",
"(",
"__obj",
",",
"'contextfunction'",
",",
"0",
")",
":",
"args",
"=",
"(",
"__self",
",",
")",
"+",
"args",
"elif",
"getattr",
"(",
"__obj",
",",
"'evalcontextfunction'",
",",
"0",
")",
":",
"args",
"=",
"(",
"__self",
".",
"eval_ctx",
",",
")",
"+",
"args",
"elif",
"getattr",
"(",
"__obj",
",",
"'environmentfunction'",
",",
"0",
")",
":",
"args",
"=",
"(",
"__self",
".",
"environment",
",",
")",
"+",
"args",
"try",
":",
"return",
"__obj",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"StopIteration",
":",
"return",
"__self",
".",
"environment",
".",
"undefined",
"(",
"'value was undefined because '",
"'a callable raised a '",
"'StopIteration exception'",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Bazaar.export
|
Export the Bazaar repository at the url to the destination location
|
capybara/virtualenv/lib/python2.7/site-packages/pip/vcs/bazaar.py
|
def export(self, location):
"""
Export the Bazaar repository at the url to the destination location
"""
temp_dir = tempfile.mkdtemp('-export', 'pip-')
self.unpack(temp_dir)
if os.path.exists(location):
# Remove the location to make sure Bazaar can export it correctly
rmtree(location)
try:
self.run_command(['export', location], cwd=temp_dir,
show_stdout=False)
finally:
rmtree(temp_dir)
|
def export(self, location):
"""
Export the Bazaar repository at the url to the destination location
"""
temp_dir = tempfile.mkdtemp('-export', 'pip-')
self.unpack(temp_dir)
if os.path.exists(location):
# Remove the location to make sure Bazaar can export it correctly
rmtree(location)
try:
self.run_command(['export', location], cwd=temp_dir,
show_stdout=False)
finally:
rmtree(temp_dir)
|
[
"Export",
"the",
"Bazaar",
"repository",
"at",
"the",
"url",
"to",
"the",
"destination",
"location"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/vcs/bazaar.py#L39-L52
|
[
"def",
"export",
"(",
"self",
",",
"location",
")",
":",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'-export'",
",",
"'pip-'",
")",
"self",
".",
"unpack",
"(",
"temp_dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"# Remove the location to make sure Bazaar can export it correctly",
"rmtree",
"(",
"location",
")",
"try",
":",
"self",
".",
"run_command",
"(",
"[",
"'export'",
",",
"location",
"]",
",",
"cwd",
"=",
"temp_dir",
",",
"show_stdout",
"=",
"False",
")",
"finally",
":",
"rmtree",
"(",
"temp_dir",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
pip_version_check
|
Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/utils/outdated.py
|
def pip_version_check(session):
"""Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path.
"""
import pip # imported here to prevent circular imports
pypi_version = None
try:
state = load_selfcheck_statefile()
current_time = datetime.datetime.utcnow()
# Determine if we need to refresh the state
if "last_check" in state.state and "pypi_version" in state.state:
last_check = datetime.datetime.strptime(
state.state["last_check"],
SELFCHECK_DATE_FMT
)
if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60:
pypi_version = state.state["pypi_version"]
# Refresh the version if we need to or just see if we need to warn
if pypi_version is None:
resp = session.get(
PyPI.pip_json_url,
headers={"Accept": "application/json"},
)
resp.raise_for_status()
pypi_version = [
v for v in sorted(
list(resp.json()["releases"]),
key=packaging_version.parse,
)
if not packaging_version.parse(v).is_prerelease
][-1]
# save that we've performed a check
state.save(pypi_version, current_time)
pip_version = packaging_version.parse(pip.__version__)
remote_version = packaging_version.parse(pypi_version)
# Determine if our pypi_version is older
if (pip_version < remote_version and
pip_version.base_version != remote_version.base_version):
# Advise "python -m pip" on Windows to avoid issues
# with overwriting pip.exe.
if WINDOWS:
pip_cmd = "python -m pip"
else:
pip_cmd = "pip"
logger.warning(
"You are using pip version %s, however version %s is "
"available.\nYou should consider upgrading via the "
"'%s install --upgrade pip' command." % (pip.__version__,
pypi_version,
pip_cmd)
)
except Exception:
logger.debug(
"There was an error checking the latest version of pip",
exc_info=True,
)
|
def pip_version_check(session):
"""Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path.
"""
import pip # imported here to prevent circular imports
pypi_version = None
try:
state = load_selfcheck_statefile()
current_time = datetime.datetime.utcnow()
# Determine if we need to refresh the state
if "last_check" in state.state and "pypi_version" in state.state:
last_check = datetime.datetime.strptime(
state.state["last_check"],
SELFCHECK_DATE_FMT
)
if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60:
pypi_version = state.state["pypi_version"]
# Refresh the version if we need to or just see if we need to warn
if pypi_version is None:
resp = session.get(
PyPI.pip_json_url,
headers={"Accept": "application/json"},
)
resp.raise_for_status()
pypi_version = [
v for v in sorted(
list(resp.json()["releases"]),
key=packaging_version.parse,
)
if not packaging_version.parse(v).is_prerelease
][-1]
# save that we've performed a check
state.save(pypi_version, current_time)
pip_version = packaging_version.parse(pip.__version__)
remote_version = packaging_version.parse(pypi_version)
# Determine if our pypi_version is older
if (pip_version < remote_version and
pip_version.base_version != remote_version.base_version):
# Advise "python -m pip" on Windows to avoid issues
# with overwriting pip.exe.
if WINDOWS:
pip_cmd = "python -m pip"
else:
pip_cmd = "pip"
logger.warning(
"You are using pip version %s, however version %s is "
"available.\nYou should consider upgrading via the "
"'%s install --upgrade pip' command." % (pip.__version__,
pypi_version,
pip_cmd)
)
except Exception:
logger.debug(
"There was an error checking the latest version of pip",
exc_info=True,
)
|
[
"Check",
"for",
"an",
"update",
"for",
"pip",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/utils/outdated.py#L95-L160
|
[
"def",
"pip_version_check",
"(",
"session",
")",
":",
"import",
"pip",
"# imported here to prevent circular imports",
"pypi_version",
"=",
"None",
"try",
":",
"state",
"=",
"load_selfcheck_statefile",
"(",
")",
"current_time",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"# Determine if we need to refresh the state",
"if",
"\"last_check\"",
"in",
"state",
".",
"state",
"and",
"\"pypi_version\"",
"in",
"state",
".",
"state",
":",
"last_check",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"state",
".",
"state",
"[",
"\"last_check\"",
"]",
",",
"SELFCHECK_DATE_FMT",
")",
"if",
"total_seconds",
"(",
"current_time",
"-",
"last_check",
")",
"<",
"7",
"*",
"24",
"*",
"60",
"*",
"60",
":",
"pypi_version",
"=",
"state",
".",
"state",
"[",
"\"pypi_version\"",
"]",
"# Refresh the version if we need to or just see if we need to warn",
"if",
"pypi_version",
"is",
"None",
":",
"resp",
"=",
"session",
".",
"get",
"(",
"PyPI",
".",
"pip_json_url",
",",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"application/json\"",
"}",
",",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"pypi_version",
"=",
"[",
"v",
"for",
"v",
"in",
"sorted",
"(",
"list",
"(",
"resp",
".",
"json",
"(",
")",
"[",
"\"releases\"",
"]",
")",
",",
"key",
"=",
"packaging_version",
".",
"parse",
",",
")",
"if",
"not",
"packaging_version",
".",
"parse",
"(",
"v",
")",
".",
"is_prerelease",
"]",
"[",
"-",
"1",
"]",
"# save that we've performed a check",
"state",
".",
"save",
"(",
"pypi_version",
",",
"current_time",
")",
"pip_version",
"=",
"packaging_version",
".",
"parse",
"(",
"pip",
".",
"__version__",
")",
"remote_version",
"=",
"packaging_version",
".",
"parse",
"(",
"pypi_version",
")",
"# Determine if our pypi_version is older",
"if",
"(",
"pip_version",
"<",
"remote_version",
"and",
"pip_version",
".",
"base_version",
"!=",
"remote_version",
".",
"base_version",
")",
":",
"# Advise \"python -m pip\" on Windows to avoid issues",
"# with overwriting pip.exe.",
"if",
"WINDOWS",
":",
"pip_cmd",
"=",
"\"python -m pip\"",
"else",
":",
"pip_cmd",
"=",
"\"pip\"",
"logger",
".",
"warning",
"(",
"\"You are using pip version %s, however version %s is \"",
"\"available.\\nYou should consider upgrading via the \"",
"\"'%s install --upgrade pip' command.\"",
"%",
"(",
"pip",
".",
"__version__",
",",
"pypi_version",
",",
"pip_cmd",
")",
")",
"except",
"Exception",
":",
"logger",
".",
"debug",
"(",
"\"There was an error checking the latest version of pip\"",
",",
"exc_info",
"=",
"True",
",",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonAPI.lookup
|
Lookup an Amazon Product.
:return:
An instance of :class:`~.AmazonProduct` if one item was returned,
or a list of :class:`~.AmazonProduct` instances if multiple
items where returned.
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def lookup(self, ResponseGroup="Large", **kwargs):
"""Lookup an Amazon Product.
:return:
An instance of :class:`~.AmazonProduct` if one item was returned,
or a list of :class:`~.AmazonProduct` instances if multiple
items where returned.
"""
response = self.api.ItemLookup(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.Items.Request.IsValid == 'False':
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
raise LookupException(
"Amazon Product Lookup Error: '{0}', '{1}'".format(code, msg))
if not hasattr(root.Items, 'Item'):
raise AsinNotFound("ASIN(s) not found: '{0}'".format(
etree.tostring(root, pretty_print=True)))
if len(root.Items.Item) > 1:
return [
AmazonProduct(
item,
self.aws_associate_tag,
self,
region=self.region) for item in root.Items.Item
]
else:
return AmazonProduct(
root.Items.Item,
self.aws_associate_tag,
self,
region=self.region
)
|
def lookup(self, ResponseGroup="Large", **kwargs):
"""Lookup an Amazon Product.
:return:
An instance of :class:`~.AmazonProduct` if one item was returned,
or a list of :class:`~.AmazonProduct` instances if multiple
items where returned.
"""
response = self.api.ItemLookup(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.Items.Request.IsValid == 'False':
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
raise LookupException(
"Amazon Product Lookup Error: '{0}', '{1}'".format(code, msg))
if not hasattr(root.Items, 'Item'):
raise AsinNotFound("ASIN(s) not found: '{0}'".format(
etree.tostring(root, pretty_print=True)))
if len(root.Items.Item) > 1:
return [
AmazonProduct(
item,
self.aws_associate_tag,
self,
region=self.region) for item in root.Items.Item
]
else:
return AmazonProduct(
root.Items.Item,
self.aws_associate_tag,
self,
region=self.region
)
|
[
"Lookup",
"an",
"Amazon",
"Product",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L101-L133
|
[
"def",
"lookup",
"(",
"self",
",",
"ResponseGroup",
"=",
"\"Large\"",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"ItemLookup",
"(",
"ResponseGroup",
"=",
"ResponseGroup",
",",
"*",
"*",
"kwargs",
")",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"response",
")",
"if",
"root",
".",
"Items",
".",
"Request",
".",
"IsValid",
"==",
"'False'",
":",
"code",
"=",
"root",
".",
"Items",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Code",
"msg",
"=",
"root",
".",
"Items",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Message",
"raise",
"LookupException",
"(",
"\"Amazon Product Lookup Error: '{0}', '{1}'\"",
".",
"format",
"(",
"code",
",",
"msg",
")",
")",
"if",
"not",
"hasattr",
"(",
"root",
".",
"Items",
",",
"'Item'",
")",
":",
"raise",
"AsinNotFound",
"(",
"\"ASIN(s) not found: '{0}'\"",
".",
"format",
"(",
"etree",
".",
"tostring",
"(",
"root",
",",
"pretty_print",
"=",
"True",
")",
")",
")",
"if",
"len",
"(",
"root",
".",
"Items",
".",
"Item",
")",
">",
"1",
":",
"return",
"[",
"AmazonProduct",
"(",
"item",
",",
"self",
".",
"aws_associate_tag",
",",
"self",
",",
"region",
"=",
"self",
".",
"region",
")",
"for",
"item",
"in",
"root",
".",
"Items",
".",
"Item",
"]",
"else",
":",
"return",
"AmazonProduct",
"(",
"root",
".",
"Items",
".",
"Item",
",",
"self",
".",
"aws_associate_tag",
",",
"self",
",",
"region",
"=",
"self",
".",
"region",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonSearch.iterate_pages
|
Iterate Pages.
A generator which iterates over all pages.
Keep in mind that Amazon limits the number of pages it makes available.
:return:
Yields lxml root elements.
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def iterate_pages(self):
"""Iterate Pages.
A generator which iterates over all pages.
Keep in mind that Amazon limits the number of pages it makes available.
:return:
Yields lxml root elements.
"""
try:
while True:
yield self._query(ItemPage=self.current_page, **self.kwargs)
self.current_page += 1
except NoMorePages:
pass
|
def iterate_pages(self):
"""Iterate Pages.
A generator which iterates over all pages.
Keep in mind that Amazon limits the number of pages it makes available.
:return:
Yields lxml root elements.
"""
try:
while True:
yield self._query(ItemPage=self.current_page, **self.kwargs)
self.current_page += 1
except NoMorePages:
pass
|
[
"Iterate",
"Pages",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L239-L253
|
[
"def",
"iterate_pages",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"yield",
"self",
".",
"_query",
"(",
"ItemPage",
"=",
"self",
".",
"current_page",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
"self",
".",
"current_page",
"+=",
"1",
"except",
"NoMorePages",
":",
"pass"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonSearch._query
|
Query.
Query Amazon search and check for errors.
:return:
An lxml root element.
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def _query(self, ResponseGroup="Large", **kwargs):
"""Query.
Query Amazon search and check for errors.
:return:
An lxml root element.
"""
response = self.api.ItemSearch(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.Items.Request.IsValid == 'False':
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
if code == 'AWS.ParameterOutOfRange':
raise NoMorePages(msg)
else:
raise SearchException(
"Amazon Search Error: '{0}', '{1}'".format(code, msg))
return root
|
def _query(self, ResponseGroup="Large", **kwargs):
"""Query.
Query Amazon search and check for errors.
:return:
An lxml root element.
"""
response = self.api.ItemSearch(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if root.Items.Request.IsValid == 'False':
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
if code == 'AWS.ParameterOutOfRange':
raise NoMorePages(msg)
else:
raise SearchException(
"Amazon Search Error: '{0}', '{1}'".format(code, msg))
return root
|
[
"Query",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L255-L273
|
[
"def",
"_query",
"(",
"self",
",",
"ResponseGroup",
"=",
"\"Large\"",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"ItemSearch",
"(",
"ResponseGroup",
"=",
"ResponseGroup",
",",
"*",
"*",
"kwargs",
")",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"response",
")",
"if",
"root",
".",
"Items",
".",
"Request",
".",
"IsValid",
"==",
"'False'",
":",
"code",
"=",
"root",
".",
"Items",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Code",
"msg",
"=",
"root",
".",
"Items",
".",
"Request",
".",
"Errors",
".",
"Error",
".",
"Message",
"if",
"code",
"==",
"'AWS.ParameterOutOfRange'",
":",
"raise",
"NoMorePages",
"(",
"msg",
")",
"else",
":",
"raise",
"SearchException",
"(",
"\"Amazon Search Error: '{0}', '{1}'\"",
".",
"format",
"(",
"code",
",",
"msg",
")",
")",
"return",
"root"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonBrowseNode.ancestor
|
This browse node's immediate ancestor in the browse node tree.
:return:
The ancestor as an :class:`~.AmazonBrowseNode`, or None.
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def ancestor(self):
"""This browse node's immediate ancestor in the browse node tree.
:return:
The ancestor as an :class:`~.AmazonBrowseNode`, or None.
"""
ancestors = getattr(self.element, 'Ancestors', None)
if hasattr(ancestors, 'BrowseNode'):
return AmazonBrowseNode(ancestors['BrowseNode'])
return None
|
def ancestor(self):
"""This browse node's immediate ancestor in the browse node tree.
:return:
The ancestor as an :class:`~.AmazonBrowseNode`, or None.
"""
ancestors = getattr(self.element, 'Ancestors', None)
if hasattr(ancestors, 'BrowseNode'):
return AmazonBrowseNode(ancestors['BrowseNode'])
return None
|
[
"This",
"browse",
"node",
"s",
"immediate",
"ancestor",
"in",
"the",
"browse",
"node",
"tree",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L311-L320
|
[
"def",
"ancestor",
"(",
"self",
")",
":",
"ancestors",
"=",
"getattr",
"(",
"self",
".",
"element",
",",
"'Ancestors'",
",",
"None",
")",
"if",
"hasattr",
"(",
"ancestors",
",",
"'BrowseNode'",
")",
":",
"return",
"AmazonBrowseNode",
"(",
"ancestors",
"[",
"'BrowseNode'",
"]",
")",
"return",
"None"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonBrowseNode.children
|
This browse node's children in the browse node tree.
:return:
A list of this browse node's children in the browse node tree.
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def children(self):
"""This browse node's children in the browse node tree.
:return:
A list of this browse node's children in the browse node tree.
"""
children = []
child_nodes = getattr(self.element, 'Children')
for child in getattr(child_nodes, 'BrowseNode', []):
children.append(AmazonBrowseNode(child))
return children
|
def children(self):
"""This browse node's children in the browse node tree.
:return:
A list of this browse node's children in the browse node tree.
"""
children = []
child_nodes = getattr(self.element, 'Children')
for child in getattr(child_nodes, 'BrowseNode', []):
children.append(AmazonBrowseNode(child))
return children
|
[
"This",
"browse",
"node",
"s",
"children",
"in",
"the",
"browse",
"node",
"tree",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L337-L347
|
[
"def",
"children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"child_nodes",
"=",
"getattr",
"(",
"self",
".",
"element",
",",
"'Children'",
")",
"for",
"child",
"in",
"getattr",
"(",
"child_nodes",
",",
"'BrowseNode'",
",",
"[",
"]",
")",
":",
"children",
".",
"append",
"(",
"AmazonBrowseNode",
"(",
"child",
")",
")",
"return",
"children"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonProduct._safe_get_element
|
Safe Get Element.
Get a child element of root (multiple levels deep) failing silently
if any descendant does not exist.
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
Element or None.
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def _safe_get_element(self, path, root=None):
"""Safe Get Element.
Get a child element of root (multiple levels deep) failing silently
if any descendant does not exist.
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
Element or None.
"""
elements = path.split('.')
parent = root if root is not None else self.item
for element in elements[:-1]:
parent = getattr(parent, element, None)
if parent is None:
return None
return getattr(parent, elements[-1], None)
|
def _safe_get_element(self, path, root=None):
"""Safe Get Element.
Get a child element of root (multiple levels deep) failing silently
if any descendant does not exist.
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
Element or None.
"""
elements = path.split('.')
parent = root if root is not None else self.item
for element in elements[:-1]:
parent = getattr(parent, element, None)
if parent is None:
return None
return getattr(parent, elements[-1], None)
|
[
"Safe",
"Get",
"Element",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L374-L393
|
[
"def",
"_safe_get_element",
"(",
"self",
",",
"path",
",",
"root",
"=",
"None",
")",
":",
"elements",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"parent",
"=",
"root",
"if",
"root",
"is",
"not",
"None",
"else",
"self",
".",
"item",
"for",
"element",
"in",
"elements",
"[",
":",
"-",
"1",
"]",
":",
"parent",
"=",
"getattr",
"(",
"parent",
",",
"element",
",",
"None",
")",
"if",
"parent",
"is",
"None",
":",
"return",
"None",
"return",
"getattr",
"(",
"parent",
",",
"elements",
"[",
"-",
"1",
"]",
",",
"None",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonProduct._safe_get_element_text
|
Safe get element text.
Get element as string or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
String or None.
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def _safe_get_element_text(self, path, root=None):
"""Safe get element text.
Get element as string or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
String or None.
"""
element = self._safe_get_element(path, root)
if element:
return element.text
else:
return None
|
def _safe_get_element_text(self, path, root=None):
"""Safe get element text.
Get element as string or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
String or None.
"""
element = self._safe_get_element(path, root)
if element:
return element.text
else:
return None
|
[
"Safe",
"get",
"element",
"text",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L395-L410
|
[
"def",
"_safe_get_element_text",
"(",
"self",
",",
"path",
",",
"root",
"=",
"None",
")",
":",
"element",
"=",
"self",
".",
"_safe_get_element",
"(",
"path",
",",
"root",
")",
"if",
"element",
":",
"return",
"element",
".",
"text",
"else",
":",
"return",
"None"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonProduct._safe_get_element_date
|
Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None.
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def _safe_get_element_date(self, path, root=None):
"""Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None.
"""
value = self._safe_get_element_text(path=path, root=root)
if value is not None:
try:
value = datetime.datetime.strptime(value, '%Y-%m-%d').date()
except ValueError:
value = None
return value
|
def _safe_get_element_date(self, path, root=None):
"""Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None.
"""
value = self._safe_get_element_text(path=path, root=root)
if value is not None:
try:
value = datetime.datetime.strptime(value, '%Y-%m-%d').date()
except ValueError:
value = None
return value
|
[
"Safe",
"get",
"elemnent",
"date",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L412-L430
|
[
"def",
"_safe_get_element_date",
"(",
"self",
",",
"path",
",",
"root",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"path",
"=",
"path",
",",
"root",
"=",
"root",
")",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"value",
",",
"'%Y-%m-%d'",
")",
".",
"date",
"(",
")",
"except",
"ValueError",
":",
"value",
"=",
"None",
"return",
"value"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonProduct.price_and_currency
|
Get Offer Price and Currency.
Return price according to the following process:
* If product has a sale return Sales Price, otherwise,
* Return Price, otherwise,
* Return lowest offer price, otherwise,
* Return None.
:return:
A tuple containing:
1. Float representation of price.
2. ISO Currency code (string).
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def price_and_currency(self):
"""Get Offer Price and Currency.
Return price according to the following process:
* If product has a sale return Sales Price, otherwise,
* Return Price, otherwise,
* Return lowest offer price, otherwise,
* Return None.
:return:
A tuple containing:
1. Float representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.CurrencyCode')
else:
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.CurrencyCode')
else:
price = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.Amount')
currency = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.CurrencyCode')
if price:
return float(price) / 100, currency
else:
return None, None
|
def price_and_currency(self):
"""Get Offer Price and Currency.
Return price according to the following process:
* If product has a sale return Sales Price, otherwise,
* Return Price, otherwise,
* Return lowest offer price, otherwise,
* Return None.
:return:
A tuple containing:
1. Float representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.SalePrice.CurrencyCode')
else:
price = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.Amount')
if price:
currency = self._safe_get_element_text(
'Offers.Offer.OfferListing.Price.CurrencyCode')
else:
price = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.Amount')
currency = self._safe_get_element_text(
'OfferSummary.LowestNewPrice.CurrencyCode')
if price:
return float(price) / 100, currency
else:
return None, None
|
[
"Get",
"Offer",
"Price",
"and",
"Currency",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L433-L468
|
[
"def",
"price_and_currency",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.Amount'",
")",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.CurrencyCode'",
")",
"if",
"price",
":",
"return",
"float",
"(",
"price",
")",
"/",
"100",
",",
"currency",
"else",
":",
"return",
"None",
",",
"None"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
AmazonProduct.list_price
|
List Price.
:return:
A tuple containing:
1. Float representation of price.
2. ISO Currency code (string).
|
capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py
|
def list_price(self):
"""List Price.
:return:
A tuple containing:
1. Float representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount')
currency = self._safe_get_element_text(
'ItemAttributes.ListPrice.CurrencyCode')
if price:
return float(price) / 100, currency
else:
return None, None
|
def list_price(self):
"""List Price.
:return:
A tuple containing:
1. Float representation of price.
2. ISO Currency code (string).
"""
price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount')
currency = self._safe_get_element_text(
'ItemAttributes.ListPrice.CurrencyCode')
if price:
return float(price) / 100, currency
else:
return None, None
|
[
"List",
"Price",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/amazon/api.py#L780-L795
|
[
"def",
"list_price",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'ItemAttributes.ListPrice.Amount'",
")",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'ItemAttributes.ListPrice.CurrencyCode'",
")",
"if",
"price",
":",
"return",
"float",
"(",
"price",
")",
"/",
"100",
",",
"currency",
"else",
":",
"return",
"None",
",",
"None"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
CacheControlAdapter.send
|
Send a request. Use the request information to see if it
exists in the cache and cache the response if we need to and can.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/cachecontrol/adapter.py
|
def send(self, request, **kw):
"""
Send a request. Use the request information to see if it
exists in the cache and cache the response if we need to and can.
"""
if request.method == 'GET':
cached_response = self.controller.cached_request(request)
if cached_response:
return self.build_response(request, cached_response,
from_cache=True)
# check for etags and add headers if appropriate
request.headers.update(
self.controller.conditional_headers(request)
)
resp = super(CacheControlAdapter, self).send(request, **kw)
return resp
|
def send(self, request, **kw):
"""
Send a request. Use the request information to see if it
exists in the cache and cache the response if we need to and can.
"""
if request.method == 'GET':
cached_response = self.controller.cached_request(request)
if cached_response:
return self.build_response(request, cached_response,
from_cache=True)
# check for etags and add headers if appropriate
request.headers.update(
self.controller.conditional_headers(request)
)
resp = super(CacheControlAdapter, self).send(request, **kw)
return resp
|
[
"Send",
"a",
"request",
".",
"Use",
"the",
"request",
"information",
"to",
"see",
"if",
"it",
"exists",
"in",
"the",
"cache",
"and",
"cache",
"the",
"response",
"if",
"we",
"need",
"to",
"and",
"can",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/cachecontrol/adapter.py#L30-L48
|
[
"def",
"send",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kw",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"cached_response",
"=",
"self",
".",
"controller",
".",
"cached_request",
"(",
"request",
")",
"if",
"cached_response",
":",
"return",
"self",
".",
"build_response",
"(",
"request",
",",
"cached_response",
",",
"from_cache",
"=",
"True",
")",
"# check for etags and add headers if appropriate",
"request",
".",
"headers",
".",
"update",
"(",
"self",
".",
"controller",
".",
"conditional_headers",
"(",
"request",
")",
")",
"resp",
"=",
"super",
"(",
"CacheControlAdapter",
",",
"self",
")",
".",
"send",
"(",
"request",
",",
"*",
"*",
"kw",
")",
"return",
"resp"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
CacheControlAdapter.build_response
|
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
|
capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/cachecontrol/adapter.py
|
def build_response(self, request, response, from_cache=False):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
if not from_cache and request.method == 'GET':
# apply any expiration heuristics
if response.status == 304:
# We must have sent an ETag request. This could mean
# that we've been expired already or that we simply
# have an etag. In either case, we want to try and
# update the cache if that is the case.
cached_response = self.controller.update_cached_response(
request, response
)
if cached_response is not response:
from_cache = True
# We are done with the server response, read a
# possible response body (compliant servers will
# not return one, but we cannot be 100% sure) and
# release the connection back to the pool.
response.read(decode_content=False)
response.release_conn()
response = cached_response
# We always cache the 301 responses
elif response.status == 301:
self.controller.cache_response(request, response)
else:
# Check for any heuristics that might update headers
# before trying to cache.
if self.heuristic:
response = self.heuristic.apply(response)
# Wrap the response file with a wrapper that will cache the
# response when the stream has been consumed.
response._fp = CallbackFileWrapper(
response._fp,
functools.partial(
self.controller.cache_response,
request,
response,
)
)
resp = super(CacheControlAdapter, self).build_response(
request, response
)
# See if we should invalidate the cache.
if request.method in self.invalidating_methods and resp.ok:
cache_url = self.controller.cache_url(request.url)
self.cache.delete(cache_url)
# Give the request a from_cache attr to let people use it
resp.from_cache = from_cache
return resp
|
def build_response(self, request, response, from_cache=False):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
if not from_cache and request.method == 'GET':
# apply any expiration heuristics
if response.status == 304:
# We must have sent an ETag request. This could mean
# that we've been expired already or that we simply
# have an etag. In either case, we want to try and
# update the cache if that is the case.
cached_response = self.controller.update_cached_response(
request, response
)
if cached_response is not response:
from_cache = True
# We are done with the server response, read a
# possible response body (compliant servers will
# not return one, but we cannot be 100% sure) and
# release the connection back to the pool.
response.read(decode_content=False)
response.release_conn()
response = cached_response
# We always cache the 301 responses
elif response.status == 301:
self.controller.cache_response(request, response)
else:
# Check for any heuristics that might update headers
# before trying to cache.
if self.heuristic:
response = self.heuristic.apply(response)
# Wrap the response file with a wrapper that will cache the
# response when the stream has been consumed.
response._fp = CallbackFileWrapper(
response._fp,
functools.partial(
self.controller.cache_response,
request,
response,
)
)
resp = super(CacheControlAdapter, self).build_response(
request, response
)
# See if we should invalidate the cache.
if request.method in self.invalidating_methods and resp.ok:
cache_url = self.controller.cache_url(request.url)
self.cache.delete(cache_url)
# Give the request a from_cache attr to let people use it
resp.from_cache = from_cache
return resp
|
[
"Build",
"a",
"response",
"by",
"making",
"a",
"request",
"or",
"using",
"the",
"cache",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/cachecontrol/adapter.py#L50-L113
|
[
"def",
"build_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"from_cache",
"=",
"False",
")",
":",
"if",
"not",
"from_cache",
"and",
"request",
".",
"method",
"==",
"'GET'",
":",
"# apply any expiration heuristics",
"if",
"response",
".",
"status",
"==",
"304",
":",
"# We must have sent an ETag request. This could mean",
"# that we've been expired already or that we simply",
"# have an etag. In either case, we want to try and",
"# update the cache if that is the case.",
"cached_response",
"=",
"self",
".",
"controller",
".",
"update_cached_response",
"(",
"request",
",",
"response",
")",
"if",
"cached_response",
"is",
"not",
"response",
":",
"from_cache",
"=",
"True",
"# We are done with the server response, read a",
"# possible response body (compliant servers will",
"# not return one, but we cannot be 100% sure) and",
"# release the connection back to the pool.",
"response",
".",
"read",
"(",
"decode_content",
"=",
"False",
")",
"response",
".",
"release_conn",
"(",
")",
"response",
"=",
"cached_response",
"# We always cache the 301 responses",
"elif",
"response",
".",
"status",
"==",
"301",
":",
"self",
".",
"controller",
".",
"cache_response",
"(",
"request",
",",
"response",
")",
"else",
":",
"# Check for any heuristics that might update headers",
"# before trying to cache.",
"if",
"self",
".",
"heuristic",
":",
"response",
"=",
"self",
".",
"heuristic",
".",
"apply",
"(",
"response",
")",
"# Wrap the response file with a wrapper that will cache the",
"# response when the stream has been consumed.",
"response",
".",
"_fp",
"=",
"CallbackFileWrapper",
"(",
"response",
".",
"_fp",
",",
"functools",
".",
"partial",
"(",
"self",
".",
"controller",
".",
"cache_response",
",",
"request",
",",
"response",
",",
")",
")",
"resp",
"=",
"super",
"(",
"CacheControlAdapter",
",",
"self",
")",
".",
"build_response",
"(",
"request",
",",
"response",
")",
"# See if we should invalidate the cache.",
"if",
"request",
".",
"method",
"in",
"self",
".",
"invalidating_methods",
"and",
"resp",
".",
"ok",
":",
"cache_url",
"=",
"self",
".",
"controller",
".",
"cache_url",
"(",
"request",
".",
"url",
")",
"self",
".",
"cache",
".",
"delete",
"(",
"cache_url",
")",
"# Give the request a from_cache attr to let people use it",
"resp",
".",
"from_cache",
"=",
"from_cache",
"return",
"resp"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
make_attrgetter
|
Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py
|
def make_attrgetter(environment, attribute):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
if not isinstance(attribute, string_types) \
or ('.' not in attribute and not attribute.isdigit()):
return lambda x: environment.getitem(x, attribute)
attribute = attribute.split('.')
def attrgetter(item):
for part in attribute:
if part.isdigit():
part = int(part)
item = environment.getitem(item, part)
return item
return attrgetter
|
def make_attrgetter(environment, attribute):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
if not isinstance(attribute, string_types) \
or ('.' not in attribute and not attribute.isdigit()):
return lambda x: environment.getitem(x, attribute)
attribute = attribute.split('.')
def attrgetter(item):
for part in attribute:
if part.isdigit():
part = int(part)
item = environment.getitem(item, part)
return item
return attrgetter
|
[
"Returns",
"a",
"callable",
"that",
"looks",
"up",
"the",
"given",
"attribute",
"from",
"a",
"passed",
"object",
"with",
"the",
"rules",
"of",
"the",
"environment",
".",
"Dots",
"are",
"allowed",
"to",
"access",
"attributes",
"of",
"attributes",
".",
"Integer",
"parts",
"in",
"paths",
"are",
"looked",
"up",
"as",
"integers",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py#L54-L70
|
[
"def",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
":",
"if",
"not",
"isinstance",
"(",
"attribute",
",",
"string_types",
")",
"or",
"(",
"'.'",
"not",
"in",
"attribute",
"and",
"not",
"attribute",
".",
"isdigit",
"(",
")",
")",
":",
"return",
"lambda",
"x",
":",
"environment",
".",
"getitem",
"(",
"x",
",",
"attribute",
")",
"attribute",
"=",
"attribute",
".",
"split",
"(",
"'.'",
")",
"def",
"attrgetter",
"(",
"item",
")",
":",
"for",
"part",
"in",
"attribute",
":",
"if",
"part",
".",
"isdigit",
"(",
")",
":",
"part",
"=",
"int",
"(",
"part",
")",
"item",
"=",
"environment",
".",
"getitem",
"(",
"item",
",",
"part",
")",
"return",
"item",
"return",
"attrgetter"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
do_title
|
Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py
|
def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
rv = []
for item in re.compile(r'([-\s]+)(?u)').split(s):
if not item:
continue
rv.append(item[0].upper() + item[1:].lower())
return ''.join(rv)
|
def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
rv = []
for item in re.compile(r'([-\s]+)(?u)').split(s):
if not item:
continue
rv.append(item[0].upper() + item[1:].lower())
return ''.join(rv)
|
[
"Return",
"a",
"titlecased",
"version",
"of",
"the",
"value",
".",
"I",
".",
"e",
".",
"words",
"will",
"start",
"with",
"uppercase",
"letters",
"all",
"remaining",
"characters",
"are",
"lowercase",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py#L181-L190
|
[
"def",
"do_title",
"(",
"s",
")",
":",
"rv",
"=",
"[",
"]",
"for",
"item",
"in",
"re",
".",
"compile",
"(",
"r'([-\\s]+)(?u)'",
")",
".",
"split",
"(",
"s",
")",
":",
"if",
"not",
"item",
":",
"continue",
"rv",
".",
"append",
"(",
"item",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"item",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
")",
"return",
"''",
".",
"join",
"(",
"rv",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
do_dictsort
|
Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dictsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by key, case insensitive, sorted
normally and ordered by value.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py
|
def do_dictsort(value, case_sensitive=False, by='key'):
"""Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dictsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by key, case insensitive, sorted
normally and ordered by value.
"""
if by == 'key':
pos = 0
elif by == 'value':
pos = 1
else:
raise FilterArgumentError('You can only sort by either '
'"key" or "value"')
def sort_func(item):
value = item[pos]
if isinstance(value, string_types) and not case_sensitive:
value = value.lower()
return value
return sorted(value.items(), key=sort_func)
|
def do_dictsort(value, case_sensitive=False, by='key'):
"""Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dictsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by key, case insensitive, sorted
normally and ordered by value.
"""
if by == 'key':
pos = 0
elif by == 'value':
pos = 1
else:
raise FilterArgumentError('You can only sort by either '
'"key" or "value"')
def sort_func(item):
value = item[pos]
if isinstance(value, string_types) and not case_sensitive:
value = value.lower()
return value
return sorted(value.items(), key=sort_func)
|
[
"Sort",
"a",
"dict",
"and",
"yield",
"(",
"key",
"value",
")",
"pairs",
".",
"Because",
"python",
"dicts",
"are",
"unsorted",
"you",
"may",
"want",
"to",
"use",
"this",
"function",
"to",
"order",
"them",
"by",
"either",
"key",
"or",
"value",
":"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py#L193-L223
|
[
"def",
"do_dictsort",
"(",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"by",
"=",
"'key'",
")",
":",
"if",
"by",
"==",
"'key'",
":",
"pos",
"=",
"0",
"elif",
"by",
"==",
"'value'",
":",
"pos",
"=",
"1",
"else",
":",
"raise",
"FilterArgumentError",
"(",
"'You can only sort by either '",
"'\"key\" or \"value\"'",
")",
"def",
"sort_func",
"(",
"item",
")",
":",
"value",
"=",
"item",
"[",
"pos",
"]",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
"and",
"not",
"case_sensitive",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"return",
"value",
"return",
"sorted",
"(",
"value",
".",
"items",
"(",
")",
",",
"key",
"=",
"sort_func",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
do_sort
|
Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py
|
def do_sort(environment, value, reverse=False, case_sensitive=False,
attribute=None):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
"""
if not case_sensitive:
def sort_func(item):
if isinstance(item, string_types):
item = item.lower()
return item
else:
sort_func = None
if attribute is not None:
getter = make_attrgetter(environment, attribute)
def sort_func(item, processor=sort_func or (lambda x: x)):
return processor(getter(item))
return sorted(value, key=sort_func, reverse=reverse)
|
def do_sort(environment, value, reverse=False, case_sensitive=False,
attribute=None):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
"""
if not case_sensitive:
def sort_func(item):
if isinstance(item, string_types):
item = item.lower()
return item
else:
sort_func = None
if attribute is not None:
getter = make_attrgetter(environment, attribute)
def sort_func(item, processor=sort_func or (lambda x: x)):
return processor(getter(item))
return sorted(value, key=sort_func, reverse=reverse)
|
[
"Sort",
"an",
"iterable",
".",
"Per",
"default",
"it",
"sorts",
"ascending",
"if",
"you",
"pass",
"it",
"true",
"as",
"first",
"argument",
"it",
"will",
"reverse",
"the",
"sorting",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py#L227-L265
|
[
"def",
"do_sort",
"(",
"environment",
",",
"value",
",",
"reverse",
"=",
"False",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"if",
"not",
"case_sensitive",
":",
"def",
"sort_func",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"string_types",
")",
":",
"item",
"=",
"item",
".",
"lower",
"(",
")",
"return",
"item",
"else",
":",
"sort_func",
"=",
"None",
"if",
"attribute",
"is",
"not",
"None",
":",
"getter",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
"def",
"sort_func",
"(",
"item",
",",
"processor",
"=",
"sort_func",
"or",
"(",
"lambda",
"x",
":",
"x",
")",
")",
":",
"return",
"processor",
"(",
"getter",
"(",
"item",
")",
")",
"return",
"sorted",
"(",
"value",
",",
"key",
"=",
"sort_func",
",",
"reverse",
"=",
"reverse",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
do_groupby
|
Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute.
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py
|
def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute.
"""
expr = make_attrgetter(environment, attribute)
return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))
|
def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute.
"""
expr = make_attrgetter(environment, attribute)
return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))
|
[
"Group",
"a",
"sequence",
"of",
"objects",
"by",
"a",
"common",
"attribute",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py#L663-L702
|
[
"def",
"do_groupby",
"(",
"environment",
",",
"value",
",",
"attribute",
")",
":",
"expr",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
"return",
"sorted",
"(",
"map",
"(",
"_GroupTuple",
",",
"groupby",
"(",
"sorted",
"(",
"value",
",",
"key",
"=",
"expr",
")",
",",
"expr",
")",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
do_map
|
Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7
|
capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py
|
def do_map(*args, **kwargs):
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7
"""
context = args[0]
seq = args[1]
if len(args) == 2 and 'attribute' in kwargs:
attribute = kwargs.pop('attribute')
if kwargs:
raise FilterArgumentError('Unexpected keyword argument %r' %
next(iter(kwargs)))
func = make_attrgetter(context.environment, attribute)
else:
try:
name = args[2]
args = args[3:]
except LookupError:
raise FilterArgumentError('map requires a filter argument')
func = lambda item: context.environment.call_filter(
name, item, args, kwargs, context=context)
if seq:
for item in seq:
yield func(item)
|
def do_map(*args, **kwargs):
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7
"""
context = args[0]
seq = args[1]
if len(args) == 2 and 'attribute' in kwargs:
attribute = kwargs.pop('attribute')
if kwargs:
raise FilterArgumentError('Unexpected keyword argument %r' %
next(iter(kwargs)))
func = make_attrgetter(context.environment, attribute)
else:
try:
name = args[2]
args = args[3:]
except LookupError:
raise FilterArgumentError('map requires a filter argument')
func = lambda item: context.environment.call_filter(
name, item, args, kwargs, context=context)
if seq:
for item in seq:
yield func(item)
|
[
"Applies",
"a",
"filter",
"on",
"a",
"sequence",
"of",
"objects",
"or",
"looks",
"up",
"an",
"attribute",
".",
"This",
"is",
"useful",
"when",
"dealing",
"with",
"lists",
"of",
"objects",
"but",
"you",
"are",
"really",
"only",
"interested",
"in",
"a",
"certain",
"value",
"of",
"it",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/filters.py#L798-L840
|
[
"def",
"do_map",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"args",
"[",
"0",
"]",
"seq",
"=",
"args",
"[",
"1",
"]",
"if",
"len",
"(",
"args",
")",
"==",
"2",
"and",
"'attribute'",
"in",
"kwargs",
":",
"attribute",
"=",
"kwargs",
".",
"pop",
"(",
"'attribute'",
")",
"if",
"kwargs",
":",
"raise",
"FilterArgumentError",
"(",
"'Unexpected keyword argument %r'",
"%",
"next",
"(",
"iter",
"(",
"kwargs",
")",
")",
")",
"func",
"=",
"make_attrgetter",
"(",
"context",
".",
"environment",
",",
"attribute",
")",
"else",
":",
"try",
":",
"name",
"=",
"args",
"[",
"2",
"]",
"args",
"=",
"args",
"[",
"3",
":",
"]",
"except",
"LookupError",
":",
"raise",
"FilterArgumentError",
"(",
"'map requires a filter argument'",
")",
"func",
"=",
"lambda",
"item",
":",
"context",
".",
"environment",
".",
"call_filter",
"(",
"name",
",",
"item",
",",
"args",
",",
"kwargs",
",",
"context",
"=",
"context",
")",
"if",
"seq",
":",
"for",
"item",
"in",
"seq",
":",
"yield",
"func",
"(",
"item",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
create_logger
|
Creates a logger for the given application. This logger works
similar to a regular Python logger but changes the effective logging
level based on the application's debug flag. Furthermore this
function also removes all attached handlers in case there was a
logger with the log name before.
|
capybara/virtualenv/lib/python2.7/site-packages/flask/logging.py
|
def create_logger(app):
"""Creates a logger for the given application. This logger works
similar to a regular Python logger but changes the effective logging
level based on the application's debug flag. Furthermore this
function also removes all attached handlers in case there was a
logger with the log name before.
"""
Logger = getLoggerClass()
class DebugLogger(Logger):
def getEffectiveLevel(x):
if x.level == 0 and app.debug:
return DEBUG
return Logger.getEffectiveLevel(x)
class DebugHandler(StreamHandler):
def emit(x, record):
StreamHandler.emit(x, record) if app.debug else None
handler = DebugHandler()
handler.setLevel(DEBUG)
handler.setFormatter(Formatter(app.debug_log_format))
logger = getLogger(app.logger_name)
# just in case that was not a new logger, get rid of all the handlers
# already attached to it.
del logger.handlers[:]
logger.__class__ = DebugLogger
logger.addHandler(handler)
return logger
|
def create_logger(app):
"""Creates a logger for the given application. This logger works
similar to a regular Python logger but changes the effective logging
level based on the application's debug flag. Furthermore this
function also removes all attached handlers in case there was a
logger with the log name before.
"""
Logger = getLoggerClass()
class DebugLogger(Logger):
def getEffectiveLevel(x):
if x.level == 0 and app.debug:
return DEBUG
return Logger.getEffectiveLevel(x)
class DebugHandler(StreamHandler):
def emit(x, record):
StreamHandler.emit(x, record) if app.debug else None
handler = DebugHandler()
handler.setLevel(DEBUG)
handler.setFormatter(Formatter(app.debug_log_format))
logger = getLogger(app.logger_name)
# just in case that was not a new logger, get rid of all the handlers
# already attached to it.
del logger.handlers[:]
logger.__class__ = DebugLogger
logger.addHandler(handler)
return logger
|
[
"Creates",
"a",
"logger",
"for",
"the",
"given",
"application",
".",
"This",
"logger",
"works",
"similar",
"to",
"a",
"regular",
"Python",
"logger",
"but",
"changes",
"the",
"effective",
"logging",
"level",
"based",
"on",
"the",
"application",
"s",
"debug",
"flag",
".",
"Furthermore",
"this",
"function",
"also",
"removes",
"all",
"attached",
"handlers",
"in",
"case",
"there",
"was",
"a",
"logger",
"with",
"the",
"log",
"name",
"before",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/logging.py#L17-L45
|
[
"def",
"create_logger",
"(",
"app",
")",
":",
"Logger",
"=",
"getLoggerClass",
"(",
")",
"class",
"DebugLogger",
"(",
"Logger",
")",
":",
"def",
"getEffectiveLevel",
"(",
"x",
")",
":",
"if",
"x",
".",
"level",
"==",
"0",
"and",
"app",
".",
"debug",
":",
"return",
"DEBUG",
"return",
"Logger",
".",
"getEffectiveLevel",
"(",
"x",
")",
"class",
"DebugHandler",
"(",
"StreamHandler",
")",
":",
"def",
"emit",
"(",
"x",
",",
"record",
")",
":",
"StreamHandler",
".",
"emit",
"(",
"x",
",",
"record",
")",
"if",
"app",
".",
"debug",
"else",
"None",
"handler",
"=",
"DebugHandler",
"(",
")",
"handler",
".",
"setLevel",
"(",
"DEBUG",
")",
"handler",
".",
"setFormatter",
"(",
"Formatter",
"(",
"app",
".",
"debug_log_format",
")",
")",
"logger",
"=",
"getLogger",
"(",
"app",
".",
"logger_name",
")",
"# just in case that was not a new logger, get rid of all the handlers",
"# already attached to it.",
"del",
"logger",
".",
"handlers",
"[",
":",
"]",
"logger",
".",
"__class__",
"=",
"DebugLogger",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"return",
"logger"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
constant_time_compare
|
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match. Do
not use this function for anything else than comparision with known
length targets.
This is should be implemented in C in order to get it completely right.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def constant_time_compare(val1, val2):
"""Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match. Do
not use this function for anything else than comparision with known
length targets.
This is should be implemented in C in order to get it completely right.
"""
if _builtin_constant_time_compare is not None:
return _builtin_constant_time_compare(val1, val2)
len_eq = len(val1) == len(val2)
if len_eq:
result = 0
left = val1
else:
result = 1
left = val2
for x, y in izip(bytearray(left), bytearray(val2)):
result |= x ^ y
return result == 0
|
def constant_time_compare(val1, val2):
"""Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match. Do
not use this function for anything else than comparision with known
length targets.
This is should be implemented in C in order to get it completely right.
"""
if _builtin_constant_time_compare is not None:
return _builtin_constant_time_compare(val1, val2)
len_eq = len(val1) == len(val2)
if len_eq:
result = 0
left = val1
else:
result = 1
left = val2
for x, y in izip(bytearray(left), bytearray(val2)):
result |= x ^ y
return result == 0
|
[
"Returns",
"True",
"if",
"the",
"two",
"strings",
"are",
"equal",
"False",
"otherwise",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L77-L97
|
[
"def",
"constant_time_compare",
"(",
"val1",
",",
"val2",
")",
":",
"if",
"_builtin_constant_time_compare",
"is",
"not",
"None",
":",
"return",
"_builtin_constant_time_compare",
"(",
"val1",
",",
"val2",
")",
"len_eq",
"=",
"len",
"(",
"val1",
")",
"==",
"len",
"(",
"val2",
")",
"if",
"len_eq",
":",
"result",
"=",
"0",
"left",
"=",
"val1",
"else",
":",
"result",
"=",
"1",
"left",
"=",
"val2",
"for",
"x",
",",
"y",
"in",
"izip",
"(",
"bytearray",
"(",
"left",
")",
",",
"bytearray",
"(",
"val2",
")",
")",
":",
"result",
"|=",
"x",
"^",
"y",
"return",
"result",
"==",
"0"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
base64_encode
|
base64 encodes a single bytestring (and is tolerant to getting
called with a unicode string).
The resulting bytestring is safe for putting into URLs.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def base64_encode(string):
"""base64 encodes a single bytestring (and is tolerant to getting
called with a unicode string).
The resulting bytestring is safe for putting into URLs.
"""
string = want_bytes(string)
return base64.urlsafe_b64encode(string).strip(b'=')
|
def base64_encode(string):
"""base64 encodes a single bytestring (and is tolerant to getting
called with a unicode string).
The resulting bytestring is safe for putting into URLs.
"""
string = want_bytes(string)
return base64.urlsafe_b64encode(string).strip(b'=')
|
[
"base64",
"encodes",
"a",
"single",
"bytestring",
"(",
"and",
"is",
"tolerant",
"to",
"getting",
"called",
"with",
"a",
"unicode",
"string",
")",
".",
"The",
"resulting",
"bytestring",
"is",
"safe",
"for",
"putting",
"into",
"URLs",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L201-L207
|
[
"def",
"base64_encode",
"(",
"string",
")",
":",
"string",
"=",
"want_bytes",
"(",
"string",
")",
"return",
"base64",
".",
"urlsafe_b64encode",
"(",
"string",
")",
".",
"strip",
"(",
"b'='",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
base64_decode
|
base64 decodes a single bytestring (and is tolerant to getting
called with a unicode string).
The result is also a bytestring.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def base64_decode(string):
"""base64 decodes a single bytestring (and is tolerant to getting
called with a unicode string).
The result is also a bytestring.
"""
string = want_bytes(string, encoding='ascii', errors='ignore')
return base64.urlsafe_b64decode(string + b'=' * (-len(string) % 4))
|
def base64_decode(string):
"""base64 decodes a single bytestring (and is tolerant to getting
called with a unicode string).
The result is also a bytestring.
"""
string = want_bytes(string, encoding='ascii', errors='ignore')
return base64.urlsafe_b64decode(string + b'=' * (-len(string) % 4))
|
[
"base64",
"decodes",
"a",
"single",
"bytestring",
"(",
"and",
"is",
"tolerant",
"to",
"getting",
"called",
"with",
"a",
"unicode",
"string",
")",
".",
"The",
"result",
"is",
"also",
"a",
"bytestring",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L210-L216
|
[
"def",
"base64_decode",
"(",
"string",
")",
":",
"string",
"=",
"want_bytes",
"(",
"string",
",",
"encoding",
"=",
"'ascii'",
",",
"errors",
"=",
"'ignore'",
")",
"return",
"base64",
".",
"urlsafe_b64decode",
"(",
"string",
"+",
"b'='",
"*",
"(",
"-",
"len",
"(",
"string",
")",
"%",
"4",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
SigningAlgorithm.verify_signature
|
Verifies the given signature matches the expected signature
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def verify_signature(self, key, value, sig):
"""Verifies the given signature matches the expected signature"""
return constant_time_compare(sig, self.get_signature(key, value))
|
def verify_signature(self, key, value, sig):
"""Verifies the given signature matches the expected signature"""
return constant_time_compare(sig, self.get_signature(key, value))
|
[
"Verifies",
"the",
"given",
"signature",
"matches",
"the",
"expected",
"signature"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L241-L243
|
[
"def",
"verify_signature",
"(",
"self",
",",
"key",
",",
"value",
",",
"sig",
")",
":",
"return",
"constant_time_compare",
"(",
"sig",
",",
"self",
".",
"get_signature",
"(",
"key",
",",
"value",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Signer.derive_key
|
This method is called to derive the key. If you're unhappy with
the default key derivation choices you can override them here.
Keep in mind that the key derivation in itsdangerous is not intended
to be used as a security method to make a complex key out of a short
password. Instead you should use large random secret keys.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def derive_key(self):
"""This method is called to derive the key. If you're unhappy with
the default key derivation choices you can override them here.
Keep in mind that the key derivation in itsdangerous is not intended
to be used as a security method to make a complex key out of a short
password. Instead you should use large random secret keys.
"""
salt = want_bytes(self.salt)
if self.key_derivation == 'concat':
return self.digest_method(salt + self.secret_key).digest()
elif self.key_derivation == 'django-concat':
return self.digest_method(salt + b'signer' +
self.secret_key).digest()
elif self.key_derivation == 'hmac':
mac = hmac.new(self.secret_key, digestmod=self.digest_method)
mac.update(salt)
return mac.digest()
elif self.key_derivation == 'none':
return self.secret_key
else:
raise TypeError('Unknown key derivation method')
|
def derive_key(self):
"""This method is called to derive the key. If you're unhappy with
the default key derivation choices you can override them here.
Keep in mind that the key derivation in itsdangerous is not intended
to be used as a security method to make a complex key out of a short
password. Instead you should use large random secret keys.
"""
salt = want_bytes(self.salt)
if self.key_derivation == 'concat':
return self.digest_method(salt + self.secret_key).digest()
elif self.key_derivation == 'django-concat':
return self.digest_method(salt + b'signer' +
self.secret_key).digest()
elif self.key_derivation == 'hmac':
mac = hmac.new(self.secret_key, digestmod=self.digest_method)
mac.update(salt)
return mac.digest()
elif self.key_derivation == 'none':
return self.secret_key
else:
raise TypeError('Unknown key derivation method')
|
[
"This",
"method",
"is",
"called",
"to",
"derive",
"the",
"key",
".",
"If",
"you",
"re",
"unhappy",
"with",
"the",
"default",
"key",
"derivation",
"choices",
"you",
"can",
"override",
"them",
"here",
".",
"Keep",
"in",
"mind",
"that",
"the",
"key",
"derivation",
"in",
"itsdangerous",
"is",
"not",
"intended",
"to",
"be",
"used",
"as",
"a",
"security",
"method",
"to",
"make",
"a",
"complex",
"key",
"out",
"of",
"a",
"short",
"password",
".",
"Instead",
"you",
"should",
"use",
"large",
"random",
"secret",
"keys",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L322-L342
|
[
"def",
"derive_key",
"(",
"self",
")",
":",
"salt",
"=",
"want_bytes",
"(",
"self",
".",
"salt",
")",
"if",
"self",
".",
"key_derivation",
"==",
"'concat'",
":",
"return",
"self",
".",
"digest_method",
"(",
"salt",
"+",
"self",
".",
"secret_key",
")",
".",
"digest",
"(",
")",
"elif",
"self",
".",
"key_derivation",
"==",
"'django-concat'",
":",
"return",
"self",
".",
"digest_method",
"(",
"salt",
"+",
"b'signer'",
"+",
"self",
".",
"secret_key",
")",
".",
"digest",
"(",
")",
"elif",
"self",
".",
"key_derivation",
"==",
"'hmac'",
":",
"mac",
"=",
"hmac",
".",
"new",
"(",
"self",
".",
"secret_key",
",",
"digestmod",
"=",
"self",
".",
"digest_method",
")",
"mac",
".",
"update",
"(",
"salt",
")",
"return",
"mac",
".",
"digest",
"(",
")",
"elif",
"self",
".",
"key_derivation",
"==",
"'none'",
":",
"return",
"self",
".",
"secret_key",
"else",
":",
"raise",
"TypeError",
"(",
"'Unknown key derivation method'",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Signer.get_signature
|
Returns the signature for the given value
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def get_signature(self, value):
"""Returns the signature for the given value"""
value = want_bytes(value)
key = self.derive_key()
sig = self.algorithm.get_signature(key, value)
return base64_encode(sig)
|
def get_signature(self, value):
"""Returns the signature for the given value"""
value = want_bytes(value)
key = self.derive_key()
sig = self.algorithm.get_signature(key, value)
return base64_encode(sig)
|
[
"Returns",
"the",
"signature",
"for",
"the",
"given",
"value"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L344-L349
|
[
"def",
"get_signature",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"want_bytes",
"(",
"value",
")",
"key",
"=",
"self",
".",
"derive_key",
"(",
")",
"sig",
"=",
"self",
".",
"algorithm",
".",
"get_signature",
"(",
"key",
",",
"value",
")",
"return",
"base64_encode",
"(",
"sig",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Signer.sign
|
Signs the given string.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def sign(self, value):
"""Signs the given string."""
return value + want_bytes(self.sep) + self.get_signature(value)
|
def sign(self, value):
"""Signs the given string."""
return value + want_bytes(self.sep) + self.get_signature(value)
|
[
"Signs",
"the",
"given",
"string",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L351-L353
|
[
"def",
"sign",
"(",
"self",
",",
"value",
")",
":",
"return",
"value",
"+",
"want_bytes",
"(",
"self",
".",
"sep",
")",
"+",
"self",
".",
"get_signature",
"(",
"value",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Signer.verify_signature
|
Verifies the signature for the given value.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def verify_signature(self, value, sig):
"""Verifies the signature for the given value."""
key = self.derive_key()
try:
sig = base64_decode(sig)
except Exception:
return False
return self.algorithm.verify_signature(key, value, sig)
|
def verify_signature(self, value, sig):
"""Verifies the signature for the given value."""
key = self.derive_key()
try:
sig = base64_decode(sig)
except Exception:
return False
return self.algorithm.verify_signature(key, value, sig)
|
[
"Verifies",
"the",
"signature",
"for",
"the",
"given",
"value",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L355-L362
|
[
"def",
"verify_signature",
"(",
"self",
",",
"value",
",",
"sig",
")",
":",
"key",
"=",
"self",
".",
"derive_key",
"(",
")",
"try",
":",
"sig",
"=",
"base64_decode",
"(",
"sig",
")",
"except",
"Exception",
":",
"return",
"False",
"return",
"self",
".",
"algorithm",
".",
"verify_signature",
"(",
"key",
",",
"value",
",",
"sig",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Signer.unsign
|
Unsigns the given string.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def unsign(self, signed_value):
"""Unsigns the given string."""
signed_value = want_bytes(signed_value)
sep = want_bytes(self.sep)
if sep not in signed_value:
raise BadSignature('No %r found in value' % self.sep)
value, sig = signed_value.rsplit(sep, 1)
if self.verify_signature(value, sig):
return value
raise BadSignature('Signature %r does not match' % sig,
payload=value)
|
def unsign(self, signed_value):
"""Unsigns the given string."""
signed_value = want_bytes(signed_value)
sep = want_bytes(self.sep)
if sep not in signed_value:
raise BadSignature('No %r found in value' % self.sep)
value, sig = signed_value.rsplit(sep, 1)
if self.verify_signature(value, sig):
return value
raise BadSignature('Signature %r does not match' % sig,
payload=value)
|
[
"Unsigns",
"the",
"given",
"string",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L364-L374
|
[
"def",
"unsign",
"(",
"self",
",",
"signed_value",
")",
":",
"signed_value",
"=",
"want_bytes",
"(",
"signed_value",
")",
"sep",
"=",
"want_bytes",
"(",
"self",
".",
"sep",
")",
"if",
"sep",
"not",
"in",
"signed_value",
":",
"raise",
"BadSignature",
"(",
"'No %r found in value'",
"%",
"self",
".",
"sep",
")",
"value",
",",
"sig",
"=",
"signed_value",
".",
"rsplit",
"(",
"sep",
",",
"1",
")",
"if",
"self",
".",
"verify_signature",
"(",
"value",
",",
"sig",
")",
":",
"return",
"value",
"raise",
"BadSignature",
"(",
"'Signature %r does not match'",
"%",
"sig",
",",
"payload",
"=",
"value",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
TimestampSigner.sign
|
Signs the given string and also attaches a time information.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def sign(self, value):
"""Signs the given string and also attaches a time information."""
value = want_bytes(value)
timestamp = base64_encode(int_to_bytes(self.get_timestamp()))
sep = want_bytes(self.sep)
value = value + sep + timestamp
return value + sep + self.get_signature(value)
|
def sign(self, value):
"""Signs the given string and also attaches a time information."""
value = want_bytes(value)
timestamp = base64_encode(int_to_bytes(self.get_timestamp()))
sep = want_bytes(self.sep)
value = value + sep + timestamp
return value + sep + self.get_signature(value)
|
[
"Signs",
"the",
"given",
"string",
"and",
"also",
"attaches",
"a",
"time",
"information",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L406-L412
|
[
"def",
"sign",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"want_bytes",
"(",
"value",
")",
"timestamp",
"=",
"base64_encode",
"(",
"int_to_bytes",
"(",
"self",
".",
"get_timestamp",
"(",
")",
")",
")",
"sep",
"=",
"want_bytes",
"(",
"self",
".",
"sep",
")",
"value",
"=",
"value",
"+",
"sep",
"+",
"timestamp",
"return",
"value",
"+",
"sep",
"+",
"self",
".",
"get_signature",
"(",
"value",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
TimestampSigner.unsign
|
Works like the regular :meth:`~Signer.unsign` but can also
validate the time. See the base docstring of the class for
the general behavior. If `return_timestamp` is set to `True`
the timestamp of the signature will be returned as naive
:class:`datetime.datetime` object in UTC.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def unsign(self, value, max_age=None, return_timestamp=False):
"""Works like the regular :meth:`~Signer.unsign` but can also
validate the time. See the base docstring of the class for
the general behavior. If `return_timestamp` is set to `True`
the timestamp of the signature will be returned as naive
:class:`datetime.datetime` object in UTC.
"""
try:
result = Signer.unsign(self, value)
sig_error = None
except BadSignature as e:
sig_error = e
result = e.payload or b''
sep = want_bytes(self.sep)
# If there is no timestamp in the result there is something
# seriously wrong. In case there was a signature error, we raise
# that one directly, otherwise we have a weird situation in which
# we shouldn't have come except someone uses a time-based serializer
# on non-timestamp data, so catch that.
if not sep in result:
if sig_error:
raise sig_error
raise BadTimeSignature('timestamp missing', payload=result)
value, timestamp = result.rsplit(sep, 1)
try:
timestamp = bytes_to_int(base64_decode(timestamp))
except Exception:
timestamp = None
# Signature is *not* okay. Raise a proper error now that we have
# split the value and the timestamp.
if sig_error is not None:
raise BadTimeSignature(text_type(sig_error), payload=value,
date_signed=timestamp)
# Signature was okay but the timestamp is actually not there or
# malformed. Should not happen, but well. We handle it nonetheless
if timestamp is None:
raise BadTimeSignature('Malformed timestamp', payload=value)
# Check timestamp is not older than max_age
if max_age is not None:
age = self.get_timestamp() - timestamp
if age > max_age:
raise SignatureExpired(
'Signature age %s > %s seconds' % (age, max_age),
payload=value,
date_signed=self.timestamp_to_datetime(timestamp))
if return_timestamp:
return value, self.timestamp_to_datetime(timestamp)
return value
|
def unsign(self, value, max_age=None, return_timestamp=False):
"""Works like the regular :meth:`~Signer.unsign` but can also
validate the time. See the base docstring of the class for
the general behavior. If `return_timestamp` is set to `True`
the timestamp of the signature will be returned as naive
:class:`datetime.datetime` object in UTC.
"""
try:
result = Signer.unsign(self, value)
sig_error = None
except BadSignature as e:
sig_error = e
result = e.payload or b''
sep = want_bytes(self.sep)
# If there is no timestamp in the result there is something
# seriously wrong. In case there was a signature error, we raise
# that one directly, otherwise we have a weird situation in which
# we shouldn't have come except someone uses a time-based serializer
# on non-timestamp data, so catch that.
if not sep in result:
if sig_error:
raise sig_error
raise BadTimeSignature('timestamp missing', payload=result)
value, timestamp = result.rsplit(sep, 1)
try:
timestamp = bytes_to_int(base64_decode(timestamp))
except Exception:
timestamp = None
# Signature is *not* okay. Raise a proper error now that we have
# split the value and the timestamp.
if sig_error is not None:
raise BadTimeSignature(text_type(sig_error), payload=value,
date_signed=timestamp)
# Signature was okay but the timestamp is actually not there or
# malformed. Should not happen, but well. We handle it nonetheless
if timestamp is None:
raise BadTimeSignature('Malformed timestamp', payload=value)
# Check timestamp is not older than max_age
if max_age is not None:
age = self.get_timestamp() - timestamp
if age > max_age:
raise SignatureExpired(
'Signature age %s > %s seconds' % (age, max_age),
payload=value,
date_signed=self.timestamp_to_datetime(timestamp))
if return_timestamp:
return value, self.timestamp_to_datetime(timestamp)
return value
|
[
"Works",
"like",
"the",
"regular",
":",
"meth",
":",
"~Signer",
".",
"unsign",
"but",
"can",
"also",
"validate",
"the",
"time",
".",
"See",
"the",
"base",
"docstring",
"of",
"the",
"class",
"for",
"the",
"general",
"behavior",
".",
"If",
"return_timestamp",
"is",
"set",
"to",
"True",
"the",
"timestamp",
"of",
"the",
"signature",
"will",
"be",
"returned",
"as",
"naive",
":",
"class",
":",
"datetime",
".",
"datetime",
"object",
"in",
"UTC",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L414-L467
|
[
"def",
"unsign",
"(",
"self",
",",
"value",
",",
"max_age",
"=",
"None",
",",
"return_timestamp",
"=",
"False",
")",
":",
"try",
":",
"result",
"=",
"Signer",
".",
"unsign",
"(",
"self",
",",
"value",
")",
"sig_error",
"=",
"None",
"except",
"BadSignature",
"as",
"e",
":",
"sig_error",
"=",
"e",
"result",
"=",
"e",
".",
"payload",
"or",
"b''",
"sep",
"=",
"want_bytes",
"(",
"self",
".",
"sep",
")",
"# If there is no timestamp in the result there is something",
"# seriously wrong. In case there was a signature error, we raise",
"# that one directly, otherwise we have a weird situation in which",
"# we shouldn't have come except someone uses a time-based serializer",
"# on non-timestamp data, so catch that.",
"if",
"not",
"sep",
"in",
"result",
":",
"if",
"sig_error",
":",
"raise",
"sig_error",
"raise",
"BadTimeSignature",
"(",
"'timestamp missing'",
",",
"payload",
"=",
"result",
")",
"value",
",",
"timestamp",
"=",
"result",
".",
"rsplit",
"(",
"sep",
",",
"1",
")",
"try",
":",
"timestamp",
"=",
"bytes_to_int",
"(",
"base64_decode",
"(",
"timestamp",
")",
")",
"except",
"Exception",
":",
"timestamp",
"=",
"None",
"# Signature is *not* okay. Raise a proper error now that we have",
"# split the value and the timestamp.",
"if",
"sig_error",
"is",
"not",
"None",
":",
"raise",
"BadTimeSignature",
"(",
"text_type",
"(",
"sig_error",
")",
",",
"payload",
"=",
"value",
",",
"date_signed",
"=",
"timestamp",
")",
"# Signature was okay but the timestamp is actually not there or",
"# malformed. Should not happen, but well. We handle it nonetheless",
"if",
"timestamp",
"is",
"None",
":",
"raise",
"BadTimeSignature",
"(",
"'Malformed timestamp'",
",",
"payload",
"=",
"value",
")",
"# Check timestamp is not older than max_age",
"if",
"max_age",
"is",
"not",
"None",
":",
"age",
"=",
"self",
".",
"get_timestamp",
"(",
")",
"-",
"timestamp",
"if",
"age",
">",
"max_age",
":",
"raise",
"SignatureExpired",
"(",
"'Signature age %s > %s seconds'",
"%",
"(",
"age",
",",
"max_age",
")",
",",
"payload",
"=",
"value",
",",
"date_signed",
"=",
"self",
".",
"timestamp_to_datetime",
"(",
"timestamp",
")",
")",
"if",
"return_timestamp",
":",
"return",
"value",
",",
"self",
".",
"timestamp_to_datetime",
"(",
"timestamp",
")",
"return",
"value"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
TimestampSigner.validate
|
Just validates the given signed value. Returns `True` if the
signature exists and is valid, `False` otherwise.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def validate(self, signed_value, max_age=None):
"""Just validates the given signed value. Returns `True` if the
signature exists and is valid, `False` otherwise."""
try:
self.unsign(signed_value, max_age=max_age)
return True
except BadSignature:
return False
|
def validate(self, signed_value, max_age=None):
"""Just validates the given signed value. Returns `True` if the
signature exists and is valid, `False` otherwise."""
try:
self.unsign(signed_value, max_age=max_age)
return True
except BadSignature:
return False
|
[
"Just",
"validates",
"the",
"given",
"signed",
"value",
".",
"Returns",
"True",
"if",
"the",
"signature",
"exists",
"and",
"is",
"valid",
"False",
"otherwise",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L469-L476
|
[
"def",
"validate",
"(",
"self",
",",
"signed_value",
",",
"max_age",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"unsign",
"(",
"signed_value",
",",
"max_age",
"=",
"max_age",
")",
"return",
"True",
"except",
"BadSignature",
":",
"return",
"False"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Serializer.load_payload
|
Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def load_payload(self, payload, serializer=None):
"""Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based.
"""
if serializer is None:
serializer = self.serializer
is_text = self.is_text_serializer
else:
is_text = is_text_serializer(serializer)
try:
if is_text:
payload = payload.decode('utf-8')
return serializer.loads(payload)
except Exception as e:
raise BadPayload('Could not load the payload because an '
'exception occurred on unserializing the data',
original_error=e)
|
def load_payload(self, payload, serializer=None):
"""Loads the encoded object. This function raises :class:`BadPayload`
if the payload is not valid. The `serializer` parameter can be used to
override the serializer stored on the class. The encoded payload is
always byte based.
"""
if serializer is None:
serializer = self.serializer
is_text = self.is_text_serializer
else:
is_text = is_text_serializer(serializer)
try:
if is_text:
payload = payload.decode('utf-8')
return serializer.loads(payload)
except Exception as e:
raise BadPayload('Could not load the payload because an '
'exception occurred on unserializing the data',
original_error=e)
|
[
"Loads",
"the",
"encoded",
"object",
".",
"This",
"function",
"raises",
":",
"class",
":",
"BadPayload",
"if",
"the",
"payload",
"is",
"not",
"valid",
".",
"The",
"serializer",
"parameter",
"can",
"be",
"used",
"to",
"override",
"the",
"serializer",
"stored",
"on",
"the",
"class",
".",
"The",
"encoded",
"payload",
"is",
"always",
"byte",
"based",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L525-L543
|
[
"def",
"load_payload",
"(",
"self",
",",
"payload",
",",
"serializer",
"=",
"None",
")",
":",
"if",
"serializer",
"is",
"None",
":",
"serializer",
"=",
"self",
".",
"serializer",
"is_text",
"=",
"self",
".",
"is_text_serializer",
"else",
":",
"is_text",
"=",
"is_text_serializer",
"(",
"serializer",
")",
"try",
":",
"if",
"is_text",
":",
"payload",
"=",
"payload",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"serializer",
".",
"loads",
"(",
"payload",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"BadPayload",
"(",
"'Could not load the payload because an '",
"'exception occurred on unserializing the data'",
",",
"original_error",
"=",
"e",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Serializer.make_signer
|
A method that creates a new instance of the signer to be used.
The default implementation uses the :class:`Signer` baseclass.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def make_signer(self, salt=None):
"""A method that creates a new instance of the signer to be used.
The default implementation uses the :class:`Signer` baseclass.
"""
if salt is None:
salt = self.salt
return self.signer(self.secret_key, salt=salt, **self.signer_kwargs)
|
def make_signer(self, salt=None):
"""A method that creates a new instance of the signer to be used.
The default implementation uses the :class:`Signer` baseclass.
"""
if salt is None:
salt = self.salt
return self.signer(self.secret_key, salt=salt, **self.signer_kwargs)
|
[
"A",
"method",
"that",
"creates",
"a",
"new",
"instance",
"of",
"the",
"signer",
"to",
"be",
"used",
".",
"The",
"default",
"implementation",
"uses",
"the",
":",
"class",
":",
"Signer",
"baseclass",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L552-L558
|
[
"def",
"make_signer",
"(",
"self",
",",
"salt",
"=",
"None",
")",
":",
"if",
"salt",
"is",
"None",
":",
"salt",
"=",
"self",
".",
"salt",
"return",
"self",
".",
"signer",
"(",
"self",
".",
"secret_key",
",",
"salt",
"=",
"salt",
",",
"*",
"*",
"self",
".",
"signer_kwargs",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Serializer.dumps
|
Returns a signed string serialized with the internal serializer.
The return value can be either a byte or unicode string depending
on the format of the internal serializer.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def dumps(self, obj, salt=None):
"""Returns a signed string serialized with the internal serializer.
The return value can be either a byte or unicode string depending
on the format of the internal serializer.
"""
payload = want_bytes(self.dump_payload(obj))
rv = self.make_signer(salt).sign(payload)
if self.is_text_serializer:
rv = rv.decode('utf-8')
return rv
|
def dumps(self, obj, salt=None):
"""Returns a signed string serialized with the internal serializer.
The return value can be either a byte or unicode string depending
on the format of the internal serializer.
"""
payload = want_bytes(self.dump_payload(obj))
rv = self.make_signer(salt).sign(payload)
if self.is_text_serializer:
rv = rv.decode('utf-8')
return rv
|
[
"Returns",
"a",
"signed",
"string",
"serialized",
"with",
"the",
"internal",
"serializer",
".",
"The",
"return",
"value",
"can",
"be",
"either",
"a",
"byte",
"or",
"unicode",
"string",
"depending",
"on",
"the",
"format",
"of",
"the",
"internal",
"serializer",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L560-L569
|
[
"def",
"dumps",
"(",
"self",
",",
"obj",
",",
"salt",
"=",
"None",
")",
":",
"payload",
"=",
"want_bytes",
"(",
"self",
".",
"dump_payload",
"(",
"obj",
")",
")",
"rv",
"=",
"self",
".",
"make_signer",
"(",
"salt",
")",
".",
"sign",
"(",
"payload",
")",
"if",
"self",
".",
"is_text_serializer",
":",
"rv",
"=",
"rv",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"rv"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Serializer.dump
|
Like :meth:`dumps` but dumps into a file. The file handle has
to be compatible with what the internal serializer expects.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def dump(self, obj, f, salt=None):
"""Like :meth:`dumps` but dumps into a file. The file handle has
to be compatible with what the internal serializer expects.
"""
f.write(self.dumps(obj, salt))
|
def dump(self, obj, f, salt=None):
"""Like :meth:`dumps` but dumps into a file. The file handle has
to be compatible with what the internal serializer expects.
"""
f.write(self.dumps(obj, salt))
|
[
"Like",
":",
"meth",
":",
"dumps",
"but",
"dumps",
"into",
"a",
"file",
".",
"The",
"file",
"handle",
"has",
"to",
"be",
"compatible",
"with",
"what",
"the",
"internal",
"serializer",
"expects",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L571-L575
|
[
"def",
"dump",
"(",
"self",
",",
"obj",
",",
"f",
",",
"salt",
"=",
"None",
")",
":",
"f",
".",
"write",
"(",
"self",
".",
"dumps",
"(",
"obj",
",",
"salt",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Serializer.loads
|
Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
signature validation fails.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def loads(self, s, salt=None):
"""Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
signature validation fails.
"""
s = want_bytes(s)
return self.load_payload(self.make_signer(salt).unsign(s))
|
def loads(self, s, salt=None):
"""Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
signature validation fails.
"""
s = want_bytes(s)
return self.load_payload(self.make_signer(salt).unsign(s))
|
[
"Reverse",
"of",
":",
"meth",
":",
"dumps",
"raises",
":",
"exc",
":",
"BadSignature",
"if",
"the",
"signature",
"validation",
"fails",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L577-L582
|
[
"def",
"loads",
"(",
"self",
",",
"s",
",",
"salt",
"=",
"None",
")",
":",
"s",
"=",
"want_bytes",
"(",
"s",
")",
"return",
"self",
".",
"load_payload",
"(",
"self",
".",
"make_signer",
"(",
"salt",
")",
".",
"unsign",
"(",
"s",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Serializer._loads_unsafe_impl
|
Lowlevel helper function to implement :meth:`loads_unsafe` in
serializer subclasses.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def _loads_unsafe_impl(self, s, salt, load_kwargs=None,
load_payload_kwargs=None):
"""Lowlevel helper function to implement :meth:`loads_unsafe` in
serializer subclasses.
"""
try:
return True, self.loads(s, salt=salt, **(load_kwargs or {}))
except BadSignature as e:
if e.payload is None:
return False, None
try:
return False, self.load_payload(e.payload,
**(load_payload_kwargs or {}))
except BadPayload:
return False, None
|
def _loads_unsafe_impl(self, s, salt, load_kwargs=None,
load_payload_kwargs=None):
"""Lowlevel helper function to implement :meth:`loads_unsafe` in
serializer subclasses.
"""
try:
return True, self.loads(s, salt=salt, **(load_kwargs or {}))
except BadSignature as e:
if e.payload is None:
return False, None
try:
return False, self.load_payload(e.payload,
**(load_payload_kwargs or {}))
except BadPayload:
return False, None
|
[
"Lowlevel",
"helper",
"function",
"to",
"implement",
":",
"meth",
":",
"loads_unsafe",
"in",
"serializer",
"subclasses",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L603-L617
|
[
"def",
"_loads_unsafe_impl",
"(",
"self",
",",
"s",
",",
"salt",
",",
"load_kwargs",
"=",
"None",
",",
"load_payload_kwargs",
"=",
"None",
")",
":",
"try",
":",
"return",
"True",
",",
"self",
".",
"loads",
"(",
"s",
",",
"salt",
"=",
"salt",
",",
"*",
"*",
"(",
"load_kwargs",
"or",
"{",
"}",
")",
")",
"except",
"BadSignature",
"as",
"e",
":",
"if",
"e",
".",
"payload",
"is",
"None",
":",
"return",
"False",
",",
"None",
"try",
":",
"return",
"False",
",",
"self",
".",
"load_payload",
"(",
"e",
".",
"payload",
",",
"*",
"*",
"(",
"load_payload_kwargs",
"or",
"{",
"}",
")",
")",
"except",
"BadPayload",
":",
"return",
"False",
",",
"None"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Serializer.load_unsafe
|
Like :meth:`loads_unsafe` but loads from a file.
.. versionadded:: 0.15
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def load_unsafe(self, f, *args, **kwargs):
"""Like :meth:`loads_unsafe` but loads from a file.
.. versionadded:: 0.15
"""
return self.loads_unsafe(f.read(), *args, **kwargs)
|
def load_unsafe(self, f, *args, **kwargs):
"""Like :meth:`loads_unsafe` but loads from a file.
.. versionadded:: 0.15
"""
return self.loads_unsafe(f.read(), *args, **kwargs)
|
[
"Like",
":",
"meth",
":",
"loads_unsafe",
"but",
"loads",
"from",
"a",
"file",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L619-L624
|
[
"def",
"load_unsafe",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"loads_unsafe",
"(",
"f",
".",
"read",
"(",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
TimedSerializer.loads
|
Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
signature validation fails. If a `max_age` is provided it will
ensure the signature is not older than that time in seconds. In
case the signature is outdated, :exc:`SignatureExpired` is raised
which is a subclass of :exc:`BadSignature`. All arguments are
forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
"""Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
signature validation fails. If a `max_age` is provided it will
ensure the signature is not older than that time in seconds. In
case the signature is outdated, :exc:`SignatureExpired` is raised
which is a subclass of :exc:`BadSignature`. All arguments are
forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
"""
base64d, timestamp = self.make_signer(salt) \
.unsign(s, max_age, return_timestamp=True)
payload = self.load_payload(base64d)
if return_timestamp:
return payload, timestamp
return payload
|
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
"""Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
signature validation fails. If a `max_age` is provided it will
ensure the signature is not older than that time in seconds. In
case the signature is outdated, :exc:`SignatureExpired` is raised
which is a subclass of :exc:`BadSignature`. All arguments are
forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
"""
base64d, timestamp = self.make_signer(salt) \
.unsign(s, max_age, return_timestamp=True)
payload = self.load_payload(base64d)
if return_timestamp:
return payload, timestamp
return payload
|
[
"Reverse",
"of",
":",
"meth",
":",
"dumps",
"raises",
":",
"exc",
":",
"BadSignature",
"if",
"the",
"signature",
"validation",
"fails",
".",
"If",
"a",
"max_age",
"is",
"provided",
"it",
"will",
"ensure",
"the",
"signature",
"is",
"not",
"older",
"than",
"that",
"time",
"in",
"seconds",
".",
"In",
"case",
"the",
"signature",
"is",
"outdated",
":",
"exc",
":",
"SignatureExpired",
"is",
"raised",
"which",
"is",
"a",
"subclass",
"of",
":",
"exc",
":",
"BadSignature",
".",
"All",
"arguments",
"are",
"forwarded",
"to",
"the",
"signer",
"s",
":",
"meth",
":",
"~TimestampSigner",
".",
"unsign",
"method",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L634-L647
|
[
"def",
"loads",
"(",
"self",
",",
"s",
",",
"max_age",
"=",
"None",
",",
"return_timestamp",
"=",
"False",
",",
"salt",
"=",
"None",
")",
":",
"base64d",
",",
"timestamp",
"=",
"self",
".",
"make_signer",
"(",
"salt",
")",
".",
"unsign",
"(",
"s",
",",
"max_age",
",",
"return_timestamp",
"=",
"True",
")",
"payload",
"=",
"self",
".",
"load_payload",
"(",
"base64d",
")",
"if",
"return_timestamp",
":",
"return",
"payload",
",",
"timestamp",
"return",
"payload"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
JSONWebSignatureSerializer.dumps
|
Like :meth:`~Serializer.dumps` but creates a JSON Web Signature. It
also allows for specifying additional fields to be included in the JWS
Header.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def dumps(self, obj, salt=None, header_fields=None):
"""Like :meth:`~Serializer.dumps` but creates a JSON Web Signature. It
also allows for specifying additional fields to be included in the JWS
Header.
"""
header = self.make_header(header_fields)
signer = self.make_signer(salt, self.algorithm)
return signer.sign(self.dump_payload(header, obj))
|
def dumps(self, obj, salt=None, header_fields=None):
"""Like :meth:`~Serializer.dumps` but creates a JSON Web Signature. It
also allows for specifying additional fields to be included in the JWS
Header.
"""
header = self.make_header(header_fields)
signer = self.make_signer(salt, self.algorithm)
return signer.sign(self.dump_payload(header, obj))
|
[
"Like",
":",
"meth",
":",
"~Serializer",
".",
"dumps",
"but",
"creates",
"a",
"JSON",
"Web",
"Signature",
".",
"It",
"also",
"allows",
"for",
"specifying",
"additional",
"fields",
"to",
"be",
"included",
"in",
"the",
"JWS",
"Header",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L735-L742
|
[
"def",
"dumps",
"(",
"self",
",",
"obj",
",",
"salt",
"=",
"None",
",",
"header_fields",
"=",
"None",
")",
":",
"header",
"=",
"self",
".",
"make_header",
"(",
"header_fields",
")",
"signer",
"=",
"self",
".",
"make_signer",
"(",
"salt",
",",
"self",
".",
"algorithm",
")",
"return",
"signer",
".",
"sign",
"(",
"self",
".",
"dump_payload",
"(",
"header",
",",
"obj",
")",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
JSONWebSignatureSerializer.loads
|
Reverse of :meth:`dumps`. If requested via `return_header` it will
return a tuple of payload and header.
|
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
|
def loads(self, s, salt=None, return_header=False):
"""Reverse of :meth:`dumps`. If requested via `return_header` it will
return a tuple of payload and header.
"""
payload, header = self.load_payload(
self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
return_header=True)
if header.get('alg') != self.algorithm_name:
raise BadHeader('Algorithm mismatch', header=header,
payload=payload)
if return_header:
return payload, header
return payload
|
def loads(self, s, salt=None, return_header=False):
"""Reverse of :meth:`dumps`. If requested via `return_header` it will
return a tuple of payload and header.
"""
payload, header = self.load_payload(
self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
return_header=True)
if header.get('alg') != self.algorithm_name:
raise BadHeader('Algorithm mismatch', header=header,
payload=payload)
if return_header:
return payload, header
return payload
|
[
"Reverse",
"of",
":",
"meth",
":",
"dumps",
".",
"If",
"requested",
"via",
"return_header",
"it",
"will",
"return",
"a",
"tuple",
"of",
"payload",
"and",
"header",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L744-L756
|
[
"def",
"loads",
"(",
"self",
",",
"s",
",",
"salt",
"=",
"None",
",",
"return_header",
"=",
"False",
")",
":",
"payload",
",",
"header",
"=",
"self",
".",
"load_payload",
"(",
"self",
".",
"make_signer",
"(",
"salt",
",",
"self",
".",
"algorithm",
")",
".",
"unsign",
"(",
"want_bytes",
"(",
"s",
")",
")",
",",
"return_header",
"=",
"True",
")",
"if",
"header",
".",
"get",
"(",
"'alg'",
")",
"!=",
"self",
".",
"algorithm_name",
":",
"raise",
"BadHeader",
"(",
"'Algorithm mismatch'",
",",
"header",
"=",
"header",
",",
"payload",
"=",
"payload",
")",
"if",
"return_header",
":",
"return",
"payload",
",",
"header",
"return",
"payload"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
server_error
|
JSON-RPC server error.
:param request_id: JSON-RPC request id
:type request_id: int or str or None
:param error: server error
:type error: Exception
|
service_factory/errors.py
|
def server_error(request_id, error):
"""JSON-RPC server error.
:param request_id: JSON-RPC request id
:type request_id: int or str or None
:param error: server error
:type error: Exception
"""
response = {
'jsonrpc': '2.0',
'id': request_id,
'error': {
'code': -32000,
'message': 'Server error',
'data': repr(error),
},
}
raise ServiceException(500, dumps(response))
|
def server_error(request_id, error):
"""JSON-RPC server error.
:param request_id: JSON-RPC request id
:type request_id: int or str or None
:param error: server error
:type error: Exception
"""
response = {
'jsonrpc': '2.0',
'id': request_id,
'error': {
'code': -32000,
'message': 'Server error',
'data': repr(error),
},
}
raise ServiceException(500, dumps(response))
|
[
"JSON",
"-",
"RPC",
"server",
"error",
"."
] |
proofit404/service-factory
|
python
|
https://github.com/proofit404/service-factory/blob/a09d4e097e5599244564a2a7f0611e58efb4156a/service_factory/errors.py#L72-L91
|
[
"def",
"server_error",
"(",
"request_id",
",",
"error",
")",
":",
"response",
"=",
"{",
"'jsonrpc'",
":",
"'2.0'",
",",
"'id'",
":",
"request_id",
",",
"'error'",
":",
"{",
"'code'",
":",
"-",
"32000",
",",
"'message'",
":",
"'Server error'",
",",
"'data'",
":",
"repr",
"(",
"error",
")",
",",
"}",
",",
"}",
"raise",
"ServiceException",
"(",
"500",
",",
"dumps",
"(",
"response",
")",
")"
] |
a09d4e097e5599244564a2a7f0611e58efb4156a
|
test
|
findall
|
Find all files under 'dir' and return the list of full filenames
(relative to 'dir').
|
capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py
|
def findall(dir = os.curdir):
"""Find all files under 'dir' and return the list of full filenames
(relative to 'dir').
"""
all_files = []
for base, dirs, files in os.walk(dir, followlinks=True):
if base==os.curdir or base.startswith(os.curdir+os.sep):
base = base[2:]
if base:
files = [os.path.join(base, f) for f in files]
all_files.extend(filter(os.path.isfile, files))
return all_files
|
def findall(dir = os.curdir):
"""Find all files under 'dir' and return the list of full filenames
(relative to 'dir').
"""
all_files = []
for base, dirs, files in os.walk(dir, followlinks=True):
if base==os.curdir or base.startswith(os.curdir+os.sep):
base = base[2:]
if base:
files = [os.path.join(base, f) for f in files]
all_files.extend(filter(os.path.isfile, files))
return all_files
|
[
"Find",
"all",
"files",
"under",
"dir",
"and",
"return",
"the",
"list",
"of",
"full",
"filenames",
"(",
"relative",
"to",
"dir",
")",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py#L136-L147
|
[
"def",
"findall",
"(",
"dir",
"=",
"os",
".",
"curdir",
")",
":",
"all_files",
"=",
"[",
"]",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir",
",",
"followlinks",
"=",
"True",
")",
":",
"if",
"base",
"==",
"os",
".",
"curdir",
"or",
"base",
".",
"startswith",
"(",
"os",
".",
"curdir",
"+",
"os",
".",
"sep",
")",
":",
"base",
"=",
"base",
"[",
"2",
":",
"]",
"if",
"base",
":",
"files",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"f",
")",
"for",
"f",
"in",
"files",
"]",
"all_files",
".",
"extend",
"(",
"filter",
"(",
"os",
".",
"path",
".",
"isfile",
",",
"files",
")",
")",
"return",
"all_files"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
PackageFinder.find
|
Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style)
path; it will be converted to the appropriate local path syntax.
'exclude' is a sequence of package names to exclude; '*' can be used
as a wildcard in the names, such that 'foo.*' will exclude all
subpackages of 'foo' (but not 'foo' itself).
'include' is a sequence of package names to include. If it's
specified, only the named packages will be included. If it's not
specified, all found packages will be included. 'include' can contain
shell style wildcard patterns just like 'exclude'.
The list of included packages is built up first and then any
explicitly excluded packages are removed from it.
|
capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py
|
def find(cls, where='.', exclude=(), include=('*',)):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style)
path; it will be converted to the appropriate local path syntax.
'exclude' is a sequence of package names to exclude; '*' can be used
as a wildcard in the names, such that 'foo.*' will exclude all
subpackages of 'foo' (but not 'foo' itself).
'include' is a sequence of package names to include. If it's
specified, only the named packages will be included. If it's not
specified, all found packages will be included. 'include' can contain
shell style wildcard patterns just like 'exclude'.
The list of included packages is built up first and then any
explicitly excluded packages are removed from it.
"""
out = cls._find_packages_iter(convert_path(where))
out = cls.require_parents(out)
includes = cls._build_filter(*include)
excludes = cls._build_filter('ez_setup', '*__pycache__', *exclude)
out = filter(includes, out)
out = filterfalse(excludes, out)
return list(out)
|
def find(cls, where='.', exclude=(), include=('*',)):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style)
path; it will be converted to the appropriate local path syntax.
'exclude' is a sequence of package names to exclude; '*' can be used
as a wildcard in the names, such that 'foo.*' will exclude all
subpackages of 'foo' (but not 'foo' itself).
'include' is a sequence of package names to include. If it's
specified, only the named packages will be included. If it's not
specified, all found packages will be included. 'include' can contain
shell style wildcard patterns just like 'exclude'.
The list of included packages is built up first and then any
explicitly excluded packages are removed from it.
"""
out = cls._find_packages_iter(convert_path(where))
out = cls.require_parents(out)
includes = cls._build_filter(*include)
excludes = cls._build_filter('ez_setup', '*__pycache__', *exclude)
out = filter(includes, out)
out = filterfalse(excludes, out)
return list(out)
|
[
"Return",
"a",
"list",
"all",
"Python",
"packages",
"found",
"within",
"directory",
"where"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py#L34-L57
|
[
"def",
"find",
"(",
"cls",
",",
"where",
"=",
"'.'",
",",
"exclude",
"=",
"(",
")",
",",
"include",
"=",
"(",
"'*'",
",",
")",
")",
":",
"out",
"=",
"cls",
".",
"_find_packages_iter",
"(",
"convert_path",
"(",
"where",
")",
")",
"out",
"=",
"cls",
".",
"require_parents",
"(",
"out",
")",
"includes",
"=",
"cls",
".",
"_build_filter",
"(",
"*",
"include",
")",
"excludes",
"=",
"cls",
".",
"_build_filter",
"(",
"'ez_setup'",
",",
"'*__pycache__'",
",",
"*",
"exclude",
")",
"out",
"=",
"filter",
"(",
"includes",
",",
"out",
")",
"out",
"=",
"filterfalse",
"(",
"excludes",
",",
"out",
")",
"return",
"list",
"(",
"out",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
PackageFinder.require_parents
|
Exclude any apparent package that apparently doesn't include its
parent.
For example, exclude 'foo.bar' if 'foo' is not present.
|
capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py
|
def require_parents(packages):
"""
Exclude any apparent package that apparently doesn't include its
parent.
For example, exclude 'foo.bar' if 'foo' is not present.
"""
found = []
for pkg in packages:
base, sep, child = pkg.rpartition('.')
if base and base not in found:
continue
found.append(pkg)
yield pkg
|
def require_parents(packages):
"""
Exclude any apparent package that apparently doesn't include its
parent.
For example, exclude 'foo.bar' if 'foo' is not present.
"""
found = []
for pkg in packages:
base, sep, child = pkg.rpartition('.')
if base and base not in found:
continue
found.append(pkg)
yield pkg
|
[
"Exclude",
"any",
"apparent",
"package",
"that",
"apparently",
"doesn",
"t",
"include",
"its",
"parent",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py#L60-L73
|
[
"def",
"require_parents",
"(",
"packages",
")",
":",
"found",
"=",
"[",
"]",
"for",
"pkg",
"in",
"packages",
":",
"base",
",",
"sep",
",",
"child",
"=",
"pkg",
".",
"rpartition",
"(",
"'.'",
")",
"if",
"base",
"and",
"base",
"not",
"in",
"found",
":",
"continue",
"found",
".",
"append",
"(",
"pkg",
")",
"yield",
"pkg"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
PackageFinder._all_dirs
|
Return all dirs in base_path, relative to base_path
|
capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py
|
def _all_dirs(base_path):
"""
Return all dirs in base_path, relative to base_path
"""
for root, dirs, files in os.walk(base_path, followlinks=True):
for dir in dirs:
yield os.path.relpath(os.path.join(root, dir), base_path)
|
def _all_dirs(base_path):
"""
Return all dirs in base_path, relative to base_path
"""
for root, dirs, files in os.walk(base_path, followlinks=True):
for dir in dirs:
yield os.path.relpath(os.path.join(root, dir), base_path)
|
[
"Return",
"all",
"dirs",
"in",
"base_path",
"relative",
"to",
"base_path"
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py#L76-L82
|
[
"def",
"_all_dirs",
"(",
"base_path",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"base_path",
",",
"followlinks",
"=",
"True",
")",
":",
"for",
"dir",
"in",
"dirs",
":",
"yield",
"os",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"dir",
")",
",",
"base_path",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
Serializer.prepare_response
|
Verify our vary headers match and construct a real urllib3
HTTPResponse object.
|
capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/cachecontrol/serialize.py
|
def prepare_response(self, request, cached):
"""Verify our vary headers match and construct a real urllib3
HTTPResponse object.
"""
# Special case the '*' Vary value as it means we cannot actually
# determine if the cached response is suitable for this request.
if "*" in cached.get("vary", {}):
return
# Ensure that the Vary headers for the cached response match our
# request
for header, value in cached.get("vary", {}).items():
if request.headers.get(header, None) != value:
return
body_raw = cached["response"].pop("body")
try:
body = io.BytesIO(body_raw)
except TypeError:
# This can happen if cachecontrol serialized to v1 format (pickle)
# using Python 2. A Python 2 str(byte string) will be unpickled as
# a Python 3 str (unicode string), which will cause the above to
# fail with:
#
# TypeError: 'str' does not support the buffer interface
body = io.BytesIO(body_raw.encode('utf8'))
return HTTPResponse(
body=body,
preload_content=False,
**cached["response"]
)
|
def prepare_response(self, request, cached):
"""Verify our vary headers match and construct a real urllib3
HTTPResponse object.
"""
# Special case the '*' Vary value as it means we cannot actually
# determine if the cached response is suitable for this request.
if "*" in cached.get("vary", {}):
return
# Ensure that the Vary headers for the cached response match our
# request
for header, value in cached.get("vary", {}).items():
if request.headers.get(header, None) != value:
return
body_raw = cached["response"].pop("body")
try:
body = io.BytesIO(body_raw)
except TypeError:
# This can happen if cachecontrol serialized to v1 format (pickle)
# using Python 2. A Python 2 str(byte string) will be unpickled as
# a Python 3 str (unicode string), which will cause the above to
# fail with:
#
# TypeError: 'str' does not support the buffer interface
body = io.BytesIO(body_raw.encode('utf8'))
return HTTPResponse(
body=body,
preload_content=False,
**cached["response"]
)
|
[
"Verify",
"our",
"vary",
"headers",
"match",
"and",
"construct",
"a",
"real",
"urllib3",
"HTTPResponse",
"object",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/cachecontrol/serialize.py#L114-L146
|
[
"def",
"prepare_response",
"(",
"self",
",",
"request",
",",
"cached",
")",
":",
"# Special case the '*' Vary value as it means we cannot actually",
"# determine if the cached response is suitable for this request.",
"if",
"\"*\"",
"in",
"cached",
".",
"get",
"(",
"\"vary\"",
",",
"{",
"}",
")",
":",
"return",
"# Ensure that the Vary headers for the cached response match our",
"# request",
"for",
"header",
",",
"value",
"in",
"cached",
".",
"get",
"(",
"\"vary\"",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"if",
"request",
".",
"headers",
".",
"get",
"(",
"header",
",",
"None",
")",
"!=",
"value",
":",
"return",
"body_raw",
"=",
"cached",
"[",
"\"response\"",
"]",
".",
"pop",
"(",
"\"body\"",
")",
"try",
":",
"body",
"=",
"io",
".",
"BytesIO",
"(",
"body_raw",
")",
"except",
"TypeError",
":",
"# This can happen if cachecontrol serialized to v1 format (pickle)",
"# using Python 2. A Python 2 str(byte string) will be unpickled as",
"# a Python 3 str (unicode string), which will cause the above to",
"# fail with:",
"#",
"# TypeError: 'str' does not support the buffer interface",
"body",
"=",
"io",
".",
"BytesIO",
"(",
"body_raw",
".",
"encode",
"(",
"'utf8'",
")",
")",
"return",
"HTTPResponse",
"(",
"body",
"=",
"body",
",",
"preload_content",
"=",
"False",
",",
"*",
"*",
"cached",
"[",
"\"response\"",
"]",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
test
|
keygen
|
Generate a public/private key pair.
|
capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py
|
def keygen(get_keyring=get_keyring):
"""Generate a public/private key pair."""
WheelKeys, keyring = get_keyring()
ed25519ll = signatures.get_ed25519ll()
wk = WheelKeys().load()
keypair = ed25519ll.crypto_sign_keypair()
vk = native(urlsafe_b64encode(keypair.vk))
sk = native(urlsafe_b64encode(keypair.sk))
kr = keyring.get_keyring()
kr.set_password("wheel", vk, sk)
sys.stdout.write("Created Ed25519 keypair with vk={0}\n".format(vk))
if isinstance(kr, keyring.backends.file.BaseKeyring):
sys.stdout.write("in {0}\n".format(kr.file_path))
else:
sys.stdout.write("in %r\n" % kr.__class__)
sk2 = kr.get_password('wheel', vk)
if sk2 != sk:
raise WheelError("Keyring is broken. Could not retrieve secret key.")
sys.stdout.write("Trusting {0} to sign and verify all packages.\n".format(vk))
wk.add_signer('+', vk)
wk.trust('+', vk)
wk.save()
|
def keygen(get_keyring=get_keyring):
"""Generate a public/private key pair."""
WheelKeys, keyring = get_keyring()
ed25519ll = signatures.get_ed25519ll()
wk = WheelKeys().load()
keypair = ed25519ll.crypto_sign_keypair()
vk = native(urlsafe_b64encode(keypair.vk))
sk = native(urlsafe_b64encode(keypair.sk))
kr = keyring.get_keyring()
kr.set_password("wheel", vk, sk)
sys.stdout.write("Created Ed25519 keypair with vk={0}\n".format(vk))
if isinstance(kr, keyring.backends.file.BaseKeyring):
sys.stdout.write("in {0}\n".format(kr.file_path))
else:
sys.stdout.write("in %r\n" % kr.__class__)
sk2 = kr.get_password('wheel', vk)
if sk2 != sk:
raise WheelError("Keyring is broken. Could not retrieve secret key.")
sys.stdout.write("Trusting {0} to sign and verify all packages.\n".format(vk))
wk.add_signer('+', vk)
wk.trust('+', vk)
wk.save()
|
[
"Generate",
"a",
"public",
"/",
"private",
"key",
"pair",
"."
] |
AkihikoITOH/capybara
|
python
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py#L36-L62
|
[
"def",
"keygen",
"(",
"get_keyring",
"=",
"get_keyring",
")",
":",
"WheelKeys",
",",
"keyring",
"=",
"get_keyring",
"(",
")",
"ed25519ll",
"=",
"signatures",
".",
"get_ed25519ll",
"(",
")",
"wk",
"=",
"WheelKeys",
"(",
")",
".",
"load",
"(",
")",
"keypair",
"=",
"ed25519ll",
".",
"crypto_sign_keypair",
"(",
")",
"vk",
"=",
"native",
"(",
"urlsafe_b64encode",
"(",
"keypair",
".",
"vk",
")",
")",
"sk",
"=",
"native",
"(",
"urlsafe_b64encode",
"(",
"keypair",
".",
"sk",
")",
")",
"kr",
"=",
"keyring",
".",
"get_keyring",
"(",
")",
"kr",
".",
"set_password",
"(",
"\"wheel\"",
",",
"vk",
",",
"sk",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Created Ed25519 keypair with vk={0}\\n\"",
".",
"format",
"(",
"vk",
")",
")",
"if",
"isinstance",
"(",
"kr",
",",
"keyring",
".",
"backends",
".",
"file",
".",
"BaseKeyring",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"in {0}\\n\"",
".",
"format",
"(",
"kr",
".",
"file_path",
")",
")",
"else",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"in %r\\n\"",
"%",
"kr",
".",
"__class__",
")",
"sk2",
"=",
"kr",
".",
"get_password",
"(",
"'wheel'",
",",
"vk",
")",
"if",
"sk2",
"!=",
"sk",
":",
"raise",
"WheelError",
"(",
"\"Keyring is broken. Could not retrieve secret key.\"",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Trusting {0} to sign and verify all packages.\\n\"",
".",
"format",
"(",
"vk",
")",
")",
"wk",
".",
"add_signer",
"(",
"'+'",
",",
"vk",
")",
"wk",
".",
"trust",
"(",
"'+'",
",",
"vk",
")",
"wk",
".",
"save",
"(",
")"
] |
e86c2173ea386654f4ae061148e8fbe3f25e715c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.