Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
get_exe_prefixes | (exe_filename) | Get exe->egg path translations for a given .exe file | Get exe->egg path translations for a given .exe file | def get_exe_prefixes(exe_filename):
"""Get exe->egg path translations for a given .exe file"""
prefixes = [
('PURELIB/', ''),
('PLATLIB/pywin32_system32', ''),
('PLATLIB/', ''),
('SCRIPTS/', 'EGG-INFO/scripts/'),
('DATA/lib/site-packages', ''),
]
z = zipfile.ZipF... | [
"def",
"get_exe_prefixes",
"(",
"exe_filename",
")",
":",
"prefixes",
"=",
"[",
"(",
"'PURELIB/'",
",",
"''",
")",
",",
"(",
"'PLATLIB/pywin32_system32'",
",",
"''",
")",
",",
"(",
"'PLATLIB/'",
",",
"''",
")",
",",
"(",
"'SCRIPTS/'",
",",
"'EGG-INFO/scrip... | [
1512,
0
] | [
1548,
19
] | python | en | ['en', 'en', 'en'] | True |
_first_line_re | () |
Return a regular expression based on first_line_re suitable for matching
strings.
|
Return a regular expression based on first_line_re suitable for matching
strings.
| def _first_line_re():
"""
Return a regular expression based on first_line_re suitable for matching
strings.
"""
if isinstance(first_line_re.pattern, str):
return first_line_re
# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
return re.compile(first_line_re.pattern.d... | [
"def",
"_first_line_re",
"(",
")",
":",
"if",
"isinstance",
"(",
"first_line_re",
".",
"pattern",
",",
"str",
")",
":",
"return",
"first_line_re",
"# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.",
"return",
"re",
".",
"compile",
"(",
"first_line_re",
... | [
1685,
0
] | [
1694,
53
] | python | en | ['en', 'error', 'th'] | False |
update_dist_caches | (dist_path, fix_zipimporter_caches) |
Fix any globally cached `dist_path` related data
`dist_path` should be a path of a newly installed egg distribution (zipped
or unzipped).
sys.path_importer_cache contains finder objects that have been cached when
importing data from the original distribution. Any such finders need to be
clear... |
Fix any globally cached `dist_path` related data | def update_dist_caches(dist_path, fix_zipimporter_caches):
"""
Fix any globally cached `dist_path` related data
`dist_path` should be a path of a newly installed egg distribution (zipped
or unzipped).
sys.path_importer_cache contains finder objects that have been cached when
importing data fro... | [
"def",
"update_dist_caches",
"(",
"dist_path",
",",
"fix_zipimporter_caches",
")",
":",
"# There are several other known sources of stale zipimport.zipimporter",
"# instances that we do not clear here, but might if ever given a reason to",
"# do so:",
"# * Global setuptools pkg_resources.worki... | [
1705,
0
] | [
1784,
67
] | python | en | ['en', 'error', 'th'] | False |
_collect_zipimporter_cache_entries | (normalized_path, cache) |
Return zipimporter cache entry keys related to a given normalized path.
Alternative path spellings (e.g. those using different character case or
those using alternative path separators) related to the same path are
included. Any sub-path entries are included as well, i.e. those
corresponding to zi... |
Return zipimporter cache entry keys related to a given normalized path. | def _collect_zipimporter_cache_entries(normalized_path, cache):
"""
Return zipimporter cache entry keys related to a given normalized path.
Alternative path spellings (e.g. those using different character case or
those using alternative path separators) related to the same path are
included. Any su... | [
"def",
"_collect_zipimporter_cache_entries",
"(",
"normalized_path",
",",
"cache",
")",
":",
"result",
"=",
"[",
"]",
"prefix_len",
"=",
"len",
"(",
"normalized_path",
")",
"for",
"p",
"in",
"cache",
":",
"np",
"=",
"normalize_path",
"(",
"p",
")",
"if",
"... | [
1787,
0
] | [
1804,
17
] | python | en | ['en', 'error', 'th'] | False |
_update_zipimporter_cache | (normalized_path, cache, updater=None) |
Update zipimporter cache data for a given normalized path.
Any sub-path entries are processed as well, i.e. those corresponding to zip
archives embedded in other zip archives.
Given updater is a callable taking a cache entry key and the original entry
(after already removing the entry from the ca... |
Update zipimporter cache data for a given normalized path. | def _update_zipimporter_cache(normalized_path, cache, updater=None):
"""
Update zipimporter cache data for a given normalized path.
Any sub-path entries are processed as well, i.e. those corresponding to zip
archives embedded in other zip archives.
Given updater is a callable taking a cache entry ... | [
"def",
"_update_zipimporter_cache",
"(",
"normalized_path",
",",
"cache",
",",
"updater",
"=",
"None",
")",
":",
"for",
"p",
"in",
"_collect_zipimporter_cache_entries",
"(",
"normalized_path",
",",
"cache",
")",
":",
"# N.B. pypy's custom zipimport._zip_directory_cache im... | [
1807,
0
] | [
1836,
32
] | python | en | ['en', 'error', 'th'] | False |
is_python | (text, filename='<string>') | Is this string a valid Python script? | Is this string a valid Python script? | def is_python(text, filename='<string>'):
"Is this string a valid Python script?"
try:
compile(text, filename, 'exec')
except (SyntaxError, TypeError):
return False
else:
return True | [
"def",
"is_python",
"(",
"text",
",",
"filename",
"=",
"'<string>'",
")",
":",
"try",
":",
"compile",
"(",
"text",
",",
"filename",
",",
"'exec'",
")",
"except",
"(",
"SyntaxError",
",",
"TypeError",
")",
":",
"return",
"False",
"else",
":",
"return",
... | [
1884,
0
] | [
1891,
19
] | python | en | ['en', 'en', 'en'] | True |
is_sh | (executable) | Determine if the specified executable is a .sh (contains a #! line) | Determine if the specified executable is a .sh (contains a #! line) | def is_sh(executable):
"""Determine if the specified executable is a .sh (contains a #! line)"""
try:
with io.open(executable, encoding='latin-1') as fp:
magic = fp.read(2)
except (OSError, IOError):
return executable
return magic == '#!' | [
"def",
"is_sh",
"(",
"executable",
")",
":",
"try",
":",
"with",
"io",
".",
"open",
"(",
"executable",
",",
"encoding",
"=",
"'latin-1'",
")",
"as",
"fp",
":",
"magic",
"=",
"fp",
".",
"read",
"(",
"2",
")",
"except",
"(",
"OSError",
",",
"IOError"... | [
1894,
0
] | [
1901,
24
] | python | en | ['en', 'en', 'en'] | True |
nt_quote_arg | (arg) | Quote a command line argument according to Windows parsing rules | Quote a command line argument according to Windows parsing rules | def nt_quote_arg(arg):
"""Quote a command line argument according to Windows parsing rules"""
return subprocess.list2cmdline([arg]) | [
"def",
"nt_quote_arg",
"(",
"arg",
")",
":",
"return",
"subprocess",
".",
"list2cmdline",
"(",
"[",
"arg",
"]",
")"
] | [
1904,
0
] | [
1906,
41
] | python | en | ['en', 'en', 'en'] | True |
is_python_script | (script_text, filename) | Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
| Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
| def is_python_script(script_text, filename):
"""Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
"""
if filename.endswith('.py') or filename.endswith('.pyw'):
return True # extension says it's Python
if is_python(script_text, filename):
return True # it's syntac... | [
"def",
"is_python_script",
"(",
"script_text",
",",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'.pyw'",
")",
":",
"return",
"True",
"# extension says it's Python",
"if",
"is_python",
"("... | [
1909,
0
] | [
1920,
16
] | python | en | ['en', 'en', 'en'] | True |
get_win_launcher | (type) |
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
Returns the executable as a byte string.
|
Load the Windows launcher (executable) suitable for launching a script. | def get_win_launcher(type):
"""
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
Returns the executable as a byte string.
"""
launcher_fn = '%s.exe' % type
if is_64bit():
launcher_fn = launcher_fn.replace(".", "-64.")
... | [
"def",
"get_win_launcher",
"(",
"type",
")",
":",
"launcher_fn",
"=",
"'%s.exe'",
"%",
"type",
"if",
"is_64bit",
"(",
")",
":",
"launcher_fn",
"=",
"launcher_fn",
".",
"replace",
"(",
"\".\"",
",",
"\"-64.\"",
")",
"else",
":",
"launcher_fn",
"=",
"launche... | [
2247,
0
] | [
2260,
53
] | python | en | ['en', 'error', 'th'] | False |
easy_install._render_version | () |
Render the Setuptools version and installation details, then exit.
|
Render the Setuptools version and installation details, then exit.
| def _render_version():
"""
Render the Setuptools version and installation details, then exit.
"""
ver = '{}.{}'.format(*sys.version_info)
dist = get_distribution('setuptools')
tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})'
print(tmpl.format... | [
"def",
"_render_version",
"(",
")",
":",
"ver",
"=",
"'{}.{}'",
".",
"format",
"(",
"*",
"sys",
".",
"version_info",
")",
"dist",
"=",
"get_distribution",
"(",
"'setuptools'",
")",
"tmpl",
"=",
"'setuptools {dist.version} from {dist.location} (Python {ver})'",
"prin... | [
235,
4
] | [
243,
26
] | python | en | ['en', 'error', 'th'] | False |
easy_install._fix_install_dir_for_user_site | (self) |
Fix the install_dir if "--user" was used.
|
Fix the install_dir if "--user" was used.
| def _fix_install_dir_for_user_site(self):
"""
Fix the install_dir if "--user" was used.
"""
if not self.user or not site.ENABLE_USER_SITE:
return
self.create_home_path()
if self.install_userbase is None:
msg = "User base directory is not specified... | [
"def",
"_fix_install_dir_for_user_site",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"user",
"or",
"not",
"site",
".",
"ENABLE_USER_SITE",
":",
"return",
"self",
".",
"create_home_path",
"(",
")",
"if",
"self",
".",
"install_userbase",
"is",
"None",
":"... | [
372,
4
] | [
385,
39
] | python | en | ['en', 'error', 'th'] | False |
easy_install.expand_basedirs | (self) | Calls `os.path.expanduser` on install_base, install_platbase and
root. | Calls `os.path.expanduser` on install_base, install_platbase and
root. | def expand_basedirs(self):
"""Calls `os.path.expanduser` on install_base, install_platbase and
root."""
self._expand_attrs(['install_base', 'install_platbase', 'root']) | [
"def",
"expand_basedirs",
"(",
"self",
")",
":",
"self",
".",
"_expand_attrs",
"(",
"[",
"'install_base'",
",",
"'install_platbase'",
",",
"'root'",
"]",
")"
] | [
396,
4
] | [
399,
72
] | python | en | ['en', 'en', 'en'] | True |
easy_install.expand_dirs | (self) | Calls `os.path.expanduser` on install dirs. | Calls `os.path.expanduser` on install dirs. | def expand_dirs(self):
"""Calls `os.path.expanduser` on install dirs."""
dirs = [
'install_purelib',
'install_platlib',
'install_lib',
'install_headers',
'install_scripts',
'install_data',
]
self._expand_attrs(dirs) | [
"def",
"expand_dirs",
"(",
"self",
")",
":",
"dirs",
"=",
"[",
"'install_purelib'",
",",
"'install_platlib'",
",",
"'install_lib'",
",",
"'install_headers'",
",",
"'install_scripts'",
",",
"'install_data'",
",",
"]",
"self",
".",
"_expand_attrs",
"(",
"dirs",
")... | [
401,
4
] | [
411,
32
] | python | en | ['en', 'en', 'en'] | True |
easy_install.pseudo_tempname | (self) | Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo.
| Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo.
| def pseudo_tempname(self):
"""Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo.
"""
try:
pid = os.getpid()
except Exception:
... | [
"def",
"pseudo_tempname",
"(",
"self",
")",
":",
"try",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"except",
"Exception",
":",
"pid",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"sys",
".",
"maxsize",
")",
"return",
"os",
".",
"path",
".",
... | [
442,
4
] | [
451,
75
] | python | en | ['en', 'en', 'en'] | True |
easy_install.check_site_dir | (self) | Verify that self.install_dir is .pth-capable dir, if needed | Verify that self.install_dir is .pth-capable dir, if needed | def check_site_dir(self):
"""Verify that self.install_dir is .pth-capable dir, if needed"""
instdir = normalize_path(self.install_dir)
pth_file = os.path.join(instdir, 'easy-install.pth')
if not os.path.exists(instdir):
try:
os.makedirs(instdir)
... | [
"def",
"check_site_dir",
"(",
"self",
")",
":",
"instdir",
"=",
"normalize_path",
"(",
"self",
".",
"install_dir",
")",
"pth_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"instdir",
",",
"'easy-install.pth'",
")",
"if",
"not",
"os",
".",
"path",
".",
... | [
456,
4
] | [
499,
34
] | python | en | ['en', 'en', 'en'] | True |
easy_install.check_pth_processing | (self) | Empirically verify whether .pth files are supported in inst. dir | Empirically verify whether .pth files are supported in inst. dir | def check_pth_processing(self):
"""Empirically verify whether .pth files are supported in inst. dir"""
instdir = self.install_dir
log.info("Checking .pth file support in %s", instdir)
pth_file = self.pseudo_tempname() + ".pth"
ok_file = pth_file + '.ok'
ok_exists = os.pat... | [
"def",
"check_pth_processing",
"(",
"self",
")",
":",
"instdir",
"=",
"self",
".",
"install_dir",
"log",
".",
"info",
"(",
"\"Checking .pth file support in %s\"",
",",
"instdir",
")",
"pth_file",
"=",
"self",
".",
"pseudo_tempname",
"(",
")",
"+",
"\".pth\"",
... | [
546,
4
] | [
603,
20
] | python | en | ['en', 'en', 'en'] | True |
easy_install.install_egg_scripts | (self, dist) | Write all the scripts for `dist`, unless scripts are excluded | Write all the scripts for `dist`, unless scripts are excluded | def install_egg_scripts(self, dist):
"""Write all the scripts for `dist`, unless scripts are excluded"""
if not self.exclude_scripts and dist.metadata_isdir('scripts'):
for script_name in dist.metadata_listdir('scripts'):
if dist.metadata_isdir('scripts/' + script_name):
... | [
"def",
"install_egg_scripts",
"(",
"self",
",",
"dist",
")",
":",
"if",
"not",
"self",
".",
"exclude_scripts",
"and",
"dist",
".",
"metadata_isdir",
"(",
"'scripts'",
")",
":",
"for",
"script_name",
"in",
"dist",
".",
"metadata_listdir",
"(",
"'scripts'",
")... | [
605,
4
] | [
617,
42
] | python | en | ['en', 'en', 'en'] | True |
easy_install.select_scheme | (self, name) | Sets the install directories by applying the install schemes. | Sets the install directories by applying the install schemes. | def select_scheme(self, name):
"""Sets the install directories by applying the install schemes."""
# it's the caller's problem if they supply a bad name!
scheme = INSTALL_SCHEMES[name]
for key in SCHEME_KEYS:
attrname = 'install_' + key
if getattr(self, attrname) ... | [
"def",
"select_scheme",
"(",
"self",
",",
"name",
")",
":",
"# it's the caller's problem if they supply a bad name!",
"scheme",
"=",
"INSTALL_SCHEMES",
"[",
"name",
"]",
"for",
"key",
"in",
"SCHEME_KEYS",
":",
"attrname",
"=",
"'install_'",
"+",
"key",
"if",
"geta... | [
723,
4
] | [
730,
52
] | python | en | ['en', 'en', 'en'] | True |
easy_install.install_script | (self, dist, script_name, script_text, dev_path=None) | Generate a legacy script wrapper and install it | Generate a legacy script wrapper and install it | def install_script(self, dist, script_name, script_text, dev_path=None):
"""Generate a legacy script wrapper and install it"""
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
if is_script:
body = self._load_template(dev_path) % locals... | [
"def",
"install_script",
"(",
"self",
",",
"dist",
",",
"script_name",
",",
"script_text",
",",
"dev_path",
"=",
"None",
")",
":",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"is_script",
"=",
"is_python_script",
"(",
"script_tex... | [
809,
4
] | [
817,
67
] | python | en | ['en', 'en', 'en'] | True |
easy_install._load_template | (dev_path) |
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
|
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
| def _load_template(dev_path):
"""
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
"""
# See https://github.com/pypa/setuptools/issues/134 for info
# on script file naming and downstream issues with SVR4
... | [
"def",
"_load_template",
"(",
"dev_path",
")",
":",
"# See https://github.com/pypa/setuptools/issues/134 for info",
"# on script file naming and downstream issues with SVR4",
"name",
"=",
"'script.tmpl'",
"if",
"dev_path",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"'.tmp... | [
820,
4
] | [
832,
40
] | python | en | ['en', 'error', 'th'] | False |
easy_install.write_script | (self, script_name, contents, mode="t", blockers=()) | Write an executable file to the scripts directory | Write an executable file to the scripts directory | def write_script(self, script_name, contents, mode="t", blockers=()):
"""Write an executable file to the scripts directory"""
self.delete_blockers( # clean up old .py/.pyw w/o a script
[os.path.join(self.script_dir, x) for x in blockers]
)
log.info("Installing %s script to %... | [
"def",
"write_script",
"(",
"self",
",",
"script_name",
",",
"contents",
",",
"mode",
"=",
"\"t\"",
",",
"blockers",
"=",
"(",
")",
")",
":",
"self",
".",
"delete_blockers",
"(",
"# clean up old .py/.pyw w/o a script",
"[",
"os",
".",
"path",
".",
"join",
... | [
834,
4
] | [
852,
35
] | python | en | ['en', 'en', 'en'] | True |
easy_install.exe_to_egg | (self, dist_filename, egg_tmp) | Extract a bdist_wininst to the directories an egg would use | Extract a bdist_wininst to the directories an egg would use | def exe_to_egg(self, dist_filename, egg_tmp):
"""Extract a bdist_wininst to the directories an egg would use"""
# Check for .pth file and set up prefix translations
prefixes = get_exe_prefixes(dist_filename)
to_compile = []
native_libs = []
top_level = {}
def pro... | [
"def",
"exe_to_egg",
"(",
"self",
",",
"dist_filename",
",",
"egg_tmp",
")",
":",
"# Check for .pth file and set up prefix translations",
"prefixes",
"=",
"get_exe_prefixes",
"(",
"dist_filename",
")",
"to_compile",
"=",
"[",
"]",
"native_libs",
"=",
"[",
"]",
"top_... | [
1005,
4
] | [
1056,
29
] | python | en | ['en', 'en', 'en'] | True |
easy_install.installation_report | (self, req, dist, what="Installed") | Helpful installation message for display to package users | Helpful installation message for display to package users | def installation_report(self, req, dist, what="Installed"):
"""Helpful installation message for display to package users"""
msg = "\n%(what)s %(eggloc)s%(extras)s"
if self.multi_version and not self.no_report:
msg += '\n' + self.__mv_warning
if self.install_dir not in map... | [
"def",
"installation_report",
"(",
"self",
",",
"req",
",",
"dist",
",",
"what",
"=",
"\"Installed\"",
")",
":",
"msg",
"=",
"\"\\n%(what)s %(eggloc)s%(extras)s\"",
"if",
"self",
".",
"multi_version",
"and",
"not",
"self",
".",
"no_report",
":",
"msg",
"+=",
... | [
1104,
4
] | [
1116,
29
] | python | en | ['en', 'en', 'en'] | True |
easy_install._set_fetcher_options | (self, base) |
When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well.
|
When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well.
| def _set_fetcher_options(self, base):
"""
When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well.
... | [
"def",
"_set_fetcher_options",
"(",
"self",
",",
"base",
")",
":",
"# find the fetch options from easy_install and write them out",
"# to the setup.cfg file.",
"ei_opts",
"=",
"self",
".",
"distribution",
".",
"get_option_dict",
"(",
"'easy_install'",
")",
".",
"copy",
"(... | [
1180,
4
] | [
1201,
50
] | python | en | ['en', 'error', 'th'] | False |
easy_install.create_home_path | (self) | Create directories under ~. | Create directories under ~. | def create_home_path(self):
"""Create directories under ~."""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for name, path in six.iteritems(self.config_vars):
if path.startswith(home) and not os.path.isdir(path):
self.debug_... | [
"def",
"create_home_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"user",
":",
"return",
"home",
"=",
"convert_path",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
")",
"for",
"name",
",",
"path",
"in",
"six",
".",
"iteritem... | [
1315,
4
] | [
1323,
40
] | python | de | ['de', 'de', 'en'] | True |
PthDistributions.save | (self) | Write changed .pth file back to disk | Write changed .pth file back to disk | def save(self):
"""Write changed .pth file back to disk"""
if not self.dirty:
return
rel_paths = list(map(self.make_relative, self.paths))
if rel_paths:
log.debug("Saving %s", self.filename)
lines = self._wrap_lines(rel_paths)
data = '\n'.... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"dirty",
":",
"return",
"rel_paths",
"=",
"list",
"(",
"map",
"(",
"self",
".",
"make_relative",
",",
"self",
".",
"paths",
")",
")",
"if",
"rel_paths",
":",
"log",
".",
"debug",
"(",
... | [
1596,
4
] | [
1616,
26
] | python | en | ['en', 'en', 'en'] | True |
PthDistributions.add | (self, dist) | Add `dist` to the distribution map | Add `dist` to the distribution map | def add(self, dist):
"""Add `dist` to the distribution map"""
new_path = (
dist.location not in self.paths and (
dist.location not in self.sitedirs or
# account for '.' being in PYTHONPATH
dist.location == os.getcwd()
)
)
... | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"new_path",
"=",
"(",
"dist",
".",
"location",
"not",
"in",
"self",
".",
"paths",
"and",
"(",
"dist",
".",
"location",
"not",
"in",
"self",
".",
"sitedirs",
"or",
"# account for '.' being in PYTHONPATH",
... | [
1622,
4
] | [
1634,
35
] | python | en | ['en', 'en', 'en'] | True |
PthDistributions.remove | (self, dist) | Remove `dist` from the distribution map | Remove `dist` from the distribution map | def remove(self, dist):
"""Remove `dist` from the distribution map"""
while dist.location in self.paths:
self.paths.remove(dist.location)
self.dirty = True
Environment.remove(self, dist) | [
"def",
"remove",
"(",
"self",
",",
"dist",
")",
":",
"while",
"dist",
".",
"location",
"in",
"self",
".",
"paths",
":",
"self",
".",
"paths",
".",
"remove",
"(",
"dist",
".",
"location",
")",
"self",
".",
"dirty",
"=",
"True",
"Environment",
".",
"... | [
1636,
4
] | [
1641,
38
] | python | en | ['en', 'en', 'en'] | True |
CommandSpec.best | (cls) |
Choose the best CommandSpec class based on environmental conditions.
|
Choose the best CommandSpec class based on environmental conditions.
| def best(cls):
"""
Choose the best CommandSpec class based on environmental conditions.
"""
return cls | [
"def",
"best",
"(",
"cls",
")",
":",
"return",
"cls"
] | [
1949,
4
] | [
1953,
18
] | python | en | ['en', 'error', 'th'] | False |
CommandSpec.from_param | (cls, param) |
Construct a CommandSpec from a parameter to build_scripts, which may
be None.
|
Construct a CommandSpec from a parameter to build_scripts, which may
be None.
| def from_param(cls, param):
"""
Construct a CommandSpec from a parameter to build_scripts, which may
be None.
"""
if isinstance(param, cls):
return param
if isinstance(param, list):
return cls(param)
if param is None:
return cls... | [
"def",
"from_param",
"(",
"cls",
",",
"param",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"cls",
")",
":",
"return",
"param",
"if",
"isinstance",
"(",
"param",
",",
"list",
")",
":",
"return",
"cls",
"(",
"param",
")",
"if",
"param",
"is",
"N... | [
1961,
4
] | [
1973,
37
] | python | en | ['en', 'error', 'th'] | False |
CommandSpec.from_string | (cls, string) |
Construct a command spec from a simple string representing a command
line parseable by shlex.split.
|
Construct a command spec from a simple string representing a command
line parseable by shlex.split.
| def from_string(cls, string):
"""
Construct a command spec from a simple string representing a command
line parseable by shlex.split.
"""
items = shlex.split(string, **cls.split_args)
return cls(items) | [
"def",
"from_string",
"(",
"cls",
",",
"string",
")",
":",
"items",
"=",
"shlex",
".",
"split",
"(",
"string",
",",
"*",
"*",
"cls",
".",
"split_args",
")",
"return",
"cls",
"(",
"items",
")"
] | [
1980,
4
] | [
1986,
25
] | python | en | ['en', 'error', 'th'] | False |
CommandSpec._extract_options | (orig_script) |
Extract any options from the first line of the script.
|
Extract any options from the first line of the script.
| def _extract_options(orig_script):
"""
Extract any options from the first line of the script.
"""
first = (orig_script + '\n').splitlines()[0]
match = _first_line_re().match(first)
options = match.group(1) or '' if match else ''
return options.strip() | [
"def",
"_extract_options",
"(",
"orig_script",
")",
":",
"first",
"=",
"(",
"orig_script",
"+",
"'\\n'",
")",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"match",
"=",
"_first_line_re",
"(",
")",
".",
"match",
"(",
"first",
")",
"options",
"=",
"match"... | [
1995,
4
] | [
2002,
30
] | python | en | ['en', 'error', 'th'] | False |
ScriptWriter.get_args | (cls, dist, header=None) |
Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points.
|
Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points.
| def get_args(cls, dist, header=None):
"""
Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points.
"""
if header is None:
header = cls.get_header()
spec = str(dist.as_requirement())
for type_ in 'console',... | [
"def",
"get_args",
"(",
"cls",
",",
"dist",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"None",
":",
"header",
"=",
"cls",
".",
"get_header",
"(",
")",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"for",
... | [
2091,
4
] | [
2106,
29
] | python | en | ['en', 'error', 'th'] | False |
ScriptWriter._ensure_safe_name | (name) |
Prevent paths in *_scripts entry point names.
|
Prevent paths in *_scripts entry point names.
| def _ensure_safe_name(name):
"""
Prevent paths in *_scripts entry point names.
"""
has_path_sep = re.search(r'[\\/]', name)
if has_path_sep:
raise ValueError("Path separators not allowed in script names") | [
"def",
"_ensure_safe_name",
"(",
"name",
")",
":",
"has_path_sep",
"=",
"re",
".",
"search",
"(",
"r'[\\\\/]'",
",",
"name",
")",
"if",
"has_path_sep",
":",
"raise",
"ValueError",
"(",
"\"Path separators not allowed in script names\"",
")"
] | [
2109,
4
] | [
2115,
75
] | python | en | ['en', 'error', 'th'] | False |
ScriptWriter.best | (cls) |
Select the best ScriptWriter for this environment.
|
Select the best ScriptWriter for this environment.
| def best(cls):
"""
Select the best ScriptWriter for this environment.
"""
if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
return WindowsScriptWriter.best()
else:
return cls | [
"def",
"best",
"(",
"cls",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"or",
"(",
"os",
".",
"name",
"==",
"'java'",
"and",
"os",
".",
"_name",
"==",
"'nt'",
")",
":",
"return",
"WindowsScriptWriter",
".",
"best",
"(",
")",
"else",
":"... | [
2124,
4
] | [
2131,
22
] | python | en | ['en', 'error', 'th'] | False |
ScriptWriter.get_header | (cls, script_text="", executable=None) | Create a #! line, getting options (if any) from script_text | Create a #! line, getting options (if any) from script_text | def get_header(cls, script_text="", executable=None):
"""Create a #! line, getting options (if any) from script_text"""
cmd = cls.command_spec_class.best().from_param(executable)
cmd.install_options(script_text)
return cmd.as_header() | [
"def",
"get_header",
"(",
"cls",
",",
"script_text",
"=",
"\"\"",
",",
"executable",
"=",
"None",
")",
":",
"cmd",
"=",
"cls",
".",
"command_spec_class",
".",
"best",
"(",
")",
".",
"from_param",
"(",
"executable",
")",
"cmd",
".",
"install_options",
"("... | [
2139,
4
] | [
2143,
30
] | python | en | ['en', 'en', 'en'] | True |
WindowsScriptWriter.best | (cls) |
Select the best ScriptWriter suitable for Windows
|
Select the best ScriptWriter suitable for Windows
| def best(cls):
"""
Select the best ScriptWriter suitable for Windows
"""
writer_lookup = dict(
executable=WindowsExecutableLauncherWriter,
natural=cls,
)
# for compatibility, use the executable launcher by default
launcher = os.environ.get(... | [
"def",
"best",
"(",
"cls",
")",
":",
"writer_lookup",
"=",
"dict",
"(",
"executable",
"=",
"WindowsExecutableLauncherWriter",
",",
"natural",
"=",
"cls",
",",
")",
"# for compatibility, use the executable launcher by default",
"launcher",
"=",
"os",
".",
"environ",
... | [
2156,
4
] | [
2166,
38
] | python | en | ['en', 'error', 'th'] | False |
WindowsScriptWriter._get_script_args | (cls, type_, name, header, script_text) | For Windows, add a .py extension | For Windows, add a .py extension | def _get_script_args(cls, type_, name, header, script_text):
"For Windows, add a .py extension"
ext = dict(console='.pya', gui='.pyw')[type_]
if ext not in os.environ['PATHEXT'].lower().split(';'):
msg = (
"{ext} not listed in PATHEXT; scripts will not be "
... | [
"def",
"_get_script_args",
"(",
"cls",
",",
"type_",
",",
"name",
",",
"header",
",",
"script_text",
")",
":",
"ext",
"=",
"dict",
"(",
"console",
"=",
"'.pya'",
",",
"gui",
"=",
"'.pyw'",
")",
"[",
"type_",
"]",
"if",
"ext",
"not",
"in",
"os",
"."... | [
2169,
4
] | [
2182,
61
] | python | en | ['en', 'en', 'en'] | True |
WindowsScriptWriter._adjust_header | (cls, type_, orig_header) |
Make sure 'pythonw' is used for gui and and 'python' is used for
console (regardless of what sys.executable is).
|
Make sure 'pythonw' is used for gui and and 'python' is used for
console (regardless of what sys.executable is).
| def _adjust_header(cls, type_, orig_header):
"""
Make sure 'pythonw' is used for gui and and 'python' is used for
console (regardless of what sys.executable is).
"""
pattern = 'pythonw.exe'
repl = 'python.exe'
if type_ == 'gui':
pattern, repl = repl, p... | [
"def",
"_adjust_header",
"(",
"cls",
",",
"type_",
",",
"orig_header",
")",
":",
"pattern",
"=",
"'pythonw.exe'",
"repl",
"=",
"'python.exe'",
"if",
"type_",
"==",
"'gui'",
":",
"pattern",
",",
"repl",
"=",
"repl",
",",
"pattern",
"pattern_ob",
"=",
"re",
... | [
2185,
4
] | [
2196,
73
] | python | en | ['en', 'error', 'th'] | False |
WindowsScriptWriter._use_header | (new_header) |
Should _adjust_header use the replaced header?
On non-windows systems, always use. On
Windows systems, only use the replaced header if it resolves
to an executable on the system.
|
Should _adjust_header use the replaced header? | def _use_header(new_header):
"""
Should _adjust_header use the replaced header?
On non-windows systems, always use. On
Windows systems, only use the replaced header if it resolves
to an executable on the system.
"""
clean_header = new_header[2:-1].strip('"')
... | [
"def",
"_use_header",
"(",
"new_header",
")",
":",
"clean_header",
"=",
"new_header",
"[",
"2",
":",
"-",
"1",
"]",
".",
"strip",
"(",
"'\"'",
")",
"return",
"sys",
".",
"platform",
"!=",
"'win32'",
"or",
"find_executable",
"(",
"clean_header",
")"
] | [
2199,
4
] | [
2208,
71
] | python | en | ['en', 'error', 'th'] | False |
WindowsExecutableLauncherWriter._get_script_args | (cls, type_, name, header, script_text) |
For Windows, add a .py extension and an .exe launcher
|
For Windows, add a .py extension and an .exe launcher
| def _get_script_args(cls, type_, name, header, script_text):
"""
For Windows, add a .py extension and an .exe launcher
"""
if type_ == 'gui':
launcher_type = 'gui'
ext = '-script.pyw'
old = ['.pyw']
else:
launcher_type = 'cli'
... | [
"def",
"_get_script_args",
"(",
"cls",
",",
"type_",
",",
"name",
",",
"header",
",",
"script_text",
")",
":",
"if",
"type_",
"==",
"'gui'",
":",
"launcher_type",
"=",
"'gui'",
"ext",
"=",
"'-script.pyw'",
"old",
"=",
"[",
"'.pyw'",
"]",
"else",
":",
"... | [
2213,
4
] | [
2239,
61
] | python | en | ['en', 'error', 'th'] | False |
MySQLOperations.get_geom_placeholder | (self, f, value) |
The placeholder here has to include MySQL's WKT constructor. Because
MySQL does not support spatial transformations, there is no need to
modify the placeholder based on the contents of the given value.
|
The placeholder here has to include MySQL's WKT constructor. Because
MySQL does not support spatial transformations, there is no need to
modify the placeholder based on the contents of the given value.
| def get_geom_placeholder(self, f, value):
"""
The placeholder here has to include MySQL's WKT constructor. Because
MySQL does not support spatial transformations, there is no need to
modify the placeholder based on the contents of the given value.
"""
if hasattr(value, '... | [
"def",
"get_geom_placeholder",
"(",
"self",
",",
"f",
",",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'expression'",
")",
":",
"placeholder",
"=",
"self",
".",
"get_expression_column",
"(",
"value",
")",
"else",
":",
"placeholder",
"=",
"'%s(%... | [
37,
4
] | [
47,
26
] | python | en | ['en', 'error', 'th'] | False |
setup_realm_internal_bots | (realm: Realm) | Create this realm's internal bots.
This function is idempotent; it does nothing for a bot that
already exists.
| Create this realm's internal bots. | def setup_realm_internal_bots(realm: Realm) -> None:
"""Create this realm's internal bots.
This function is idempotent; it does nothing for a bot that
already exists.
"""
internal_bots = [
(bot["name"], bot["email_template"] % (settings.INTERNAL_BOT_DOMAIN,))
for bot in settings.REA... | [
"def",
"setup_realm_internal_bots",
"(",
"realm",
":",
"Realm",
")",
"->",
"None",
":",
"internal_bots",
"=",
"[",
"(",
"bot",
"[",
"\"name\"",
"]",
",",
"bot",
"[",
"\"email_template\"",
"]",
"%",
"(",
"settings",
".",
"INTERNAL_BOT_DOMAIN",
",",
")",
")"... | [
30,
0
] | [
48,
18
] | python | en | ['en', 'en', 'en'] | True |
create_if_missing_realm_internal_bots | () | This checks if there is any realm internal bot missing.
If that is the case, it creates the missing realm internal bots.
| This checks if there is any realm internal bot missing. | def create_if_missing_realm_internal_bots() -> None:
"""This checks if there is any realm internal bot missing.
If that is the case, it creates the missing realm internal bots.
"""
if missing_any_realm_internal_bots():
for realm in Realm.objects.all():
setup_realm_internal_bots(real... | [
"def",
"create_if_missing_realm_internal_bots",
"(",
")",
"->",
"None",
":",
"if",
"missing_any_realm_internal_bots",
"(",
")",
":",
"for",
"realm",
"in",
"Realm",
".",
"objects",
".",
"all",
"(",
")",
":",
"setup_realm_internal_bots",
"(",
"realm",
")"
] | [
51,
0
] | [
58,
44
] | python | en | ['en', 'en', 'en'] | True |
NoModelTests.test_no_models | (self) | Test that it's possible to load an app with no models.py file. | Test that it's possible to load an app with no models.py file. | def test_no_models(self):
"""Test that it's possible to load an app with no models.py file."""
app_config = apps.get_app_config('no_models')
self.assertIsNone(app_config.models_module) | [
"def",
"test_no_models",
"(",
"self",
")",
":",
"app_config",
"=",
"apps",
".",
"get_app_config",
"(",
"'no_models'",
")",
"self",
".",
"assertIsNone",
"(",
"app_config",
".",
"models_module",
")"
] | [
6,
4
] | [
9,
51
] | python | en | ['en', 'en', 'en'] | True |
compatible_tags | () |
Return (pyver, abi, arch) tuples compatible with this Python.
|
Return (pyver, abi, arch) tuples compatible with this Python.
| def compatible_tags():
"""
Return (pyver, abi, arch) tuples compatible with this Python.
"""
versions = [VER_SUFFIX]
major = VER_SUFFIX[0]
for minor in range(sys.version_info[1] - 1, - 1, -1):
versions.append(''.join([major, str(minor)]))
abis = []
for suffix, _, _ in imp.get_su... | [
"def",
"compatible_tags",
"(",
")",
":",
"versions",
"=",
"[",
"VER_SUFFIX",
"]",
"major",
"=",
"VER_SUFFIX",
"[",
"0",
"]",
"for",
"minor",
"in",
"range",
"(",
"sys",
".",
"version_info",
"[",
"1",
"]",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")... | [
926,
0
] | [
985,
22
] | python | en | ['en', 'error', 'th'] | False |
Wheel.__init__ | (self, filename=None, sign=False, verify=False) |
Initialise an instance using a (valid) filename.
|
Initialise an instance using a (valid) filename.
| def __init__(self, filename=None, sign=False, verify=False):
"""
Initialise an instance using a (valid) filename.
"""
self.sign = sign
self.should_verify = verify
self.buildver = ''
self.pyver = [PYVER]
self.abi = ['none']
self.arch = ['any']
... | [
"def",
"__init__",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"sign",
"=",
"False",
",",
"verify",
"=",
"False",
")",
":",
"self",
".",
"sign",
"=",
"sign",
"self",
".",
"should_verify",
"=",
"verify",
"self",
".",
"buildver",
"=",
"''",
"self",... | [
143,
4
] | [
182,
49
] | python | en | ['en', 'error', 'th'] | False |
Wheel.filename | (self) |
Build and return a filename from the various components.
|
Build and return a filename from the various components.
| def filename(self):
"""
Build and return a filename from the various components.
"""
if self.buildver:
buildver = '-' + self.buildver
else:
buildver = ''
pyver = '.'.join(self.pyver)
abi = '.'.join(self.abi)
arch = '.'.join(self.arc... | [
"def",
"filename",
"(",
"self",
")",
":",
"if",
"self",
".",
"buildver",
":",
"buildver",
"=",
"'-'",
"+",
"self",
".",
"buildver",
"else",
":",
"buildver",
"=",
"''",
"pyver",
"=",
"'.'",
".",
"join",
"(",
"self",
".",
"pyver",
")",
"abi",
"=",
... | [
185,
4
] | [
199,
58
] | python | en | ['en', 'error', 'th'] | False |
Wheel.build | (self, paths, tags=None, wheel_version=None) |
Build a wheel from files in specified paths, and use any specified tags
when determining the name of the wheel.
|
Build a wheel from files in specified paths, and use any specified tags
when determining the name of the wheel.
| def build(self, paths, tags=None, wheel_version=None):
"""
Build a wheel from files in specified paths, and use any specified tags
when determining the name of the wheel.
"""
if tags is None:
tags = {}
libkey = list(filter(lambda o: o in paths, ('purelib', 'p... | [
"def",
"build",
"(",
"self",
",",
"paths",
",",
"tags",
"=",
"None",
",",
"wheel_version",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"{",
"}",
"libkey",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"o",
":",
"o",
"in",
... | [
331,
4
] | [
433,
23
] | python | en | ['en', 'error', 'th'] | False |
Wheel.skip_entry | (self, arcname) |
Determine whether an archive entry should be skipped when verifying
or installing.
|
Determine whether an archive entry should be skipped when verifying
or installing.
| def skip_entry(self, arcname):
"""
Determine whether an archive entry should be skipped when verifying
or installing.
"""
# The signature file won't be in RECORD,
# and we don't currently don't do anything with it
# We also skip directories, as they won't be in R... | [
"def",
"skip_entry",
"(",
"self",
",",
"arcname",
")",
":",
"# The signature file won't be in RECORD,",
"# and we don't currently don't do anything with it",
"# We also skip directories, as they won't be in RECORD",
"# either. See:",
"#",
"# https://github.com/pypa/wheel/issues/294",
"#... | [
435,
4
] | [
449,
53
] | python | en | ['en', 'error', 'th'] | False |
Wheel.install | (self, paths, maker, **kwargs) |
Install a wheel to the specified paths. If kwarg ``warner`` is
specified, it should be a callable, which will be called with two
tuples indicating the wheel version of this software and the wheel
version in the file, if there is a discrepancy in the versions.
This can be used to... |
Install a wheel to the specified paths. If kwarg ``warner`` is
specified, it should be a callable, which will be called with two
tuples indicating the wheel version of this software and the wheel
version in the file, if there is a discrepancy in the versions.
This can be used to... | def install(self, paths, maker, **kwargs):
"""
Install a wheel to the specified paths. If kwarg ``warner`` is
specified, it should be a callable, which will be called with two
tuples indicating the wheel version of this software and the wheel
version in the file, if there is a di... | [
"def",
"install",
"(",
"self",
",",
"paths",
",",
"maker",
",",
"*",
"*",
"kwargs",
")",
":",
"dry_run",
"=",
"maker",
".",
"dry_run",
"warner",
"=",
"kwargs",
".",
"get",
"(",
"'warner'",
")",
"lib_only",
"=",
"kwargs",
".",
"get",
"(",
"'lib_only'"... | [
451,
4
] | [
679,
38
] | python | en | ['en', 'error', 'th'] | False |
Wheel.is_compatible | (self) |
Determine if a wheel is compatible with the running system.
|
Determine if a wheel is compatible with the running system.
| def is_compatible(self):
"""
Determine if a wheel is compatible with the running system.
"""
return is_compatible(self) | [
"def",
"is_compatible",
"(",
"self",
")",
":",
"return",
"is_compatible",
"(",
"self",
")"
] | [
724,
4
] | [
728,
34
] | python | en | ['en', 'error', 'th'] | False |
Wheel.is_mountable | (self) |
Determine if a wheel is asserted as mountable by its metadata.
|
Determine if a wheel is asserted as mountable by its metadata.
| def is_mountable(self):
"""
Determine if a wheel is asserted as mountable by its metadata.
"""
return True | [
"def",
"is_mountable",
"(",
"self",
")",
":",
"return",
"True"
] | [
730,
4
] | [
734,
19
] | python | en | ['en', 'error', 'th'] | False |
Wheel.update | (self, modifier, dest_dir=None, **kwargs) |
Update the contents of a wheel in a generic way. The modifier should
be a callable which expects a dictionary argument: its keys are
archive-entry paths, and its values are absolute filesystem paths
where the contents the corresponding archive entries can be found. The
modifier ... |
Update the contents of a wheel in a generic way. The modifier should
be a callable which expects a dictionary argument: its keys are
archive-entry paths, and its values are absolute filesystem paths
where the contents the corresponding archive entries can be found. The
modifier ... | def update(self, modifier, dest_dir=None, **kwargs):
"""
Update the contents of a wheel in a generic way. The modifier should
be a callable which expects a dictionary argument: its keys are
archive-entry paths, and its values are absolute filesystem paths
where the contents the c... | [
"def",
"update",
"(",
"self",
",",
"modifier",
",",
"dest_dir",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"get_version",
"(",
"path_map",
",",
"info_dir",
")",
":",
"version",
"=",
"path",
"=",
"None",
"key",
"=",
"'%s/%s'",
"%",
"(",
... | [
825,
4
] | [
924,
23
] | python | en | ['en', 'error', 'th'] | False |
radial_frequency_linewidth | (
size_im=288,
radius_circle=80,
shift_x=0,
shift_y=0,
line_width=6,
frequency=7,
amplitude=18,
phase=0,
frequency2=0,
amplitude2=0,
phase2=0,
gapsize=0,
gapphase=0,
dash_numgaps=0,
dash_phase=0,
) |
Makes a (closed/ open/ dashed) contour defined by 2 sinusoidal components with equal linewidth
Args:
size_im (int): the size of the output image
radius_circle (float): size of the modulated circle
shift_x (float): shift the contour in x direction (relative to center, positive means... |
Makes a (closed/ open/ dashed) contour defined by 2 sinusoidal components with equal linewidth
Args:
size_im (int): the size of the output image
radius_circle (float): size of the modulated circle
shift_x (float): shift the contour in x direction (relative to center, positive means... | def radial_frequency_linewidth(
size_im=288,
radius_circle=80,
shift_x=0,
shift_y=0,
line_width=6,
frequency=7,
amplitude=18,
phase=0,
frequency2=0,
amplitude2=0,
phase2=0,
gapsize=0,
gapphase=0,
dash_numgaps=0,
dash_phase=0,
):
"""
Makes a (closed/ op... | [
"def",
"radial_frequency_linewidth",
"(",
"size_im",
"=",
"288",
",",
"radius_circle",
"=",
"80",
",",
"shift_x",
"=",
"0",
",",
"shift_y",
"=",
"0",
",",
"line_width",
"=",
"6",
",",
"frequency",
"=",
"7",
",",
"amplitude",
"=",
"18",
",",
"phase",
"=... | [
10,
0
] | [
87,
14
] | python | en | ['en', 'error', 'th'] | False |
overlay_contours | (im1, im2) |
add two images: necessary for two contours in the image
|
add two images: necessary for two contours in the image
| def overlay_contours(im1, im2):
"""
add two images: necessary for two contours in the image
"""
return np.logical_and(im1, im2) | [
"def",
"overlay_contours",
"(",
"im1",
",",
"im2",
")",
":",
"return",
"np",
".",
"logical_and",
"(",
"im1",
",",
"im2",
")"
] | [
90,
0
] | [
94,
35
] | python | en | ['en', 'error', 'th'] | False |
make_full_dataset | (top_dir, set_num, debug) |
generate and save the full data set for a specified variation
:param top_dir: where to save the images [string]
:param set_num: number that specifies the variation [one of: 17, 18, 19, 20, 21, 22, 23]
:param debug: generate only seven images [bool]
|
generate and save the full data set for a specified variation
:param top_dir: where to save the images [string]
:param set_num: number that specifies the variation [one of: 17, 18, 19, 20, 21, 22, 23]
:param debug: generate only seven images [bool]
| def make_full_dataset(top_dir, set_num, debug):
"""
generate and save the full data set for a specified variation
:param top_dir: where to save the images [string]
:param set_num: number that specifies the variation [one of: 17, 18, 19, 20, 21, 22, 23]
:param debug: generate only seven images [bool]... | [
"def",
"make_full_dataset",
"(",
"top_dir",
",",
"set_num",
",",
"debug",
")",
":",
"if",
"debug",
":",
"num_rep",
"=",
"2",
"# 2800 # equals 5600 images",
"else",
":",
"num_rep",
"=",
"2800",
"# equals to 5600 images",
"np",
".",
"random",
".",
"seed",
"(",
... | [
109,
0
] | [
280,
73
] | python | en | ['en', 'error', 'th'] | False |
DraftCreationTests.test_missing_timestamps | (self) | If a timestamp is not provided for a draft dict then it should be automatically
filled in. | If a timestamp is not provided for a draft dict then it should be automatically
filled in. | def test_missing_timestamps(self) -> None:
"""If a timestamp is not provided for a draft dict then it should be automatically
filled in."""
hamlet = self.example_user("hamlet")
visible_stream_name = self.get_streams(hamlet)[0]
visible_stream_id = self.get_stream_id(visible_stream... | [
"def",
"test_missing_timestamps",
"(",
"self",
")",
"->",
"None",
":",
"hamlet",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"visible_stream_name",
"=",
"self",
".",
"get_streams",
"(",
"hamlet",
")",
"[",
"0",
"]",
"visible_stream_id",
"=",
"s... | [
147,
4
] | [
176,
63
] | python | en | ['en', 'en', 'en'] | True |
DraftCreationTests.test_create_non_stream_draft_with_no_recipient | (self) | When "to" is an empty list, the type should become "" as well. | When "to" is an empty list, the type should become "" as well. | def test_create_non_stream_draft_with_no_recipient(self) -> None:
""" When "to" is an empty list, the type should become "" as well. """
draft_dicts = [
{
"type": "private",
"to": [],
"topic": "sync drafts",
"content": "Let's ad... | [
"def",
"test_create_non_stream_draft_with_no_recipient",
"(",
"self",
")",
"->",
"None",
":",
"draft_dicts",
"=",
"[",
"{",
"\"type\"",
":",
"\"private\"",
",",
"\"to\"",
":",
"[",
"]",
",",
"\"topic\"",
":",
"\"sync drafts\"",
",",
"\"content\"",
":",
"\"Let's ... | [
190,
4
] | [
224,
83
] | python | en | ['en', 'en', 'en'] | True |
test_order_line_products_are_unique | (user_api_client, resource_in_unit, product) | Test order validator enforces that order lines cannot contain duplicates of the same product | Test order validator enforces that order lines cannot contain duplicates of the same product | def test_order_line_products_are_unique(user_api_client, resource_in_unit, product):
"""Test order validator enforces that order lines cannot contain duplicates of the same product"""
reservation_data = build_reservation_data(resource_in_unit)
reservation_data['order'] = build_order_data(product, quantity=2... | [
"def",
"test_order_line_products_are_unique",
"(",
"user_api_client",
",",
"resource_in_unit",
",",
"product",
")",
":",
"reservation_data",
"=",
"build_reservation_data",
"(",
"resource_in_unit",
")",
"reservation_data",
"[",
"'order'",
"]",
"=",
"build_order_data",
"(",... | [
254,
0
] | [
260,
38
] | python | en | ['en', 'en', 'en'] | True |
test_order_line_product_quantity_limitation | (user_api_client, resource_in_unit, quantity, expected_status) | Test order validator order line quantity is within product max quantity limitation | Test order validator order line quantity is within product max quantity limitation | def test_order_line_product_quantity_limitation(user_api_client, resource_in_unit, quantity, expected_status):
"""Test order validator order line quantity is within product max quantity limitation"""
reservation_data = build_reservation_data(resource_in_unit)
product_with_quantity = ProductFactory(resources... | [
"def",
"test_order_line_product_quantity_limitation",
"(",
"user_api_client",
",",
"resource_in_unit",
",",
"quantity",
",",
"expected_status",
")",
":",
"reservation_data",
"=",
"build_reservation_data",
"(",
"resource_in_unit",
")",
"product_with_quantity",
"=",
"ProductFac... | [
268,
0
] | [
277,
65
] | python | en | ['en', 'en', 'en'] | True |
process_varaamo_libraries | () |
Find varaamo libraries' Units from the db,
ask their data from kirjastot.fi and
process resulting opening hours if found
into their Unit object
Asks the span of opening hours from get_time_range
TODO: Libraries in Helmet system with resources need more reliable identifier
:return: None
... |
Find varaamo libraries' Units from the db,
ask their data from kirjastot.fi and
process resulting opening hours if found
into their Unit object | def process_varaamo_libraries():
"""
Find varaamo libraries' Units from the db,
ask their data from kirjastot.fi and
process resulting opening hours if found
into their Unit object
Asks the span of opening hours from get_time_range
TODO: Libraries in Helmet system with resources need more ... | [
"def",
"process_varaamo_libraries",
"(",
")",
":",
"varaamo_units",
"=",
"Unit",
".",
"objects",
".",
"filter",
"(",
"identifiers__namespace",
"=",
"\"kirjastot.fi\"",
")",
".",
"exclude",
"(",
"resources__isnull",
"=",
"True",
")",
"start",
",",
"end",
"=",
"... | [
42,
0
] | [
76,
44
] | python | en | ['en', 'error', 'th'] | False |
get_helmet_timetables | () |
Old V2 API makes a return
:return:None
|
Old V2 API makes a return | def get_helmet_timetables():
"""
Old V2 API makes a return
:return:None
"""
url = "https://api.kirjastot.fi/v2/search/libraries?consortium=helmet&with=periods"
resp = requests.get(url)
assert resp.status_code == 200
data = resp.json() # ??
# data = [{'id': 'H53', 'periods': []}]
... | [
"def",
"get_helmet_timetables",
"(",
")",
":",
"url",
"=",
"\"https://api.kirjastot.fi/v2/search/libraries?consortium=helmet&with=periods\"",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"assert",
"resp",
".",
"status_code",
"==",
"200",
"data",
"=",
"resp",
... | [
80,
0
] | [
106,
39
] | python | en | ['en', 'error', 'th'] | False |
timetable_fetcher | (unit, start='2016-07-01', end='2016-12-31') |
Fetch periods using kirjastot.fi's new v3 API
v3 gives opening for each day with period id
it originated from, thus allowing creation of
unique periods
Data is requested first on Unit's kirjastot.fi id,
then helmet identificator from tprek
TODO: helmet consortium's id permanency check
... |
Fetch periods using kirjastot.fi's new v3 API | def timetable_fetcher(unit, start='2016-07-01', end='2016-12-31'):
"""
Fetch periods using kirjastot.fi's new v3 API
v3 gives opening for each day with period id
it originated from, thus allowing creation of
unique periods
Data is requested first on Unit's kirjastot.fi id,
then helmet iden... | [
"def",
"timetable_fetcher",
"(",
"unit",
",",
"start",
"=",
"'2016-07-01'",
",",
"end",
"=",
"'2016-12-31'",
")",
":",
"base",
"=",
"\"https://api.kirjastot.fi/v3/organisation\"",
"for",
"identificator",
"in",
"unit",
".",
"identifiers",
".",
"all",
"(",
")",
":... | [
159,
0
] | [
214,
16
] | python | en | ['en', 'error', 'th'] | False |
process_periods | (data, unit) |
Generate Period and Day objects into
given Unit from kirjastot.fi v3 API data
Each day in data has its own Period and Day object
resulting in as many Periods with one Day as there is
items in data
:param data: kirjastot.fi v3 API data form /organisation endpoint
:param unit: Unit
:ret... |
Generate Period and Day objects into
given Unit from kirjastot.fi v3 API data | def process_periods(data, unit):
"""
Generate Period and Day objects into
given Unit from kirjastot.fi v3 API data
Each day in data has its own Period and Day object
resulting in as many Periods with one Day as there is
items in data
:param data: kirjastot.fi v3 API data form /organisation... | [
"def",
"process_periods",
"(",
"data",
",",
"unit",
")",
":",
"periods",
"=",
"[",
"]",
"if",
"data",
"[",
"'total'",
"]",
"!=",
"1",
":",
"for",
"item",
"in",
"data",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'name'",
"]",
"[",
"'fi'",
"]",
... | [
217,
0
] | [
271,
31
] | python | en | ['en', 'error', 'th'] | False |
get_time_range | (start=None, back=1, forward=12) |
From a starting date from back and forward
by given amount and return start of both months
as dates
:param start: datetime.date
:param back: int
:param forward: int
:return: (datetime.date, datetime.date)
|
From a starting date from back and forward
by given amount and return start of both months
as dates | def get_time_range(start=None, back=1, forward=12):
"""
From a starting date from back and forward
by given amount and return start of both months
as dates
:param start: datetime.date
:param back: int
:param forward: int
:return: (datetime.date, datetime.date)
"""
base = delorea... | [
"def",
"get_time_range",
"(",
"start",
"=",
"None",
",",
"back",
"=",
"1",
",",
"forward",
"=",
"12",
")",
":",
"base",
"=",
"delorean",
".",
"Delorean",
"(",
"start",
")",
"start",
"=",
"base",
".",
"last_month",
"(",
"back",
")",
".",
"date",
"."... | [
274,
0
] | [
288,
21
] | python | en | ['en', 'error', 'th'] | False |
test_implementation | (mocker) | Test Abstract Base Class | Test Abstract Base Class | def test_implementation(mocker):
"""Test Abstract Base Class"""
mocker.patch.object(modules.ProjectModule, "__abstractmethods__", new_callable=set)
inst = modules.ProjectModule()
inst.config
inst.load()
inst.create()
inst.update()
inst.add([])
inst.remove([]) | [
"def",
"test_implementation",
"(",
"mocker",
")",
":",
"mocker",
".",
"patch",
".",
"object",
"(",
"modules",
".",
"ProjectModule",
",",
"\"__abstractmethods__\"",
",",
"new_callable",
"=",
"set",
")",
"inst",
"=",
"modules",
".",
"ProjectModule",
"(",
")",
... | [
117,
0
] | [
126,
19
] | python | en | ['en', 'en', 'en'] | True |
FileTests.test_unicode_uploadedfile_name | (self) |
Regression test for #8156: files with unicode names I can't quite figure
out the encoding situation between doctest and this file, but the actual
repr doesn't matter; it just shouldn't return a unicode object.
|
Regression test for #8156: files with unicode names I can't quite figure
out the encoding situation between doctest and this file, but the actual
repr doesn't matter; it just shouldn't return a unicode object.
| def test_unicode_uploadedfile_name(self):
"""
Regression test for #8156: files with unicode names I can't quite figure
out the encoding situation between doctest and this file, but the actual
repr doesn't matter; it just shouldn't return a unicode object.
"""
uf = Uploade... | [
"def",
"test_unicode_uploadedfile_name",
"(",
"self",
")",
":",
"uf",
"=",
"UploadedFile",
"(",
"name",
"=",
"'¿Cómo?', ",
"c",
"ntent_type='",
"t",
"ext')",
"",
"self",
".",
"assertEqual",
"(",
"type",
"(",
"uf",
".",
"__repr__",
"(",
")",
")",
",",
"st... | [
27,
4
] | [
34,
50
] | python | en | ['en', 'error', 'th'] | False |
FileTests.test_namedtemporaryfile_closes | (self) |
The symbol django.core.files.NamedTemporaryFile is assigned as
a different class on different operating systems. In
any case, the result should minimally mock some of the API of
tempfile.NamedTemporaryFile from the Python standard library.
|
The symbol django.core.files.NamedTemporaryFile is assigned as
a different class on different operating systems. In
any case, the result should minimally mock some of the API of
tempfile.NamedTemporaryFile from the Python standard library.
| def test_namedtemporaryfile_closes(self):
"""
The symbol django.core.files.NamedTemporaryFile is assigned as
a different class on different operating systems. In
any case, the result should minimally mock some of the API of
tempfile.NamedTemporaryFile from the Python standard lib... | [
"def",
"test_namedtemporaryfile_closes",
"(",
"self",
")",
":",
"tempfile",
"=",
"NamedTemporaryFile",
"(",
")",
"self",
".",
"assertTrue",
"(",
"hasattr",
"(",
"tempfile",
",",
"\"closed\"",
")",
")",
"self",
".",
"assertFalse",
"(",
"tempfile",
".",
"closed"... | [
45,
4
] | [
57,
40
] | python | en | ['en', 'error', 'th'] | False |
FileTests.test_file_iteration | (self) |
File objects should yield lines when iterated over.
Refs #22107.
|
File objects should yield lines when iterated over.
Refs #22107.
| def test_file_iteration(self):
"""
File objects should yield lines when iterated over.
Refs #22107.
"""
file = File(BytesIO(b'one\ntwo\nthree'))
self.assertEqual(list(file), [b'one\n', b'two\n', b'three']) | [
"def",
"test_file_iteration",
"(",
"self",
")",
":",
"file",
"=",
"File",
"(",
"BytesIO",
"(",
"b'one\\ntwo\\nthree'",
")",
")",
"self",
".",
"assertEqual",
"(",
"list",
"(",
"file",
")",
",",
"[",
"b'one\\n'",
",",
"b'two\\n'",
",",
"b'three'",
"]",
")"... | [
66,
4
] | [
72,
68
] | python | en | ['en', 'error', 'th'] | False |
ContentFileTestCase.test_content_file_custom_name | (self) |
Test that the constructor of ContentFile accepts 'name' (#16590).
|
Test that the constructor of ContentFile accepts 'name' (#16590).
| def test_content_file_custom_name(self):
"""
Test that the constructor of ContentFile accepts 'name' (#16590).
"""
name = "I can have a name too!"
self.assertEqual(ContentFile(b"content", name=name).name, name) | [
"def",
"test_content_file_custom_name",
"(",
"self",
")",
":",
"name",
"=",
"\"I can have a name too!\"",
"self",
".",
"assertEqual",
"(",
"ContentFile",
"(",
"b\"content\"",
",",
"name",
"=",
"name",
")",
".",
"name",
",",
"name",
")"
] | [
91,
4
] | [
96,
71
] | python | en | ['en', 'error', 'th'] | False |
ContentFileTestCase.test_content_file_input_type | (self) |
Test that ContentFile can accept both bytes and unicode and that the
retrieved content is of the same type.
|
Test that ContentFile can accept both bytes and unicode and that the
retrieved content is of the same type.
| def test_content_file_input_type(self):
"""
Test that ContentFile can accept both bytes and unicode and that the
retrieved content is of the same type.
"""
self.assertIsInstance(ContentFile(b"content").read(), bytes)
if six.PY3:
self.assertIsInstance(ContentFi... | [
"def",
"test_content_file_input_type",
"(",
"self",
")",
":",
"self",
".",
"assertIsInstance",
"(",
"ContentFile",
"(",
"b\"content\"",
")",
".",
"read",
"(",
")",
",",
"bytes",
")",
"if",
"six",
".",
"PY3",
":",
"self",
".",
"assertIsInstance",
"(",
"Cont... | [
98,
4
] | [
107,
72
] | python | en | ['en', 'error', 'th'] | False |
DimensionClosingBug.test_not_closing_of_files | (self) |
Open files passed into get_image_dimensions() should stay opened.
|
Open files passed into get_image_dimensions() should stay opened.
| def test_not_closing_of_files(self):
"""
Open files passed into get_image_dimensions() should stay opened.
"""
empty_io = BytesIO()
try:
images.get_image_dimensions(empty_io)
finally:
self.assertTrue(not empty_io.closed) | [
"def",
"test_not_closing_of_files",
"(",
"self",
")",
":",
"empty_io",
"=",
"BytesIO",
"(",
")",
"try",
":",
"images",
".",
"get_image_dimensions",
"(",
"empty_io",
")",
"finally",
":",
"self",
".",
"assertTrue",
"(",
"not",
"empty_io",
".",
"closed",
")"
] | [
115,
4
] | [
123,
48
] | python | en | ['en', 'error', 'th'] | False |
DimensionClosingBug.test_closing_of_filenames | (self) |
get_image_dimensions() called with a filename should closed the file.
|
get_image_dimensions() called with a filename should closed the file.
| def test_closing_of_filenames(self):
"""
get_image_dimensions() called with a filename should closed the file.
"""
# We need to inject a modified open() builtin into the images module
# that checks if the file was closed properly if the function is
# called with a filenam... | [
"def",
"test_closing_of_filenames",
"(",
"self",
")",
":",
"# We need to inject a modified open() builtin into the images module",
"# that checks if the file was closed properly if the function is",
"# called with a filename instead of an file object.",
"# get_image_dimensions will call our catchi... | [
126,
4
] | [
157,
44
] | python | en | ['en', 'error', 'th'] | False |
InconsistentGetImageDimensionsBug.test_multiple_calls | (self) |
Multiple calls of get_image_dimensions() should return the same size.
|
Multiple calls of get_image_dimensions() should return the same size.
| def test_multiple_calls(self):
"""
Multiple calls of get_image_dimensions() should return the same size.
"""
img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
with open(img_path, 'rb') as fh:
image = images.ImageFile(fh)
image_pil = Ima... | [
"def",
"test_multiple_calls",
"(",
"self",
")",
":",
"img_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"upath",
"(",
"__file__",
")",
")",
",",
"\"test.png\"",
")",
"with",
"open",
"(",
"img_path",
",",
"'r... | [
166,
4
] | [
177,
40
] | python | en | ['en', 'error', 'th'] | False |
InconsistentGetImageDimensionsBug.test_bug_19457 | (self) |
Regression test for #19457
get_image_dimensions fails on some pngs, while Image.size is working good on them
|
Regression test for #19457
get_image_dimensions fails on some pngs, while Image.size is working good on them
| def test_bug_19457(self):
"""
Regression test for #19457
get_image_dimensions fails on some pngs, while Image.size is working good on them
"""
img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png")
try:
size = images.get_image_dimensions(img_pa... | [
"def",
"test_bug_19457",
"(",
"self",
")",
":",
"img_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"upath",
"(",
"__file__",
")",
")",
",",
"\"magic.png\"",
")",
"try",
":",
"size",
"=",
"images",
".",
"ge... | [
180,
4
] | [
191,
55
] | python | en | ['en', 'error', 'th'] | False |
install_package | (specifier, prefix) |
Install a pip package (without dependencies) into the prefix directory.
|
Install a pip package (without dependencies) into the prefix directory.
| def install_package(specifier, prefix):
"""
Install a pip package (without dependencies) into the prefix directory.
"""
# TODO(vip): If this command is run as a different user, we can prevent models
# from modifying the installed packages (can also do things like read-only mounts, etc.)
from pi... | [
"def",
"install_package",
"(",
"specifier",
",",
"prefix",
")",
":",
"# TODO(vip): If this command is run as a different user, we can prevent models",
"# from modifying the installed packages (can also do things like read-only mounts, etc.)",
"from",
"pip",
".",
"_internal",
".",
"cli"... | [
39,
0
] | [
63,
86
] | python | en | ['en', 'error', 'th'] | False |
bootstrap_requirements | () |
If we're loading the python library from native code in an isolated environment,
we need to make sure that our required deps are available before we try to load
Neuropod
This is called from the PythonBridge in native code
|
If we're loading the python library from native code in an isolated environment,
we need to make sure that our required deps are available before we try to load
Neuropod | def bootstrap_requirements():
"""
If we're loading the python library from native code in an isolated environment,
we need to make sure that our required deps are available before we try to load
Neuropod
This is called from the PythonBridge in native code
"""
if hasattr(bootstrap_requireme... | [
"def",
"bootstrap_requirements",
"(",
")",
":",
"if",
"hasattr",
"(",
"bootstrap_requirements",
",",
"\"did_run\"",
")",
":",
"# Only need to run this once",
"return",
"bootstrap_requirements",
".",
"did_run",
"=",
"True",
"# A lockfile of runtime requirements to bootstrap wi... | [
66,
0
] | [
91,
29
] | python | en | ['en', 'error', 'th'] | False |
load_deps | (lockfile) |
For each dependency in the lockfile, install it to the cachedir if necessary
and add it to sys.path
Note: the lockfile contains all transitive deps so we don't need to do any
recursive scanning
This is intented to be used by the native code when running with OPE (i.e. one
model per process).
... |
For each dependency in the lockfile, install it to the cachedir if necessary
and add it to sys.path | def load_deps(lockfile):
"""
For each dependency in the lockfile, install it to the cachedir if necessary
and add it to sys.path
Note: the lockfile contains all transitive deps so we don't need to do any
recursive scanning
This is intented to be used by the native code when running with OPE (i... | [
"def",
"load_deps",
"(",
"lockfile",
")",
":",
"with",
"open",
"(",
"lockfile",
",",
"\"r\"",
")",
"as",
"f",
":",
"lockfile_contents",
"=",
"f",
".",
"read",
"(",
")",
"# Load the data",
"_load_deps_internal",
"(",
"lockfile_contents",
")"
] | [
94,
0
] | [
109,
42
] | python | en | ['en', 'error', 'th'] | False |
_load_deps_internal | (lockfile_contents) |
See `load_deps` above for details
|
See `load_deps` above for details
| def _load_deps_internal(lockfile_contents):
"""
See `load_deps` above for details
"""
requirements = []
for line in lockfile_contents.splitlines():
# Remove comments
pos = line.find("#")
if pos != -1:
line = line[:pos]
# Remove surrounding whitespace
... | [
"def",
"_load_deps_internal",
"(",
"lockfile_contents",
")",
":",
"requirements",
"=",
"[",
"]",
"for",
"line",
"in",
"lockfile_contents",
".",
"splitlines",
"(",
")",
":",
"# Remove comments",
"pos",
"=",
"line",
".",
"find",
"(",
"\"#\"",
")",
"if",
"pos",... | [
112,
0
] | [
168,
9
] | python | en | ['en', 'error', 'th'] | False |
python_2_unicode_compatible | (klass) |
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
|
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing. | def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if six.PY... | [
"def",
"python_2_unicode_compatible",
"(",
"klass",
")",
":",
"if",
"six",
".",
"PY2",
":",
"if",
"'__str__'",
"not",
"in",
"klass",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"\"@python_2_unicode_compatible cannot be applied \"",
"\"to %s because it doesn't defi... | [
23,
0
] | [
38,
16
] | python | en | ['en', 'error', 'th'] | False |
smart_text | (s, encoding='utf-8', strings_only=False, errors='strict') |
Returns a text object representing 's' -- unicode on Python 2 and str on
Python 3. Treats bytestrings using the 'encoding' codec.
If strings_only is True, don't convert (some) non-string-like objects.
|
Returns a text object representing 's' -- unicode on Python 2 and str on
Python 3. Treats bytestrings using the 'encoding' codec. | def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a text object representing 's' -- unicode on Python 2 and str on
Python 3. Treats bytestrings using the 'encoding' codec.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstanc... | [
"def",
"smart_text",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"Promise",
")",
":",
"# The input is the result of a gettext_lazy() call.",
"return",
... | [
41,
0
] | [
51,
56
] | python | en | ['en', 'error', 'th'] | False |
is_protected_type | (obj) | Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
| Determine if the object instance is of a protected type. | def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
"""
return isinstance(obj, _PROTECTED_TYPES) | [
"def",
"is_protected_type",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"_PROTECTED_TYPES",
")"
] | [
58,
0
] | [
64,
44
] | python | en | ['en', 'en', 'en'] | True |
force_text | (s, encoding='utf-8', strings_only=False, errors='strict') |
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
|
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects. | def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first fo... | [
"def",
"force_text",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"# Handle the common case first for performance reasons.",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"text_type",
")... | [
67,
0
] | [
106,
12
] | python | en | ['en', 'error', 'th'] | False |
smart_bytes | (s, encoding='utf-8', strings_only=False, errors='strict') |
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
|
Returns a bytestring version of 's', encoded as specified in 'encoding'. | def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, Promise):
# The input is the result of a gettex... | [
"def",
"smart_bytes",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"Promise",
")",
":",
"# The input is the result of a gettext_lazy() call.",
"return",... | [
109,
0
] | [
118,
57
] | python | en | ['en', 'error', 'th'] | False |
force_bytes | (s, encoding='utf-8', strings_only=False, errors='strict') |
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
|
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects. | def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first ... | [
"def",
"force_bytes",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"# Handle the common case first for performance reasons.",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"if",
... | [
121,
0
] | [
155,
41
] | python | en | ['en', 'error', 'th'] | False |
iri_to_uri | (iri) |
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL.
This is the algorithm from section 3.1 of RFC 3987. However, since we are
assuming input is either UTF-8 or unicode already, we can simplify things a
little from the full metho... |
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL. | def iri_to_uri(iri):
"""
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL.
This is the algorithm from section 3.1 of RFC 3987. However, since we are
assuming input is either UTF-8 or unicode already, we can simplify things a
... | [
"def",
"iri_to_uri",
"(",
"iri",
")",
":",
"# The list of safe characters here is constructed from the \"reserved\" and",
"# \"unreserved\" characters specified in sections 2.2 and 2.3 of RFC 3986:",
"# reserved = gen-delims / sub-delims",
"# gen-delims = \":\" / \"/\" / \"?\" / \"#\" ... | [
178,
0
] | [
203,
64
] | python | en | ['en', 'error', 'th'] | False |
filepath_to_uri | (path) | Convert a file system path to a URI portion that is suitable for
inclusion in a URL.
We are assuming input is either UTF-8 or unicode already.
This method will encode certain chars that would normally be recognized as
special chars for URIs. Note that this method does not encode the '
character, ... | Convert a file system path to a URI portion that is suitable for
inclusion in a URL. | def filepath_to_uri(path):
"""Convert a file system path to a URI portion that is suitable for
inclusion in a URL.
We are assuming input is either UTF-8 or unicode already.
This method will encode certain chars that would normally be recognized as
special chars for URIs. Note that this method doe... | [
"def",
"filepath_to_uri",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"path",
"# I know about `os.sep` and `os.altsep` but I want to leave",
"# some flexibility for hardcoding separators.",
"return",
"quote",
"(",
"force_bytes",
"(",
"path",
")",
"."... | [
206,
0
] | [
223,
73
] | python | en | ['en', 'en', 'en'] | True |
get_system_encoding | () |
The encoding of the default system locale but falls back to the given
fallback encoding if the encoding is unsupported by python or could
not be determined. See tickets #10335 and #5846
|
The encoding of the default system locale but falls back to the given
fallback encoding if the encoding is unsupported by python or could
not be determined. See tickets #10335 and #5846
| def get_system_encoding():
"""
The encoding of the default system locale but falls back to the given
fallback encoding if the encoding is unsupported by python or could
not be determined. See tickets #10335 and #5846
"""
try:
encoding = locale.getdefaultlocale()[1] or 'ascii'
co... | [
"def",
"get_system_encoding",
"(",
")",
":",
"try",
":",
"encoding",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"[",
"1",
"]",
"or",
"'ascii'",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
"except",
"Exception",
":",
"encoding",
"=",
"'ascii'",
... | [
226,
0
] | [
237,
19
] | python | en | ['en', 'error', 'th'] | False |
_get_locale_dirs | (resources, include_core=True) |
Return a tuple (contrib name, absolute path) for all locale directories,
optionally including the django core catalog.
If resources list is not None, filter directories matching resources content.
|
Return a tuple (contrib name, absolute path) for all locale directories,
optionally including the django core catalog.
If resources list is not None, filter directories matching resources content.
| def _get_locale_dirs(resources, include_core=True):
"""
Return a tuple (contrib name, absolute path) for all locale directories,
optionally including the django core catalog.
If resources list is not None, filter directories matching resources content.
"""
contrib_dir = os.path.join(os.getcwd(),... | [
"def",
"_get_locale_dirs",
"(",
"resources",
",",
"include_core",
"=",
"True",
")",
":",
"contrib_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'django'",
",",
"'contrib'",
")",
"dirs",
"=",
"[",
"]",
"# Collect a... | [
30,
0
] | [
57,
15
] | python | en | ['en', 'error', 'th'] | False |
_tx_resource_for_name | (name) | Return the Transifex resource name | Return the Transifex resource name | def _tx_resource_for_name(name):
""" Return the Transifex resource name """
if name == 'core':
return "django.core"
else:
return "django.contrib-%s" % name | [
"def",
"_tx_resource_for_name",
"(",
"name",
")",
":",
"if",
"name",
"==",
"'core'",
":",
"return",
"\"django.core\"",
"else",
":",
"return",
"\"django.contrib-%s\"",
"%",
"name"
] | [
60,
0
] | [
65,
41
] | python | en | ['en', 'id', 'en'] | True |
_check_diff | (cat_name, base_path) |
Output the approximate number of changed/added strings in the en catalog.
|
Output the approximate number of changed/added strings in the en catalog.
| def _check_diff(cat_name, base_path):
"""
Output the approximate number of changed/added strings in the en catalog.
"""
po_path = '%(path)s/en/LC_MESSAGES/django%(ext)s.po' % {
'path': base_path, 'ext': 'js' if cat_name.endswith('-js') else ''}
p = Popen("git diff -U0 %s | egrep '^[-+]msgid'... | [
"def",
"_check_diff",
"(",
"cat_name",
",",
"base_path",
")",
":",
"po_path",
"=",
"'%(path)s/en/LC_MESSAGES/django%(ext)s.po'",
"%",
"{",
"'path'",
":",
"base_path",
",",
"'ext'",
":",
"'js'",
"if",
"cat_name",
".",
"endswith",
"(",
"'-js'",
")",
"else",
"''"... | [
68,
0
] | [
78,
81
] | python | en | ['en', 'error', 'th'] | False |
update_catalogs | (resources=None, languages=None) |
Update the en/LC_MESSAGES/django.po (main and contrib) files with
new/updated translatable strings.
|
Update the en/LC_MESSAGES/django.po (main and contrib) files with
new/updated translatable strings.
| def update_catalogs(resources=None, languages=None):
"""
Update the en/LC_MESSAGES/django.po (main and contrib) files with
new/updated translatable strings.
"""
if resources is not None:
print("`update_catalogs` will always process all resources.")
contrib_dirs = _get_locale_dirs(None, i... | [
"def",
"update_catalogs",
"(",
"resources",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",
"if",
"resources",
"is",
"not",
"None",
":",
"print",
"(",
"\"`update_catalogs` will always process all resources.\"",
")",
"contrib_dirs",
"=",
"_get_locale_dirs",
"("... | [
81,
0
] | [
99,
31
] | python | en | ['en', 'error', 'th'] | False |
lang_stats | (resources=None, languages=None) |
Output language statistics of committed translation files for each
Django catalog.
If resources is provided, it should be a list of translation resource to
limit the output (e.g. ['core', 'gis']).
|
Output language statistics of committed translation files for each
Django catalog.
If resources is provided, it should be a list of translation resource to
limit the output (e.g. ['core', 'gis']).
| def lang_stats(resources=None, languages=None):
"""
Output language statistics of committed translation files for each
Django catalog.
If resources is provided, it should be a list of translation resource to
limit the output (e.g. ['core', 'gis']).
"""
locale_dirs = _get_locale_dirs(resource... | [
"def",
"lang_stats",
"(",
"resources",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",
"locale_dirs",
"=",
"_get_locale_dirs",
"(",
"resources",
")",
"for",
"name",
",",
"dir_",
"in",
"locale_dirs",
":",
"print",
"(",
"\"\\nShowing translations stats for '... | [
102,
0
] | [
127,
40
] | python | en | ['en', 'error', 'th'] | False |
fetch | (resources=None, languages=None) |
Fetch translations from Transifex, wrap long lines, generate mo files.
|
Fetch translations from Transifex, wrap long lines, generate mo files.
| def fetch(resources=None, languages=None):
"""
Fetch translations from Transifex, wrap long lines, generate mo files.
"""
locale_dirs = _get_locale_dirs(resources)
errors = []
for name, dir_ in locale_dirs:
# Transifex pull
if languages is None:
call('tx pull -r %(re... | [
"def",
"fetch",
"(",
"resources",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",
"locale_dirs",
"=",
"_get_locale_dirs",
"(",
"resources",
")",
"errors",
"=",
"[",
"]",
"for",
"name",
",",
"dir_",
"in",
"locale_dirs",
":",
"# Transifex pull",
"if",
... | [
130,
0
] | [
163,
15
] | python | en | ['en', 'error', 'th'] | False |
mnist_tutorial | (
nb_epochs=NB_EPOCHS,
batch_size=BATCH_SIZE,
train_end=-1,
test_end=-1,
learning_rate=LEARNING_RATE,
) |
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for training
:return: an AccuracyReport object
|
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning rate for training
:return: an AccuracyReport object
| def mnist_tutorial(
nb_epochs=NB_EPOCHS,
batch_size=BATCH_SIZE,
train_end=-1,
test_end=-1,
learning_rate=LEARNING_RATE,
):
"""
MNIST cleverhans tutorial
:param nb_epochs: number of epochs to train model
:param batch_size: size of training batches
:param learning_rate: learning ra... | [
"def",
"mnist_tutorial",
"(",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"train_end",
"=",
"-",
"1",
",",
"test_end",
"=",
"-",
"1",
",",
"learning_rate",
"=",
"LEARNING_RATE",
",",
")",
":",
"# Train a pytorch MNIST model",
"tor... | [
69,
0
] | [
185,
17
] | python | en | ['en', 'error', 'th'] | False |
_wrapper | (args=None) | Central wrapper for all old entrypoints.
Historically pip has had several entrypoints defined. Because of issues
arising from PATH, sys.path, multiple Pythons, their interactions, and most
of them having a pip installed, users suffer every time an entrypoint gets
moved.
To alleviate this pain, and... | Central wrapper for all old entrypoints. | def _wrapper(args=None):
# type: (Optional[List[str]]) -> int
"""Central wrapper for all old entrypoints.
Historically pip has had several entrypoints defined. Because of issues
arising from PATH, sys.path, multiple Pythons, their interactions, and most
of them having a pip installed, users suffer ... | [
"def",
"_wrapper",
"(",
"args",
"=",
"None",
")",
":",
"# type: (Optional[List[str]]) -> int",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"WARNING: pip is being invoked by an old script wrapper. This will \"",
"\"fail in a future version of pip.\\n\"",
"\"Please see https://github.... | [
9,
0
] | [
30,
21
] | python | en | ['en', 'en', 'en'] | True |
WhereNode.split_having | (self, negated=False) |
Return two possibly None nodes: one for those parts of self that
should be included in the WHERE clause and one for those parts of
self that must be included in the HAVING clause.
|
Return two possibly None nodes: one for those parts of self that
should be included in the WHERE clause and one for those parts of
self that must be included in the HAVING clause.
| def split_having(self, negated=False):
"""
Return two possibly None nodes: one for those parts of self that
should be included in the WHERE clause and one for those parts of
self that must be included in the HAVING clause.
"""
if not self.contains_aggregate:
r... | [
"def",
"split_having",
"(",
"self",
",",
"negated",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"contains_aggregate",
":",
"return",
"self",
",",
"None",
"in_negated",
"=",
"negated",
"^",
"self",
".",
"negated",
"# If the effective connector is OR and thi... | [
31,
4
] | [
62,
38
] | python | en | ['en', 'error', 'th'] | False |
WhereNode.as_sql | (self, compiler, connection) |
Return the SQL version of the where clause and the value to be
substituted in. Return '', [] if this node matches everything,
None, [] if this node is empty, and raise EmptyResultSet if this
node can't match anything.
|
Return the SQL version of the where clause and the value to be
substituted in. Return '', [] if this node matches everything,
None, [] if this node is empty, and raise EmptyResultSet if this
node can't match anything.
| def as_sql(self, compiler, connection):
"""
Return the SQL version of the where clause and the value to be
substituted in. Return '', [] if this node matches everything,
None, [] if this node is empty, and raise EmptyResultSet if this
node can't match anything.
"""
... | [
"def",
"as_sql",
"(",
"self",
",",
"compiler",
",",
"connection",
")",
":",
"result",
"=",
"[",
"]",
"result_params",
"=",
"[",
"]",
"if",
"self",
".",
"connector",
"==",
"AND",
":",
"full_needed",
",",
"empty_needed",
"=",
"len",
"(",
"self",
".",
"... | [
64,
4
] | [
114,
40
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.