id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
170,308 | import os
import re
import sys
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import multiprocessing
import textwrap
import importlib.util
from threading import local as tlocal
from functools import reduce
import distutils
from distutils.errors import DistutilsError
def is_string(s):
return isinstance(s, str)
def is_local_src_dir(directory):
"""Return true if directory is local directory.
"""
if not is_string(directory):
return False
abs_dir = os.path.abspath(directory)
c = os.path.commonprefix([os.getcwd(), abs_dir])
new_dir = abs_dir[len(c):].split(os.sep)
if new_dir and not new_dir[0]:
new_dir = new_dir[1:]
if new_dir and new_dir[0]=='build':
return False
new_dir = os.sep.join(new_dir)
return os.path.isdir(new_dir)
def general_source_files(top_path):
pruned_directories = {'CVS':1, '.svn':1, 'build':1}
prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$')
for dirpath, dirnames, filenames in os.walk(top_path, topdown=True):
pruned = [ d for d in dirnames if d not in pruned_directories ]
dirnames[:] = pruned
for f in filenames:
if not prune_file_pat.search(f):
yield os.path.join(dirpath, f)
def get_data_files(data):
if is_string(data):
return [data]
sources = data[1]
filenames = []
for s in sources:
if hasattr(s, '__call__'):
continue
if is_local_src_dir(s):
filenames.extend(list(general_source_files(s)))
elif is_string(s):
if os.path.isfile(s):
filenames.append(s)
else:
print('Not existing data file:', s)
else:
raise TypeError(repr(s))
return filenames | null |
170,309 | import os
import re
import sys
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import multiprocessing
import textwrap
import importlib.util
from threading import local as tlocal
from functools import reduce
import distutils
from distutils.errors import DistutilsError
The provided code snippet includes necessary dependencies for implementing the `get_frame` function. Write a Python function `def get_frame(level=0)` to solve the following problem:
Return frame object from call stack with given level.
Here is the function:
def get_frame(level=0):
"""Return frame object from call stack with given level.
"""
try:
return sys._getframe(level+1)
except AttributeError:
frame = sys.exc_info()[2].tb_frame
for _ in range(level+1):
frame = frame.f_back
return frame | Return frame object from call stack with given level. |
170,310 | import os
import re
import sys
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import multiprocessing
import textwrap
import importlib.util
from threading import local as tlocal
from functools import reduce
import distutils
from distutils.errors import DistutilsError
def get_cmd(cmdname, _cache={}):
if cmdname not in _cache:
import distutils.core
dist = distutils.core._setup_distribution
if dist is None:
from distutils.errors import DistutilsInternalError
raise DistutilsInternalError(
'setup distribution instance not initialized')
cmd = dist.get_command_obj(cmdname)
_cache[cmdname] = cmd
return _cache[cmdname] | null |
170,311 | import os
import re
import sys
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import multiprocessing
import textwrap
import importlib.util
from threading import local as tlocal
from functools import reduce
import distutils
from distutils.errors import DistutilsError
def is_bootstrapping():
import builtins
try:
builtins.__NUMPY_SETUP__
return True
except AttributeError:
return False | null |
170,312 | import os
import re
import sys
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import multiprocessing
import textwrap
import importlib.util
from threading import local as tlocal
from functools import reduce
import distutils
from distutils.errors import DistutilsError
class Configuration:
_list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs',
'libraries', 'headers', 'scripts', 'py_modules',
'installed_libraries', 'define_macros']
_dict_keys = ['package_dir', 'installed_pkg_config']
_extra_keys = ['name', 'version']
numpy_include_dirs = []
def __init__(self,
package_name=None,
parent_name=None,
top_path=None,
package_path=None,
caller_level=1,
setup_name='setup.py',
**attrs):
"""Construct configuration instance of a package.
package_name -- name of the package
Ex.: 'distutils'
parent_name -- name of the parent package
Ex.: 'numpy'
top_path -- directory of the toplevel package
Ex.: the directory where the numpy package source sits
package_path -- directory of package. Will be computed by magic from the
directory of the caller module if not specified
Ex.: the directory where numpy.distutils is
caller_level -- frame level to caller namespace, internal parameter.
"""
self.name = dot_join(parent_name, package_name)
self.version = None
caller_frame = get_frame(caller_level)
self.local_path = get_path_from_frame(caller_frame, top_path)
# local_path -- directory of a file (usually setup.py) that
# defines a configuration() function.
# local_path -- directory of a file (usually setup.py) that
# defines a configuration() function.
if top_path is None:
top_path = self.local_path
self.local_path = ''
if package_path is None:
package_path = self.local_path
elif os.path.isdir(njoin(self.local_path, package_path)):
package_path = njoin(self.local_path, package_path)
if not os.path.isdir(package_path or '.'):
raise ValueError("%r is not a directory" % (package_path,))
self.top_path = top_path
self.package_path = package_path
# this is the relative path in the installed package
self.path_in_package = os.path.join(*self.name.split('.'))
self.list_keys = self._list_keys[:]
self.dict_keys = self._dict_keys[:]
for n in self.list_keys:
v = copy.copy(attrs.get(n, []))
setattr(self, n, as_list(v))
for n in self.dict_keys:
v = copy.copy(attrs.get(n, {}))
setattr(self, n, v)
known_keys = self.list_keys + self.dict_keys
self.extra_keys = self._extra_keys[:]
for n in attrs.keys():
if n in known_keys:
continue
a = attrs[n]
setattr(self, n, a)
if isinstance(a, list):
self.list_keys.append(n)
elif isinstance(a, dict):
self.dict_keys.append(n)
else:
self.extra_keys.append(n)
if os.path.exists(njoin(package_path, '__init__.py')):
self.packages.append(self.name)
self.package_dir[self.name] = package_path
self.options = dict(
ignore_setup_xxx_py = False,
assume_default_configuration = False,
delegate_options_to_subpackages = False,
quiet = False,
)
caller_instance = None
for i in range(1, 3):
try:
f = get_frame(i)
except ValueError:
break
try:
caller_instance = eval('self', f.f_globals, f.f_locals)
break
except NameError:
pass
if isinstance(caller_instance, self.__class__):
if caller_instance.options['delegate_options_to_subpackages']:
self.set_options(**caller_instance.options)
self.setup_name = setup_name
def todict(self):
"""
Return a dictionary compatible with the keyword arguments of distutils
setup function.
Examples
--------
>>> setup(**config.todict()) #doctest: +SKIP
"""
self._optimize_data_files()
d = {}
known_keys = self.list_keys + self.dict_keys + self.extra_keys
for n in known_keys:
a = getattr(self, n)
if a:
d[n] = a
return d
def info(self, message):
if not self.options['quiet']:
print(message)
def warn(self, message):
sys.stderr.write('Warning: %s\n' % (message,))
def set_options(self, **options):
"""
Configure Configuration instance.
The following options are available:
- ignore_setup_xxx_py
- assume_default_configuration
- delegate_options_to_subpackages
- quiet
"""
for key, value in options.items():
if key in self.options:
self.options[key] = value
else:
raise ValueError('Unknown option: '+key)
def get_distribution(self):
"""Return the distutils distribution object for self."""
from numpy.distutils.core import get_distribution
return get_distribution()
def _wildcard_get_subpackage(self, subpackage_name,
parent_name,
caller_level = 1):
l = subpackage_name.split('.')
subpackage_path = njoin([self.local_path]+l)
dirs = [_m for _m in sorted_glob(subpackage_path) if os.path.isdir(_m)]
config_list = []
for d in dirs:
if not os.path.isfile(njoin(d, '__init__.py')):
continue
if 'build' in d.split(os.sep):
continue
n = '.'.join(d.split(os.sep)[-len(l):])
c = self.get_subpackage(n,
parent_name = parent_name,
caller_level = caller_level+1)
config_list.extend(c)
return config_list
def _get_configuration_from_setup_py(self, setup_py,
subpackage_name,
subpackage_path,
parent_name,
caller_level = 1):
# In case setup_py imports local modules:
sys.path.insert(0, os.path.dirname(setup_py))
try:
setup_name = os.path.splitext(os.path.basename(setup_py))[0]
n = dot_join(self.name, subpackage_name, setup_name)
setup_module = exec_mod_from_location(
'_'.join(n.split('.')), setup_py)
if not hasattr(setup_module, 'configuration'):
if not self.options['assume_default_configuration']:
self.warn('Assuming default configuration '\
'(%s does not define configuration())'\
% (setup_module))
config = Configuration(subpackage_name, parent_name,
self.top_path, subpackage_path,
caller_level = caller_level + 1)
else:
pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1]))
args = (pn,)
if setup_module.configuration.__code__.co_argcount > 1:
args = args + (self.top_path,)
config = setup_module.configuration(*args)
if config.name!=dot_join(parent_name, subpackage_name):
self.warn('Subpackage %r configuration returned as %r' % \
(dot_join(parent_name, subpackage_name), config.name))
finally:
del sys.path[0]
return config
def get_subpackage(self,subpackage_name,
subpackage_path=None,
parent_name=None,
caller_level = 1):
"""Return list of subpackage configurations.
Parameters
----------
subpackage_name : str or None
Name of the subpackage to get the configuration. '*' in
subpackage_name is handled as a wildcard.
subpackage_path : str
If None, then the path is assumed to be the local path plus the
subpackage_name. If a setup.py file is not found in the
subpackage_path, then a default configuration is used.
parent_name : str
Parent name.
"""
if subpackage_name is None:
if subpackage_path is None:
raise ValueError(
"either subpackage_name or subpackage_path must be specified")
subpackage_name = os.path.basename(subpackage_path)
# handle wildcards
l = subpackage_name.split('.')
if subpackage_path is None and '*' in subpackage_name:
return self._wildcard_get_subpackage(subpackage_name,
parent_name,
caller_level = caller_level+1)
assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name))
if subpackage_path is None:
subpackage_path = njoin([self.local_path] + l)
else:
subpackage_path = njoin([subpackage_path] + l[:-1])
subpackage_path = self.paths([subpackage_path])[0]
setup_py = njoin(subpackage_path, self.setup_name)
if not self.options['ignore_setup_xxx_py']:
if not os.path.isfile(setup_py):
setup_py = njoin(subpackage_path,
'setup_%s.py' % (subpackage_name))
if not os.path.isfile(setup_py):
if not self.options['assume_default_configuration']:
self.warn('Assuming default configuration '\
'(%s/{setup_%s,setup}.py was not found)' \
% (os.path.dirname(setup_py), subpackage_name))
config = Configuration(subpackage_name, parent_name,
self.top_path, subpackage_path,
caller_level = caller_level+1)
else:
config = self._get_configuration_from_setup_py(
setup_py,
subpackage_name,
subpackage_path,
parent_name,
caller_level = caller_level + 1)
if config:
return [config]
else:
return []
def add_subpackage(self,subpackage_name,
subpackage_path=None,
standalone = False):
"""Add a sub-package to the current Configuration instance.
This is useful in a setup.py script for adding sub-packages to a
package.
Parameters
----------
subpackage_name : str
name of the subpackage
subpackage_path : str
if given, the subpackage path such as the subpackage is in
subpackage_path / subpackage_name. If None,the subpackage is
assumed to be located in the local path / subpackage_name.
standalone : bool
"""
if standalone:
parent_name = None
else:
parent_name = self.name
config_list = self.get_subpackage(subpackage_name, subpackage_path,
parent_name = parent_name,
caller_level = 2)
if not config_list:
self.warn('No configuration returned, assuming unavailable.')
for config in config_list:
d = config
if isinstance(config, Configuration):
d = config.todict()
assert isinstance(d, dict), repr(type(d))
self.info('Appending %s configuration to %s' \
% (d.get('name'), self.name))
self.dict_append(**d)
dist = self.get_distribution()
if dist is not None:
self.warn('distutils distribution has been initialized,'\
' it may be too late to add a subpackage '+ subpackage_name)
def add_data_dir(self, data_path):
"""Recursively add files under data_path to data_files list.
Recursively add files under data_path to the list of data_files to be
installed (and distributed). The data_path can be either a relative
path-name, or an absolute path-name, or a 2-tuple where the first
argument shows where in the install directory the data directory
should be installed to.
Parameters
----------
data_path : seq or str
Argument can be either
* 2-sequence (<datadir suffix>, <path to data directory>)
* path to data directory where python datadir suffix defaults
to package dir.
Notes
-----
Rules for installation paths::
foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar
(gun, foo/bar) -> parent/gun
foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b
(gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun
(gun/*, foo/*) -> parent/gun/a, parent/gun/b
/foo/bar -> (bar, /foo/bar) -> parent/bar
(gun, /foo/bar) -> parent/gun
(fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar
Examples
--------
For example suppose the source directory contains fun/foo.dat and
fun/bar/car.dat:
>>> self.add_data_dir('fun') #doctest: +SKIP
>>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP
>>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP
Will install data-files to the locations::
<package install directory>/
fun/
foo.dat
bar/
car.dat
sun/
foo.dat
bar/
car.dat
gun/
foo.dat
car.dat
"""
if is_sequence(data_path):
d, data_path = data_path
else:
d = None
if is_sequence(data_path):
[self.add_data_dir((d, p)) for p in data_path]
return
if not is_string(data_path):
raise TypeError("not a string: %r" % (data_path,))
if d is None:
if os.path.isabs(data_path):
return self.add_data_dir((os.path.basename(data_path), data_path))
return self.add_data_dir((data_path, data_path))
paths = self.paths(data_path, include_non_existing=False)
if is_glob_pattern(data_path):
if is_glob_pattern(d):
pattern_list = allpath(d).split(os.sep)
pattern_list.reverse()
# /a/*//b/ -> /a/*/b
rl = list(range(len(pattern_list)-1)); rl.reverse()
for i in rl:
if not pattern_list[i]:
del pattern_list[i]
#
for path in paths:
if not os.path.isdir(path):
print('Not a directory, skipping', path)
continue
rpath = rel_path(path, self.local_path)
path_list = rpath.split(os.sep)
path_list.reverse()
target_list = []
i = 0
for s in pattern_list:
if is_glob_pattern(s):
if i>=len(path_list):
raise ValueError('cannot fill pattern %r with %r' \
% (d, path))
target_list.append(path_list[i])
else:
assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath))
target_list.append(s)
i += 1
if path_list[i:]:
self.warn('mismatch of pattern_list=%s and path_list=%s'\
% (pattern_list, path_list))
target_list.reverse()
self.add_data_dir((os.sep.join(target_list), path))
else:
for path in paths:
self.add_data_dir((d, path))
return
assert not is_glob_pattern(d), repr(d)
dist = self.get_distribution()
if dist is not None and dist.data_files is not None:
data_files = dist.data_files
else:
data_files = self.data_files
for path in paths:
for d1, f in list(general_source_directories_files(path)):
target_path = os.path.join(self.path_in_package, d, d1)
data_files.append((target_path, f))
def _optimize_data_files(self):
data_dict = {}
for p, files in self.data_files:
if p not in data_dict:
data_dict[p] = set()
for f in files:
data_dict[p].add(f)
self.data_files[:] = [(p, list(files)) for p, files in data_dict.items()]
def add_data_files(self,*files):
"""Add data files to configuration data_files.
Parameters
----------
files : sequence
Argument(s) can be either
* 2-sequence (<datadir prefix>,<path to data file(s)>)
* paths to data files where python datadir prefix defaults
to package dir.
Notes
-----
The form of each element of the files sequence is very flexible
allowing many combinations of where to get the files from the package
and where they should ultimately be installed on the system. The most
basic usage is for an element of the files argument sequence to be a
simple filename. This will cause that file from the local path to be
installed to the installation path of the self.name package (package
path). The file argument can also be a relative path in which case the
entire relative path will be installed into the package directory.
Finally, the file can be an absolute path name in which case the file
will be found at the absolute path name but installed to the package
path.
This basic behavior can be augmented by passing a 2-tuple in as the
file argument. The first element of the tuple should specify the
relative path (under the package install directory) where the
remaining sequence of files should be installed to (it has nothing to
do with the file-names in the source distribution). The second element
of the tuple is the sequence of files that should be installed. The
files in this sequence can be filenames, relative paths, or absolute
paths. For absolute paths the file will be installed in the top-level
package installation directory (regardless of the first argument).
Filenames and relative path names will be installed in the package
install directory under the path name given as the first element of
the tuple.
Rules for installation paths:
#. file.txt -> (., file.txt)-> parent/file.txt
#. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt
#. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt
#. ``*``.txt -> parent/a.txt, parent/b.txt
#. foo/``*``.txt`` -> parent/foo/a.txt, parent/foo/b.txt
#. ``*/*.txt`` -> (``*``, ``*``/``*``.txt) -> parent/c/a.txt, parent/d/b.txt
#. (sun, file.txt) -> parent/sun/file.txt
#. (sun, bar/file.txt) -> parent/sun/file.txt
#. (sun, /foo/bar/file.txt) -> parent/sun/file.txt
#. (sun, ``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt
#. (sun, bar/``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt
#. (sun/``*``, ``*``/``*``.txt) -> parent/sun/c/a.txt, parent/d/b.txt
An additional feature is that the path to a data-file can actually be
a function that takes no arguments and returns the actual path(s) to
the data-files. This is useful when the data files are generated while
building the package.
Examples
--------
Add files to the list of data_files to be included with the package.
>>> self.add_data_files('foo.dat',
... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']),
... 'bar/cat.dat',
... '/full/path/to/can.dat') #doctest: +SKIP
will install these data files to::
<package install directory>/
foo.dat
fun/
gun.dat
nun/
pun.dat
sun.dat
bar/
car.dat
can.dat
where <package install directory> is the package (or sub-package)
directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C:
\\Python2.4 \\Lib \\site-packages \\mypackage') or
'/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C:
\\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage').
"""
if len(files)>1:
for f in files:
self.add_data_files(f)
return
assert len(files)==1
if is_sequence(files[0]):
d, files = files[0]
else:
d = None
if is_string(files):
filepat = files
elif is_sequence(files):
if len(files)==1:
filepat = files[0]
else:
for f in files:
self.add_data_files((d, f))
return
else:
raise TypeError(repr(type(files)))
if d is None:
if hasattr(filepat, '__call__'):
d = ''
elif os.path.isabs(filepat):
d = ''
else:
d = os.path.dirname(filepat)
self.add_data_files((d, files))
return
paths = self.paths(filepat, include_non_existing=False)
if is_glob_pattern(filepat):
if is_glob_pattern(d):
pattern_list = d.split(os.sep)
pattern_list.reverse()
for path in paths:
path_list = path.split(os.sep)
path_list.reverse()
path_list.pop() # filename
target_list = []
i = 0
for s in pattern_list:
if is_glob_pattern(s):
target_list.append(path_list[i])
i += 1
else:
target_list.append(s)
target_list.reverse()
self.add_data_files((os.sep.join(target_list), path))
else:
self.add_data_files((d, paths))
return
assert not is_glob_pattern(d), repr((d, filepat))
dist = self.get_distribution()
if dist is not None and dist.data_files is not None:
data_files = dist.data_files
else:
data_files = self.data_files
data_files.append((os.path.join(self.path_in_package, d), paths))
### XXX Implement add_py_modules
def add_define_macros(self, macros):
"""Add define macros to configuration
Add the given sequence of macro name and value duples to the beginning
of the define_macros list This list will be visible to all extension
modules of the current package.
"""
dist = self.get_distribution()
if dist is not None:
if not hasattr(dist, 'define_macros'):
dist.define_macros = []
dist.define_macros.extend(macros)
else:
self.define_macros.extend(macros)
def add_include_dirs(self,*paths):
"""Add paths to configuration include directories.
Add the given sequence of paths to the beginning of the include_dirs
list. This list will be visible to all extension modules of the
current package.
"""
include_dirs = self.paths(paths)
dist = self.get_distribution()
if dist is not None:
if dist.include_dirs is None:
dist.include_dirs = []
dist.include_dirs.extend(include_dirs)
else:
self.include_dirs.extend(include_dirs)
def add_headers(self,*files):
"""Add installable headers to configuration.
Add the given sequence of files to the beginning of the headers list.
By default, headers will be installed under <python-
include>/<self.name.replace('.','/')>/ directory. If an item of files
is a tuple, then its first argument specifies the actual installation
location relative to the <python-include> path.
Parameters
----------
files : str or seq
Argument(s) can be either:
* 2-sequence (<includedir suffix>,<path to header file(s)>)
* path(s) to header file(s) where python includedir suffix will
default to package name.
"""
headers = []
for path in files:
if is_string(path):
[headers.append((self.name, p)) for p in self.paths(path)]
else:
if not isinstance(path, (tuple, list)) or len(path) != 2:
raise TypeError(repr(path))
[headers.append((path[0], p)) for p in self.paths(path[1])]
dist = self.get_distribution()
if dist is not None:
if dist.headers is None:
dist.headers = []
dist.headers.extend(headers)
else:
self.headers.extend(headers)
def paths(self,*paths,**kws):
"""Apply glob to paths and prepend local_path if needed.
Applies glob.glob(...) to each path in the sequence (if needed) and
pre-pends the local_path if needed. Because this is called on all
source lists, this allows wildcard characters to be specified in lists
of sources for extension modules and libraries and scripts and allows
path-names be relative to the source directory.
"""
include_non_existing = kws.get('include_non_existing', True)
return gpaths(paths,
local_path = self.local_path,
include_non_existing=include_non_existing)
def _fix_paths_dict(self, kw):
for k in kw.keys():
v = kw[k]
if k in ['sources', 'depends', 'include_dirs', 'library_dirs',
'module_dirs', 'extra_objects']:
new_v = self.paths(v)
kw[k] = new_v
def add_extension(self,name,sources,**kw):
"""Add extension to configuration.
Create and add an Extension instance to the ext_modules list. This
method also takes the following optional keyword arguments that are
passed on to the Extension constructor.
Parameters
----------
name : str
name of the extension
sources : seq
list of the sources. The list of sources may contain functions
(called source generators) which must take an extension instance
and a build directory as inputs and return a source file or list of
source files or None. If None is returned then no sources are
generated. If the Extension instance has no sources after
processing all source generators, then no extension module is
built.
include_dirs :
define_macros :
undef_macros :
library_dirs :
libraries :
runtime_library_dirs :
extra_objects :
extra_compile_args :
extra_link_args :
extra_f77_compile_args :
extra_f90_compile_args :
export_symbols :
swig_opts :
depends :
The depends list contains paths to files or directories that the
sources of the extension module depend on. If any path in the
depends list is newer than the extension module, then the module
will be rebuilt.
language :
f2py_options :
module_dirs :
extra_info : dict or list
dict or list of dict of keywords to be appended to keywords.
Notes
-----
The self.paths(...) method is applied to all lists that may contain
paths.
"""
ext_args = copy.copy(kw)
ext_args['name'] = dot_join(self.name, name)
ext_args['sources'] = sources
if 'extra_info' in ext_args:
extra_info = ext_args['extra_info']
del ext_args['extra_info']
if isinstance(extra_info, dict):
extra_info = [extra_info]
for info in extra_info:
assert isinstance(info, dict), repr(info)
dict_append(ext_args,**info)
self._fix_paths_dict(ext_args)
# Resolve out-of-tree dependencies
libraries = ext_args.get('libraries', [])
libnames = []
ext_args['libraries'] = []
for libname in libraries:
if isinstance(libname, tuple):
self._fix_paths_dict(libname[1])
# Handle library names of the form libname@relative/path/to/library
if '@' in libname:
lname, lpath = libname.split('@', 1)
lpath = os.path.abspath(njoin(self.local_path, lpath))
if os.path.isdir(lpath):
c = self.get_subpackage(None, lpath,
caller_level = 2)
if isinstance(c, Configuration):
c = c.todict()
for l in [l[0] for l in c.get('libraries', [])]:
llname = l.split('__OF__', 1)[0]
if llname == lname:
c.pop('name', None)
dict_append(ext_args,**c)
break
continue
libnames.append(libname)
ext_args['libraries'] = libnames + ext_args['libraries']
ext_args['define_macros'] = \
self.define_macros + ext_args.get('define_macros', [])
from numpy.distutils.core import Extension
ext = Extension(**ext_args)
self.ext_modules.append(ext)
dist = self.get_distribution()
if dist is not None:
self.warn('distutils distribution has been initialized,'\
' it may be too late to add an extension '+name)
return ext
def add_library(self,name,sources,**build_info):
"""
Add library to configuration.
Parameters
----------
name : str
Name of the extension.
sources : sequence
List of the sources. The list of sources may contain functions
(called source generators) which must take an extension instance
and a build directory as inputs and return a source file or list of
source files or None. If None is returned then no sources are
generated. If the Extension instance has no sources after
processing all source generators, then no extension module is
built.
build_info : dict, optional
The following keys are allowed:
* depends
* macros
* include_dirs
* extra_compiler_args
* extra_f77_compile_args
* extra_f90_compile_args
* f2py_options
* language
"""
self._add_library(name, sources, None, build_info)
dist = self.get_distribution()
if dist is not None:
self.warn('distutils distribution has been initialized,'\
' it may be too late to add a library '+ name)
def _add_library(self, name, sources, install_dir, build_info):
"""Common implementation for add_library and add_installed_library. Do
not use directly"""
build_info = copy.copy(build_info)
build_info['sources'] = sources
# Sometimes, depends is not set up to an empty list by default, and if
# depends is not given to add_library, distutils barfs (#1134)
if not 'depends' in build_info:
build_info['depends'] = []
self._fix_paths_dict(build_info)
# Add to libraries list so that it is build with build_clib
self.libraries.append((name, build_info))
def add_installed_library(self, name, sources, install_dir, build_info=None):
"""
Similar to add_library, but the specified library is installed.
Most C libraries used with `distutils` are only used to build python
extensions, but libraries built through this method will be installed
so that they can be reused by third-party packages.
Parameters
----------
name : str
Name of the installed library.
sources : sequence
List of the library's source files. See `add_library` for details.
install_dir : str
Path to install the library, relative to the current sub-package.
build_info : dict, optional
The following keys are allowed:
* depends
* macros
* include_dirs
* extra_compiler_args
* extra_f77_compile_args
* extra_f90_compile_args
* f2py_options
* language
Returns
-------
None
See Also
--------
add_library, add_npy_pkg_config, get_info
Notes
-----
The best way to encode the options required to link against the specified
C libraries is to use a "libname.ini" file, and use `get_info` to
retrieve the required options (see `add_npy_pkg_config` for more
information).
"""
if not build_info:
build_info = {}
install_dir = os.path.join(self.package_path, install_dir)
self._add_library(name, sources, install_dir, build_info)
self.installed_libraries.append(InstallableLib(name, build_info, install_dir))
def add_npy_pkg_config(self, template, install_dir, subst_dict=None):
"""
Generate and install a npy-pkg config file from a template.
The config file generated from `template` is installed in the
given install directory, using `subst_dict` for variable substitution.
Parameters
----------
template : str
The path of the template, relatively to the current package path.
install_dir : str
Where to install the npy-pkg config file, relatively to the current
package path.
subst_dict : dict, optional
If given, any string of the form ``@key@`` will be replaced by
``subst_dict[key]`` in the template file when installed. The install
prefix is always available through the variable ``@prefix@``, since the
install prefix is not easy to get reliably from setup.py.
See also
--------
add_installed_library, get_info
Notes
-----
This works for both standard installs and in-place builds, i.e. the
``@prefix@`` refer to the source directory for in-place builds.
Examples
--------
::
config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar})
Assuming the foo.ini.in file has the following content::
[meta]
Name=@foo@
Version=1.0
Description=dummy description
[default]
Cflags=-I@prefix@/include
Libs=
The generated file will have the following content::
[meta]
Name=bar
Version=1.0
Description=dummy description
[default]
Cflags=-Iprefix_dir/include
Libs=
and will be installed as foo.ini in the 'lib' subpath.
When cross-compiling with numpy distutils, it might be necessary to
use modified npy-pkg-config files. Using the default/generated files
will link with the host libraries (i.e. libnpymath.a). For
cross-compilation you of-course need to link with target libraries,
while using the host Python installation.
You can copy out the numpy/core/lib/npy-pkg-config directory, add a
pkgdir value to the .ini files and set NPY_PKG_CONFIG_PATH environment
variable to point to the directory with the modified npy-pkg-config
files.
Example npymath.ini modified for cross-compilation::
[meta]
Name=npymath
Description=Portable, core math library implementing C99 standard
Version=0.1
[variables]
pkgname=numpy.core
pkgdir=/build/arm-linux-gnueabi/sysroot/usr/lib/python3.7/site-packages/numpy/core
prefix=${pkgdir}
libdir=${prefix}/lib
includedir=${prefix}/include
[default]
Libs=-L${libdir} -lnpymath
Cflags=-I${includedir}
Requires=mlib
[msvc]
Libs=/LIBPATH:${libdir} npymath.lib
Cflags=/INCLUDE:${includedir}
Requires=mlib
"""
if subst_dict is None:
subst_dict = {}
template = os.path.join(self.package_path, template)
if self.name in self.installed_pkg_config:
self.installed_pkg_config[self.name].append((template, install_dir,
subst_dict))
else:
self.installed_pkg_config[self.name] = [(template, install_dir,
subst_dict)]
def add_scripts(self,*files):
"""Add scripts to configuration.
Add the sequence of files to the beginning of the scripts list.
Scripts will be installed under the <prefix>/bin/ directory.
"""
scripts = self.paths(files)
dist = self.get_distribution()
if dist is not None:
if dist.scripts is None:
dist.scripts = []
dist.scripts.extend(scripts)
else:
self.scripts.extend(scripts)
def dict_append(self,**dict):
for key in self.list_keys:
a = getattr(self, key)
a.extend(dict.get(key, []))
for key in self.dict_keys:
a = getattr(self, key)
a.update(dict.get(key, {}))
known_keys = self.list_keys + self.dict_keys + self.extra_keys
for key in dict.keys():
if key not in known_keys:
a = getattr(self, key, None)
if a and a==dict[key]: continue
self.warn('Inheriting attribute %r=%r from %r' \
% (key, dict[key], dict.get('name', '?')))
setattr(self, key, dict[key])
self.extra_keys.append(key)
elif key in self.extra_keys:
self.info('Ignoring attempt to set %r (from %r to %r)' \
% (key, getattr(self, key), dict[key]))
elif key in known_keys:
# key is already processed above
pass
else:
raise ValueError("Don't know about key=%r" % (key))
def __str__(self):
from pprint import pformat
known_keys = self.list_keys + self.dict_keys + self.extra_keys
s = '<'+5*'-' + '\n'
s += 'Configuration of '+self.name+':\n'
known_keys.sort()
for k in known_keys:
a = getattr(self, k, None)
if a:
s += '%s = %s\n' % (k, pformat(a))
s += 5*'-' + '>'
return s
def get_config_cmd(self):
"""
Returns the numpy.distutils config command instance.
"""
cmd = get_cmd('config')
cmd.ensure_finalized()
cmd.dump_source = 0
cmd.noisy = 0
old_path = os.environ.get('PATH')
if old_path:
path = os.pathsep.join(['.', old_path])
os.environ['PATH'] = path
return cmd
def get_build_temp_dir(self):
"""
Return a path to a temporary directory where temporary files should be
placed.
"""
cmd = get_cmd('build')
cmd.ensure_finalized()
return cmd.build_temp
def have_f77c(self):
"""Check for availability of Fortran 77 compiler.
Use it inside source generating function to ensure that
setup distribution instance has been initialized.
Notes
-----
True if a Fortran 77 compiler is available (because a simple Fortran 77
code was able to be compiled successfully).
"""
simple_fortran_subroutine = '''
subroutine simple
end
'''
config_cmd = self.get_config_cmd()
flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77')
return flag
def have_f90c(self):
"""Check for availability of Fortran 90 compiler.
Use it inside source generating function to ensure that
setup distribution instance has been initialized.
Notes
-----
True if a Fortran 90 compiler is available (because a simple Fortran
90 code was able to be compiled successfully)
"""
simple_fortran_subroutine = '''
subroutine simple
end
'''
config_cmd = self.get_config_cmd()
flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90')
return flag
def append_to(self, extlib):
"""Append libraries, include_dirs to extension or library item.
"""
if is_sequence(extlib):
lib_name, build_info = extlib
dict_append(build_info,
libraries=self.libraries,
include_dirs=self.include_dirs)
else:
from numpy.distutils.core import Extension
assert isinstance(extlib, Extension), repr(extlib)
extlib.libraries.extend(self.libraries)
extlib.include_dirs.extend(self.include_dirs)
def _get_svn_revision(self, path):
"""Return path's SVN revision number.
"""
try:
output = subprocess.check_output(['svnversion'], cwd=path)
except (subprocess.CalledProcessError, OSError):
pass
else:
m = re.match(rb'(?P<revision>\d+)', output)
if m:
return int(m.group('revision'))
if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None):
entries = njoin(path, '_svn', 'entries')
else:
entries = njoin(path, '.svn', 'entries')
if os.path.isfile(entries):
with open(entries) as f:
fstr = f.read()
if fstr[:5] == '<?xml': # pre 1.4
m = re.search(r'revision="(?P<revision>\d+)"', fstr)
if m:
return int(m.group('revision'))
else: # non-xml entries file --- check to be sure that
m = re.search(r'dir[\n\r]+(?P<revision>\d+)', fstr)
if m:
return int(m.group('revision'))
return None
def _get_hg_revision(self, path):
"""Return path's Mercurial revision number.
"""
try:
output = subprocess.check_output(
['hg', 'identify', '--num'], cwd=path)
except (subprocess.CalledProcessError, OSError):
pass
else:
m = re.match(rb'(?P<revision>\d+)', output)
if m:
return int(m.group('revision'))
branch_fn = njoin(path, '.hg', 'branch')
branch_cache_fn = njoin(path, '.hg', 'branch.cache')
if os.path.isfile(branch_fn):
branch0 = None
with open(branch_fn) as f:
revision0 = f.read().strip()
branch_map = {}
with open(branch_cache_fn, 'r') as f:
for line in f:
branch1, revision1 = line.split()[:2]
if revision1==revision0:
branch0 = branch1
try:
revision1 = int(revision1)
except ValueError:
continue
branch_map[branch1] = revision1
return branch_map.get(branch0)
return None
def get_version(self, version_file=None, version_variable=None):
"""Try to get version string of a package.
Return a version string of the current package or None if the version
information could not be detected.
Notes
-----
This method scans files named
__version__.py, <packagename>_version.py, version.py, and
__svn_version__.py for string variables version, __version__, and
<packagename>_version, until a version number is found.
"""
version = getattr(self, 'version', None)
if version is not None:
return version
# Get version from version file.
if version_file is None:
files = ['__version__.py',
self.name.split('.')[-1]+'_version.py',
'version.py',
'__svn_version__.py',
'__hg_version__.py']
else:
files = [version_file]
if version_variable is None:
version_vars = ['version',
'__version__',
self.name.split('.')[-1]+'_version']
else:
version_vars = [version_variable]
for f in files:
fn = njoin(self.local_path, f)
if os.path.isfile(fn):
info = ('.py', 'U', 1)
name = os.path.splitext(os.path.basename(fn))[0]
n = dot_join(self.name, name)
try:
version_module = exec_mod_from_location(
'_'.join(n.split('.')), fn)
except ImportError as e:
self.warn(str(e))
version_module = None
if version_module is None:
continue
for a in version_vars:
version = getattr(version_module, a, None)
if version is not None:
break
# Try if versioneer module
try:
version = version_module.get_versions()['version']
except AttributeError:
pass
if version is not None:
break
if version is not None:
self.version = version
return version
# Get version as SVN or Mercurial revision number
revision = self._get_svn_revision(self.local_path)
if revision is None:
revision = self._get_hg_revision(self.local_path)
if revision is not None:
version = str(revision)
self.version = version
return version
def make_svn_version_py(self, delete=True):
"""Appends a data function to the data_files list that will generate
__svn_version__.py file to the current package directory.
Generate package __svn_version__.py file from SVN revision number,
it will be removed after python exits but will be available
when sdist, etc commands are executed.
Notes
-----
If __svn_version__.py existed before, nothing is done.
This is
intended for working with source directories that are in an SVN
repository.
"""
target = njoin(self.local_path, '__svn_version__.py')
revision = self._get_svn_revision(self.local_path)
if os.path.isfile(target) or revision is None:
return
else:
def generate_svn_version_py():
if not os.path.isfile(target):
version = str(revision)
self.info('Creating %s (version=%r)' % (target, version))
with open(target, 'w') as f:
f.write('version = %r\n' % (version))
def rm_file(f=target,p=self.info):
if delete:
try: os.remove(f); p('removed '+f)
except OSError: pass
try: os.remove(f+'c'); p('removed '+f+'c')
except OSError: pass
atexit.register(rm_file)
return target
self.add_data_files(('', generate_svn_version_py()))
def make_hg_version_py(self, delete=True):
"""Appends a data function to the data_files list that will generate
__hg_version__.py file to the current package directory.
Generate package __hg_version__.py file from Mercurial revision,
it will be removed after python exits but will be available
when sdist, etc commands are executed.
Notes
-----
If __hg_version__.py existed before, nothing is done.
This is intended for working with source directories that are
in an Mercurial repository.
"""
target = njoin(self.local_path, '__hg_version__.py')
revision = self._get_hg_revision(self.local_path)
if os.path.isfile(target) or revision is None:
return
else:
def generate_hg_version_py():
if not os.path.isfile(target):
version = str(revision)
self.info('Creating %s (version=%r)' % (target, version))
with open(target, 'w') as f:
f.write('version = %r\n' % (version))
def rm_file(f=target,p=self.info):
if delete:
try: os.remove(f); p('removed '+f)
except OSError: pass
try: os.remove(f+'c'); p('removed '+f+'c')
except OSError: pass
atexit.register(rm_file)
return target
self.add_data_files(('', generate_hg_version_py()))
def make_config_py(self,name='__config__'):
"""Generate package __config__.py file containing system_info
information used during building the package.
This file is installed to the
package installation directory.
"""
self.py_modules.append((self.name, name, generate_config_py))
def get_info(self,*names):
"""Get resources information.
Return information (from system_info.get_info) for all of the names in
the argument list in a single dictionary.
"""
from .system_info import get_info, dict_append
info_dict = {}
for a in names:
dict_append(info_dict,**get_info(a))
return info_dict
import warnings
warnings.warn("\n\n"
" `numpy.distutils` is deprecated since NumPy 1.23.0, as a result\n"
" of the deprecation of `distutils` itself. It will be removed for\n"
" Python >= 3.12. For older Python versions it will remain present.\n"
" It is recommended to use `setuptools < 60.0` for those Python versions.\n"
" For more details, see:\n"
" https://numpy.org/devdocs/reference/distutils_status_migration.html \n\n",
DeprecationWarning, stacklevel=2
)
del warnings
The provided code snippet includes necessary dependencies for implementing the `default_config_dict` function. Write a Python function `def default_config_dict(name = None, parent_name = None, local_path=None)` to solve the following problem:
Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py.
Here is the function:
def default_config_dict(name = None, parent_name = None, local_path=None):
"""Return a configuration dictionary for usage in
configuration() function defined in file setup_<name>.py.
"""
import warnings
warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of '\
'deprecated default_config_dict(%r,%r,%r)'
% (name, parent_name, local_path,
name, parent_name, local_path,
), stacklevel=2)
c = Configuration(name, parent_name, local_path)
return c.todict() | Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py. |
170,313 | import os
import re
import sys
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import multiprocessing
import textwrap
import importlib.util
from threading import local as tlocal
from functools import reduce
import distutils
from distutils.errors import DistutilsError
def njoin(*path):
"""Join two or more pathname components +
- convert a /-separated pathname to one using the OS's path separator.
- resolve `..` and `.` from path.
Either passing n arguments as in njoin('a','b'), or a sequence
of n names as in njoin(['a','b']) is handled, or a mixture of such arguments.
"""
paths = []
for p in path:
if is_sequence(p):
# njoin(['a', 'b'], 'c')
paths.append(njoin(*p))
else:
assert is_string(p)
paths.append(p)
path = paths
if not path:
# njoin()
joined = ''
else:
# njoin('a', 'b')
joined = os.path.join(*path)
if os.path.sep != '/':
joined = joined.replace('/', os.path.sep)
return minrelpath(joined)
def appendpath(prefix, path):
if os.path.sep != '/':
prefix = prefix.replace('/', os.path.sep)
path = path.replace('/', os.path.sep)
drive = ''
if os.path.isabs(path):
drive = os.path.splitdrive(prefix)[0]
absprefix = os.path.splitdrive(os.path.abspath(prefix))[1]
pathdrive, path = os.path.splitdrive(path)
d = os.path.commonprefix([absprefix, path])
if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix \
or os.path.join(path[:len(d)], path[len(d):]) != path:
# Handle invalid paths
d = os.path.dirname(d)
subpath = path[len(d):]
if os.path.isabs(subpath):
subpath = subpath[1:]
else:
subpath = path
return os.path.normpath(njoin(drive + prefix, subpath)) | null |
170,314 | import os
import re
import sys
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import multiprocessing
import textwrap
import importlib.util
from threading import local as tlocal
from functools import reduce
import distutils
from distutils.errors import DistutilsError
class system_info:
""" get_info() is the only public method. Don't use others.
"""
dir_env_var = None
# XXX: search_static_first is disabled by default, may disappear in
# future unless it is proved to be useful.
search_static_first = 0
# The base-class section name is a random word "ALL" and is not really
# intended for general use. It cannot be None nor can it be DEFAULT as
# these break the ConfigParser. See gh-15338
section = 'ALL'
saved_results = {}
notfounderror = NotFoundError
def __init__(self,
default_lib_dirs=default_lib_dirs,
default_include_dirs=default_include_dirs,
):
self.__class__.info = {}
self.local_prefixes = []
defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
'include_dirs': os.pathsep.join(default_include_dirs),
'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
'rpath': '',
'src_dirs': os.pathsep.join(default_src_dirs),
'search_static_first': str(self.search_static_first),
'extra_compile_args': '', 'extra_link_args': ''}
self.cp = ConfigParser(defaults)
self.files = []
self.files.extend(get_standard_file('.numpy-site.cfg'))
self.files.extend(get_standard_file('site.cfg'))
self.parse_config_files()
if self.section is not None:
self.search_static_first = self.cp.getboolean(
self.section, 'search_static_first')
assert isinstance(self.search_static_first, int)
def parse_config_files(self):
self.cp.read(self.files)
if not self.cp.has_section(self.section):
if self.section is not None:
self.cp.add_section(self.section)
def calc_libraries_info(self):
libs = self.get_libraries()
dirs = self.get_lib_dirs()
# The extensions use runtime_library_dirs
r_dirs = self.get_runtime_lib_dirs()
# Intrinsic distutils use rpath, we simply append both entries
# as though they were one entry
r_dirs.extend(self.get_runtime_lib_dirs(key='rpath'))
info = {}
for lib in libs:
i = self.check_libs(dirs, [lib])
if i is not None:
dict_append(info, **i)
else:
log.info('Library %s was not found. Ignoring' % (lib))
if r_dirs:
i = self.check_libs(r_dirs, [lib])
if i is not None:
# Swap library keywords found to runtime_library_dirs
# the libraries are insisting on the user having defined
# them using the library_dirs, and not necessarily by
# runtime_library_dirs
del i['libraries']
i['runtime_library_dirs'] = i.pop('library_dirs')
dict_append(info, **i)
else:
log.info('Runtime library %s was not found. Ignoring' % (lib))
return info
def set_info(self, **info):
if info:
lib_info = self.calc_libraries_info()
dict_append(info, **lib_info)
# Update extra information
extra_info = self.calc_extra_info()
dict_append(info, **extra_info)
self.saved_results[self.__class__.__name__] = info
def get_option_single(self, *options):
""" Ensure that only one of `options` are found in the section
Parameters
----------
*options : list of str
a list of options to be found in the section (``self.section``)
Returns
-------
str :
the option that is uniquely found in the section
Raises
------
AliasedOptionError :
in case more than one of the options are found
"""
found = [self.cp.has_option(self.section, opt) for opt in options]
if sum(found) == 1:
return options[found.index(True)]
elif sum(found) == 0:
# nothing is found anyways
return options[0]
# Else we have more than 1 key found
if AliasedOptionError.__doc__ is None:
raise AliasedOptionError()
raise AliasedOptionError(AliasedOptionError.__doc__.format(
section=self.section, options='[{}]'.format(', '.join(options))))
def has_info(self):
return self.__class__.__name__ in self.saved_results
def calc_extra_info(self):
""" Updates the information in the current information with
respect to these flags:
extra_compile_args
extra_link_args
"""
info = {}
for key in ['extra_compile_args', 'extra_link_args']:
# Get values
opt = self.cp.get(self.section, key)
opt = _shell_utils.NativeParser.split(opt)
if opt:
tmp = {key: opt}
dict_append(info, **tmp)
return info
def get_info(self, notfound_action=0):
""" Return a dictionary with items that are compatible
with numpy.distutils.setup keyword arguments.
"""
flag = 0
if not self.has_info():
flag = 1
log.info(self.__class__.__name__ + ':')
if hasattr(self, 'calc_info'):
self.calc_info()
if notfound_action:
if not self.has_info():
if notfound_action == 1:
warnings.warn(self.notfounderror.__doc__, stacklevel=2)
elif notfound_action == 2:
raise self.notfounderror(self.notfounderror.__doc__)
else:
raise ValueError(repr(notfound_action))
if not self.has_info():
log.info(' NOT AVAILABLE')
self.set_info()
else:
log.info(' FOUND:')
res = self.saved_results.get(self.__class__.__name__)
if log.get_threshold() <= log.INFO and flag:
for k, v in res.items():
v = str(v)
if k in ['sources', 'libraries'] and len(v) > 270:
v = v[:120] + '...\n...\n...' + v[-120:]
log.info(' %s = %s', k, v)
log.info('')
return copy.deepcopy(res)
def get_paths(self, section, key):
dirs = self.cp.get(section, key).split(os.pathsep)
env_var = self.dir_env_var
if env_var:
if is_sequence(env_var):
e0 = env_var[-1]
for e in env_var:
if e in os.environ:
e0 = e
break
if not env_var[0] == e0:
log.info('Setting %s=%s' % (env_var[0], e0))
env_var = e0
if env_var and env_var in os.environ:
d = os.environ[env_var]
if d == 'None':
log.info('Disabled %s: %s',
self.__class__.__name__, '(%s is None)'
% (env_var,))
return []
if os.path.isfile(d):
dirs = [os.path.dirname(d)] + dirs
l = getattr(self, '_lib_names', [])
if len(l) == 1:
b = os.path.basename(d)
b = os.path.splitext(b)[0]
if b[:3] == 'lib':
log.info('Replacing _lib_names[0]==%r with %r' \
% (self._lib_names[0], b[3:]))
self._lib_names[0] = b[3:]
else:
ds = d.split(os.pathsep)
ds2 = []
for d in ds:
if os.path.isdir(d):
ds2.append(d)
for dd in ['include', 'lib']:
d1 = os.path.join(d, dd)
if os.path.isdir(d1):
ds2.append(d1)
dirs = ds2 + dirs
default_dirs = self.cp.get(self.section, key).split(os.pathsep)
dirs.extend(default_dirs)
ret = []
for d in dirs:
if len(d) > 0 and not os.path.isdir(d):
warnings.warn('Specified path %s is invalid.' % d, stacklevel=2)
continue
if d not in ret:
ret.append(d)
log.debug('( %s = %s )', key, ':'.join(ret))
return ret
def get_lib_dirs(self, key='library_dirs'):
return self.get_paths(self.section, key)
def get_runtime_lib_dirs(self, key='runtime_library_dirs'):
path = self.get_paths(self.section, key)
if path == ['']:
path = []
return path
def get_include_dirs(self, key='include_dirs'):
return self.get_paths(self.section, key)
def get_src_dirs(self, key='src_dirs'):
return self.get_paths(self.section, key)
def get_libs(self, key, default):
try:
libs = self.cp.get(self.section, key)
except NoOptionError:
if not default:
return []
if is_string(default):
return [default]
return default
return [b for b in [a.strip() for a in libs.split(',')] if b]
def get_libraries(self, key='libraries'):
if hasattr(self, '_lib_names'):
return self.get_libs(key, default=self._lib_names)
else:
return self.get_libs(key, '')
def library_extensions(self):
c = customized_ccompiler()
static_exts = []
if c.compiler_type != 'msvc':
# MSVC doesn't understand binutils
static_exts.append('.a')
if sys.platform == 'win32':
static_exts.append('.lib') # .lib is used by MSVC and others
if self.search_static_first:
exts = static_exts + [so_ext]
else:
exts = [so_ext] + static_exts
if sys.platform == 'cygwin':
exts.append('.dll.a')
if sys.platform == 'darwin':
exts.append('.dylib')
return exts
def check_libs(self, lib_dirs, libs, opt_libs=[]):
"""If static or shared libraries are available then return
their info dictionary.
Checks for all libraries as shared libraries first, then
static (or vice versa if self.search_static_first is True).
"""
exts = self.library_extensions()
info = None
for ext in exts:
info = self._check_libs(lib_dirs, libs, opt_libs, [ext])
if info is not None:
break
if not info:
log.info(' libraries %s not found in %s', ','.join(libs),
lib_dirs)
return info
def check_libs2(self, lib_dirs, libs, opt_libs=[]):
"""If static or shared libraries are available then return
their info dictionary.
Checks each library for shared or static.
"""
exts = self.library_extensions()
info = self._check_libs(lib_dirs, libs, opt_libs, exts)
if not info:
log.info(' libraries %s not found in %s', ','.join(libs),
lib_dirs)
return info
def _find_lib(self, lib_dir, lib, exts):
assert is_string(lib_dir)
# under windows first try without 'lib' prefix
if sys.platform == 'win32':
lib_prefixes = ['', 'lib']
else:
lib_prefixes = ['lib']
# for each library name, see if we can find a file for it.
for ext in exts:
for prefix in lib_prefixes:
p = self.combine_paths(lib_dir, prefix + lib + ext)
if p:
break
if p:
assert len(p) == 1
# ??? splitext on p[0] would do this for cygwin
# doesn't seem correct
if ext == '.dll.a':
lib += '.dll'
if ext == '.lib':
lib = prefix + lib
return lib
return False
def _find_libs(self, lib_dirs, libs, exts):
# make sure we preserve the order of libs, as it can be important
found_dirs, found_libs = [], []
for lib in libs:
for lib_dir in lib_dirs:
found_lib = self._find_lib(lib_dir, lib, exts)
if found_lib:
found_libs.append(found_lib)
if lib_dir not in found_dirs:
found_dirs.append(lib_dir)
break
return found_dirs, found_libs
def _check_libs(self, lib_dirs, libs, opt_libs, exts):
"""Find mandatory and optional libs in expected paths.
Missing optional libraries are silently forgotten.
"""
if not is_sequence(lib_dirs):
lib_dirs = [lib_dirs]
# First, try to find the mandatory libraries
found_dirs, found_libs = self._find_libs(lib_dirs, libs, exts)
if len(found_libs) > 0 and len(found_libs) == len(libs):
# Now, check for optional libraries
opt_found_dirs, opt_found_libs = self._find_libs(lib_dirs, opt_libs, exts)
found_libs.extend(opt_found_libs)
for lib_dir in opt_found_dirs:
if lib_dir not in found_dirs:
found_dirs.append(lib_dir)
info = {'libraries': found_libs, 'library_dirs': found_dirs}
return info
else:
return None
def combine_paths(self, *args):
"""Return a list of existing paths composed by all combinations
of items from the arguments.
"""
return combine_paths(*args)
The provided code snippet includes necessary dependencies for implementing the `generate_config_py` function. Write a Python function `def generate_config_py(target)` to solve the following problem:
Generate config.py file containing system_info information used during building the package. Usage: config['py_modules'].append((packagename, '__config__',generate_config_py))
Here is the function:
def generate_config_py(target):
"""Generate config.py file containing system_info information
used during building the package.
Usage:
config['py_modules'].append((packagename, '__config__',generate_config_py))
"""
from numpy.distutils.system_info import system_info
from distutils.dir_util import mkpath
mkpath(os.path.dirname(target))
with open(target, 'w') as f:
f.write('# This file is generated by numpy\'s %s\n' % (os.path.basename(sys.argv[0])))
f.write('# It contains system_info results at the time of building this package.\n')
f.write('__all__ = ["get_info","show"]\n\n')
# For gfortran+msvc combination, extra shared libraries may exist
f.write(textwrap.dedent("""
import os
import sys
extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')
if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):
os.add_dll_directory(extra_dll_dir)
"""))
for k, i in system_info.saved_results.items():
f.write('%s=%r\n' % (k, i))
f.write(textwrap.dedent(r'''
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {}))
def show():
"""
Show libraries in the system on which NumPy was built.
Print information about various resources (libraries, library
directories, include directories, etc.) in the system on which
NumPy was built.
See Also
--------
get_include : Returns the directory containing NumPy C
header files.
Notes
-----
1. Classes specifying the information to be printed are defined
in the `numpy.distutils.system_info` module.
Information may include:
* ``language``: language used to write the libraries (mostly
C or f77)
* ``libraries``: names of libraries found in the system
* ``library_dirs``: directories containing the libraries
* ``include_dirs``: directories containing library header files
* ``src_dirs``: directories containing library source files
* ``define_macros``: preprocessor macros used by
``distutils.setup``
* ``baseline``: minimum CPU features required
* ``found``: dispatched features supported in the system
* ``not found``: dispatched features that are not supported
in the system
2. NumPy BLAS/LAPACK Installation Notes
Installing a numpy wheel (``pip install numpy`` or force it
via ``pip install numpy --only-binary :numpy: numpy``) includes
an OpenBLAS implementation of the BLAS and LAPACK linear algebra
APIs. In this case, ``library_dirs`` reports the original build
time configuration as compiled with gcc/gfortran; at run time
the OpenBLAS library is in
``site-packages/numpy.libs/`` (linux), or
``site-packages/numpy/.dylibs/`` (macOS), or
``site-packages/numpy/.libs/`` (windows).
Installing numpy from source
(``pip install numpy --no-binary numpy``) searches for BLAS and
LAPACK dynamic link libraries at build time as influenced by
environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and
NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER;
or the optional file ``~/.numpy-site.cfg``.
NumPy remembers those locations and expects to load the same
libraries at run-time.
In NumPy 1.21+ on macOS, 'accelerate' (Apple's Accelerate BLAS
library) is in the default build-time search order after
'openblas'.
Examples
--------
>>> import numpy as np
>>> np.show_config()
blas_opt_info:
language = c
define_macros = [('HAVE_CBLAS', None)]
libraries = ['openblas', 'openblas']
library_dirs = ['/usr/local/lib']
"""
from numpy.core._multiarray_umath import (
__cpu_features__, __cpu_baseline__, __cpu_dispatch__
)
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not type({}): continue
print(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
features_found, features_not_found = [], []
for feature in __cpu_dispatch__:
if __cpu_features__[feature]:
features_found.append(feature)
else:
features_not_found.append(feature)
print("Supported SIMD extensions in this NumPy install:")
print(" baseline = %s" % (','.join(__cpu_baseline__)))
print(" found = %s" % (','.join(features_found)))
print(" not found = %s" % (','.join(features_not_found)))
'''))
return target | Generate config.py file containing system_info information used during building the package. Usage: config['py_modules'].append((packagename, '__config__',generate_config_py)) |
170,315 | import os
import re
import sys
import copy
import glob
import atexit
import tempfile
import subprocess
import shutil
import multiprocessing
import textwrap
import importlib.util
from threading import local as tlocal
from functools import reduce
import distutils
from distutils.errors import DistutilsError
The provided code snippet includes necessary dependencies for implementing the `msvc_version` function. Write a Python function `def msvc_version(compiler)` to solve the following problem:
Return version major and minor of compiler instance if it is MSVC, raise an exception otherwise.
Here is the function:
def msvc_version(compiler):
"""Return version major and minor of compiler instance if it is
MSVC, raise an exception otherwise."""
if not compiler.compiler_type == "msvc":
raise ValueError("Compiler instance is not msvc (%s)"\
% compiler.compiler_type)
return compiler._MSVCCompiler__version | Return version major and minor of compiler instance if it is MSVC, raise an exception otherwise. |
170,316 | import re
import sys
import subprocess
py_ver = "%d%d" % tuple(sys.version_info[:2])
The provided code snippet includes necessary dependencies for implementing the `parse_cmd` function. Write a Python function `def parse_cmd()` to solve the following problem:
Parses the command-line arguments. libfile, deffile = parse_cmd()
Here is the function:
def parse_cmd():
"""Parses the command-line arguments.
libfile, deffile = parse_cmd()"""
if len(sys.argv) == 3:
if sys.argv[1][-4:] == '.lib' and sys.argv[2][-4:] == '.def':
libfile, deffile = sys.argv[1:]
elif sys.argv[1][-4:] == '.def' and sys.argv[2][-4:] == '.lib':
deffile, libfile = sys.argv[1:]
else:
print("I'm assuming that your first argument is the library")
print("and the second is the DEF file.")
elif len(sys.argv) == 2:
if sys.argv[1][-4:] == '.def':
deffile = sys.argv[1]
libfile = 'python%s.lib' % py_ver
elif sys.argv[1][-4:] == '.lib':
deffile = None
libfile = sys.argv[1]
else:
libfile = 'python%s.lib' % py_ver
deffile = None
return libfile, deffile | Parses the command-line arguments. libfile, deffile = parse_cmd() |
170,317 | import os
import re
import sys
import shlex
import copy
from distutils.command import build_ext
from distutils.dep_util import newer_group, newer
from distutils.util import get_platform
from distutils.errors import DistutilsError, DistutilsSetupError
from numpy.distutils import log
from numpy.distutils.misc_util import (
fortran_ext_match, appendpath, is_string, is_sequence, get_cmd
)
from numpy.distutils.from_template import process_file as process_f_file
from numpy.distutils.conv_template import process_file as process_c_file
The provided code snippet includes necessary dependencies for implementing the `subst_vars` function. Write a Python function `def subst_vars(target, source, d)` to solve the following problem:
Substitute any occurrence of @foo@ by d['foo'] from source file into target.
Here is the function:
def subst_vars(target, source, d):
"""Substitute any occurrence of @foo@ by d['foo'] from source file into
target."""
var = re.compile('@([a-zA-Z_]+)@')
with open(source, 'r') as fs:
with open(target, 'w') as ft:
for l in fs:
m = var.search(l)
if m:
ft.write(l.replace('@%s@' % m.group(1), d[m.group(1)]))
else:
ft.write(l) | Substitute any occurrence of @foo@ by d['foo'] from source file into target. |
170,318 | import os
import re
import sys
import shlex
import copy
from distutils.command import build_ext
from distutils.dep_util import newer_group, newer
from distutils.util import get_platform
from distutils.errors import DistutilsError, DistutilsSetupError
from numpy.distutils import log
from numpy.distutils.misc_util import (
fortran_ext_match, appendpath, is_string, is_sequence, get_cmd
)
from numpy.distutils.from_template import process_file as process_f_file
from numpy.distutils.conv_template import process_file as process_c_file
_has_c_header = re.compile(r'-\*-\s*c\s*-\*-', re.I).search
_has_cpp_header = re.compile(r'-\*-\s*c\+\+\s*-\*-', re.I).search
def get_swig_target(source):
with open(source, 'r') as f:
result = None
line = f.readline()
if _has_cpp_header(line):
result = 'c++'
if _has_c_header(line):
result = 'c'
return result | null |
170,319 | import os
import re
import sys
import shlex
import copy
from distutils.command import build_ext
from distutils.dep_util import newer_group, newer
from distutils.util import get_platform
from distutils.errors import DistutilsError, DistutilsSetupError
from numpy.distutils import log
from numpy.distutils.misc_util import (
fortran_ext_match, appendpath, is_string, is_sequence, get_cmd
)
from numpy.distutils.from_template import process_file as process_f_file
from numpy.distutils.conv_template import process_file as process_c_file
_swig_module_name_match = re.compile(r'\s*%module\s*(.*\(\s*package\s*=\s*"(?P<package>[\w_]+)".*\)|)\s*(?P<name>[\w_]+)',
re.I).match
def get_swig_modulename(source):
with open(source, 'r') as f:
name = None
for line in f:
m = _swig_module_name_match(line)
if m:
name = m.group('name')
break
return name | null |
170,320 | import os
import re
import sys
import shlex
import copy
from distutils.command import build_ext
from distutils.dep_util import newer_group, newer
from distutils.util import get_platform
from distutils.errors import DistutilsError, DistutilsSetupError
from numpy.distutils import log
from numpy.distutils.misc_util import (
fortran_ext_match, appendpath, is_string, is_sequence, get_cmd
)
from numpy.distutils.from_template import process_file as process_f_file
from numpy.distutils.conv_template import process_file as process_c_file
def _find_swig_target(target_dir, name):
for ext in ['.cpp', '.c']:
target = os.path.join(target_dir, '%s_wrap%s' % (name, ext))
if os.path.isfile(target):
break
return target | null |
170,321 | from distutils.core import Command
from numpy.distutils import log
def show_fcompilers(dist=None):
"""Print list of available compilers (used by the "--help-fcompiler"
option to "config_fc").
"""
if dist is None:
from distutils.dist import Distribution
from numpy.distutils.command.config_compiler import config_fc
dist = Distribution()
dist.script_name = os.path.basename(sys.argv[0])
dist.script_args = ['config_fc'] + sys.argv[1:]
try:
dist.script_args.remove('--help-fcompiler')
except ValueError:
pass
dist.cmdclass['config_fc'] = config_fc
dist.parse_config_files()
dist.parse_command_line()
compilers = []
compilers_na = []
compilers_ni = []
if not fcompiler_class:
load_all_fcompiler_classes()
platform_compilers = available_fcompilers_for_platform()
for compiler in platform_compilers:
v = None
log.set_verbosity(-2)
try:
c = new_fcompiler(compiler=compiler, verbose=dist.verbose)
c.customize(dist)
v = c.get_version()
except (DistutilsModuleError, CompilerNotFound) as e:
log.debug("show_fcompilers: %s not found" % (compiler,))
log.debug(repr(e))
if v is None:
compilers_na.append(("fcompiler="+compiler, None,
fcompiler_class[compiler][2]))
else:
c.dump_properties()
compilers.append(("fcompiler="+compiler, None,
fcompiler_class[compiler][2] + ' (%s)' % v))
compilers_ni = list(set(fcompiler_class.keys()) - set(platform_compilers))
compilers_ni = [("fcompiler="+fc, None, fcompiler_class[fc][2])
for fc in compilers_ni]
compilers.sort()
compilers_na.sort()
compilers_ni.sort()
pretty_printer = FancyGetopt(compilers)
pretty_printer.print_help("Fortran compilers found:")
pretty_printer = FancyGetopt(compilers_na)
pretty_printer.print_help("Compilers available for this "
"platform, but not found:")
if compilers_ni:
pretty_printer = FancyGetopt(compilers_ni)
pretty_printer.print_help("Compilers not available on this platform:")
print("For compiler details, run 'config_fc --verbose' setup command.")
def show_fortran_compilers(_cache=None):
# Using cache to prevent infinite recursion.
if _cache:
return
elif _cache is None:
_cache = []
_cache.append(1)
from numpy.distutils.fcompiler import show_fcompilers
import distutils.core
dist = distutils.core._setup_distribution
show_fcompilers(dist) | null |
170,322 | import textwrap
The provided code snippet includes necessary dependencies for implementing the `check_inline` function. Write a Python function `def check_inline(cmd)` to solve the following problem:
Return the inline identifier (may be empty).
Here is the function:
def check_inline(cmd):
"""Return the inline identifier (may be empty)."""
cmd._check_compiler()
body = textwrap.dedent("""
#ifndef __cplusplus
static %(inline)s int static_func (void)
{
return 0;
}
%(inline)s int nostatic_func (void)
{
return 0;
}
#endif""")
for kw in ['inline', '__inline__', '__inline']:
st = cmd.try_compile(body % {'inline': kw}, None, None)
if st:
return kw
return '' | Return the inline identifier (may be empty). |
170,323 | import textwrap
The provided code snippet includes necessary dependencies for implementing the `check_restrict` function. Write a Python function `def check_restrict(cmd)` to solve the following problem:
Return the restrict identifier (may be empty).
Here is the function:
def check_restrict(cmd):
"""Return the restrict identifier (may be empty)."""
cmd._check_compiler()
body = textwrap.dedent("""
static int static_func (char * %(restrict)s a)
{
return 0;
}
""")
for kw in ['restrict', '__restrict__', '__restrict']:
st = cmd.try_compile(body % {'restrict': kw}, None, None)
if st:
return kw
return '' | Return the restrict identifier (may be empty). |
170,324 | import textwrap
The provided code snippet includes necessary dependencies for implementing the `check_compiler_gcc` function. Write a Python function `def check_compiler_gcc(cmd)` to solve the following problem:
Check if the compiler is GCC.
Here is the function:
def check_compiler_gcc(cmd):
"""Check if the compiler is GCC."""
cmd._check_compiler()
body = textwrap.dedent("""
int
main()
{
#if (! defined __GNUC__)
#error gcc required
#endif
return 0;
}
""")
return cmd.try_compile(body, None, None) | Check if the compiler is GCC. |
170,325 | import textwrap
The provided code snippet includes necessary dependencies for implementing the `check_gcc_version_at_least` function. Write a Python function `def check_gcc_version_at_least(cmd, major, minor=0, patchlevel=0)` to solve the following problem:
Check that the gcc version is at least the specified version.
Here is the function:
def check_gcc_version_at_least(cmd, major, minor=0, patchlevel=0):
"""
Check that the gcc version is at least the specified version."""
cmd._check_compiler()
version = '.'.join([str(major), str(minor), str(patchlevel)])
body = textwrap.dedent("""
int
main()
{
#if (! defined __GNUC__) || (__GNUC__ < %(major)d) || \\
(__GNUC_MINOR__ < %(minor)d) || \\
(__GNUC_PATCHLEVEL__ < %(patchlevel)d)
#error gcc >= %(version)s required
#endif
return 0;
}
""")
kw = {'version': version, 'major': major, 'minor': minor,
'patchlevel': patchlevel}
return cmd.try_compile(body % kw, None, None) | Check that the gcc version is at least the specified version. |
170,326 | import textwrap
The provided code snippet includes necessary dependencies for implementing the `check_gcc_function_attribute` function. Write a Python function `def check_gcc_function_attribute(cmd, attribute, name)` to solve the following problem:
Return True if the given function attribute is supported.
Here is the function:
def check_gcc_function_attribute(cmd, attribute, name):
"""Return True if the given function attribute is supported."""
cmd._check_compiler()
body = textwrap.dedent("""
#pragma GCC diagnostic error "-Wattributes"
#pragma clang diagnostic error "-Wattributes"
int %s %s(void* unused)
{
return 0;
}
int
main()
{
return 0;
}
""") % (attribute, name)
return cmd.try_compile(body, None, None) != 0 | Return True if the given function attribute is supported. |
170,327 | import textwrap
The provided code snippet includes necessary dependencies for implementing the `check_gcc_function_attribute_with_intrinsics` function. Write a Python function `def check_gcc_function_attribute_with_intrinsics(cmd, attribute, name, code, include)` to solve the following problem:
Return True if the given function attribute is supported with intrinsics.
Here is the function:
def check_gcc_function_attribute_with_intrinsics(cmd, attribute, name, code,
include):
"""Return True if the given function attribute is supported with
intrinsics."""
cmd._check_compiler()
body = textwrap.dedent("""
#include<%s>
int %s %s(void)
{
%s;
return 0;
}
int
main()
{
return 0;
}
""") % (include, attribute, name, code)
return cmd.try_compile(body, None, None) != 0 | Return True if the given function attribute is supported with intrinsics. |
170,328 | import textwrap
The provided code snippet includes necessary dependencies for implementing the `check_gcc_variable_attribute` function. Write a Python function `def check_gcc_variable_attribute(cmd, attribute)` to solve the following problem:
Return True if the given variable attribute is supported.
Here is the function:
def check_gcc_variable_attribute(cmd, attribute):
"""Return True if the given variable attribute is supported."""
cmd._check_compiler()
body = textwrap.dedent("""
#pragma GCC diagnostic error "-Wattributes"
#pragma clang diagnostic error "-Wattributes"
int %s foo;
int
main()
{
return 0;
}
""") % (attribute, )
return cmd.try_compile(body, None, None) != 0 | Return True if the given variable attribute is supported. |
170,329 | import sys
import os
import re
import copy
import warnings
import subprocess
import textwrap
from glob import glob
from functools import reduce
from configparser import NoOptionError
from configparser import RawConfigParser as ConfigParser
from distutils.errors import DistutilsError
from distutils.dist import Distribution
import sysconfig
from numpy.distutils import log
from distutils.util import get_platform
from numpy.distutils.exec_command import (
find_executable, filepath_from_subprocess_output,
)
from numpy.distutils.misc_util import (is_sequence, is_string,
get_shared_lib_extension)
from numpy.distutils.command.config import config as cmd_config
from numpy.distutils import customized_ccompiler as _customized_ccompiler
from numpy.distutils import _shell_utils
import distutils.ccompiler
import tempfile
import shutil
import platform
global_compiler = None
def customized_ccompiler():
global global_compiler
if not global_compiler:
global_compiler = _customized_ccompiler()
return global_compiler | null |
170,330 | import sys
import os
import re
import copy
import warnings
import subprocess
import textwrap
from glob import glob
from functools import reduce
from configparser import NoOptionError
from configparser import RawConfigParser as ConfigParser
from distutils.errors import DistutilsError
from distutils.dist import Distribution
import sysconfig
from numpy.distutils import log
from distutils.util import get_platform
from numpy.distutils.exec_command import (
find_executable, filepath_from_subprocess_output,
)
from numpy.distutils.misc_util import (is_sequence, is_string,
get_shared_lib_extension)
from numpy.distutils.command.config import config as cmd_config
from numpy.distutils import customized_ccompiler as _customized_ccompiler
from numpy.distutils import _shell_utils
import distutils.ccompiler
import tempfile
import shutil
import platform
The provided code snippet includes necessary dependencies for implementing the `libpaths` function. Write a Python function `def libpaths(paths, bits)` to solve the following problem:
Return a list of library paths valid on 32 or 64 bit systems. Inputs: paths : sequence A sequence of strings (typically paths) bits : int An integer, the only valid values are 32 or 64. A ValueError exception is raised otherwise. Examples: Consider a list of directories >>> paths = ['/usr/X11R6/lib','/usr/X11/lib','/usr/lib'] For a 32-bit platform, this is already valid: >>> np.distutils.system_info.libpaths(paths,32) ['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib'] On 64 bits, we prepend the '64' postfix >>> np.distutils.system_info.libpaths(paths,64) ['/usr/X11R6/lib64', '/usr/X11R6/lib', '/usr/X11/lib64', '/usr/X11/lib', '/usr/lib64', '/usr/lib']
Here is the function:
def libpaths(paths, bits):
"""Return a list of library paths valid on 32 or 64 bit systems.
Inputs:
paths : sequence
A sequence of strings (typically paths)
bits : int
An integer, the only valid values are 32 or 64. A ValueError exception
is raised otherwise.
Examples:
Consider a list of directories
>>> paths = ['/usr/X11R6/lib','/usr/X11/lib','/usr/lib']
For a 32-bit platform, this is already valid:
>>> np.distutils.system_info.libpaths(paths,32)
['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib']
On 64 bits, we prepend the '64' postfix
>>> np.distutils.system_info.libpaths(paths,64)
['/usr/X11R6/lib64', '/usr/X11R6/lib', '/usr/X11/lib64', '/usr/X11/lib',
'/usr/lib64', '/usr/lib']
"""
if bits not in (32, 64):
raise ValueError("Invalid bit size in libpaths: 32 or 64 only")
# Handle 32bit case
if bits == 32:
return paths
# Handle 64bit case
out = []
for p in paths:
out.extend([p + '64', p])
return out | Return a list of library paths valid on 32 or 64 bit systems. Inputs: paths : sequence A sequence of strings (typically paths) bits : int An integer, the only valid values are 32 or 64. A ValueError exception is raised otherwise. Examples: Consider a list of directories >>> paths = ['/usr/X11R6/lib','/usr/X11/lib','/usr/lib'] For a 32-bit platform, this is already valid: >>> np.distutils.system_info.libpaths(paths,32) ['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib'] On 64 bits, we prepend the '64' postfix >>> np.distutils.system_info.libpaths(paths,64) ['/usr/X11R6/lib64', '/usr/X11R6/lib', '/usr/X11/lib64', '/usr/X11/lib', '/usr/lib64', '/usr/lib'] |
170,331 | import sys
import os
import re
import copy
import warnings
import subprocess
import textwrap
from glob import glob
from functools import reduce
from configparser import NoOptionError
from configparser import RawConfigParser as ConfigParser
from distutils.errors import DistutilsError
from distutils.dist import Distribution
import sysconfig
from numpy.distutils import log
from distutils.util import get_platform
from numpy.distutils.exec_command import (
find_executable, filepath_from_subprocess_output,
)
from numpy.distutils.misc_util import (is_sequence, is_string,
get_shared_lib_extension)
from numpy.distutils.command.config import config as cmd_config
from numpy.distutils import customized_ccompiler as _customized_ccompiler
from numpy.distutils import _shell_utils
import distutils.ccompiler
import tempfile
import shutil
import platform
if os.path.join(sys.prefix, 'lib') not in default_lib_dirs:
default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib'))
default_include_dirs.append(os.path.join(sys.prefix, 'include'))
default_src_dirs.append(os.path.join(sys.prefix, 'src'))
default_lib_dirs = [_m for _m in default_lib_dirs if os.path.isdir(_m)]
default_include_dirs = [_m for _m in default_include_dirs if os.path.isdir(_m)]
The provided code snippet includes necessary dependencies for implementing the `add_system_root` function. Write a Python function `def add_system_root(library_root)` to solve the following problem:
Add a package manager root to the include directories
Here is the function:
def add_system_root(library_root):
"""Add a package manager root to the include directories"""
global default_lib_dirs
global default_include_dirs
library_root = os.path.normpath(library_root)
default_lib_dirs.extend(
os.path.join(library_root, d) for d in _lib_dirs)
default_include_dirs.extend(
os.path.join(library_root, d) for d in _include_dirs) | Add a package manager root to the include directories |
170,332 | import sys
import os
import re
import copy
import warnings
import subprocess
import textwrap
from glob import glob
from functools import reduce
from configparser import NoOptionError
from configparser import RawConfigParser as ConfigParser
from distutils.errors import DistutilsError
from distutils.dist import Distribution
import sysconfig
from numpy.distutils import log
from distutils.util import get_platform
from numpy.distutils.exec_command import (
find_executable, filepath_from_subprocess_output,
)
from numpy.distutils.misc_util import (is_sequence, is_string,
get_shared_lib_extension)
from numpy.distutils.command.config import config as cmd_config
from numpy.distutils import customized_ccompiler as _customized_ccompiler
from numpy.distutils import _shell_utils
import distutils.ccompiler
import tempfile
import shutil
import platform
if sys.platform == 'win32':
default_lib_dirs = ['C:\\',
os.path.join(sysconfig.get_config_var('exec_prefix'),
'libs')]
default_runtime_dirs = []
default_include_dirs = []
default_src_dirs = ['.']
default_x11_lib_dirs = []
default_x11_include_dirs = []
_include_dirs = [
'include',
'include/suitesparse',
]
_lib_dirs = [
'lib',
]
_include_dirs = [d.replace('/', os.sep) for d in _include_dirs]
_lib_dirs = [d.replace('/', os.sep) for d in _lib_dirs]
# VCpkg is the de-facto package manager on windows for C/C++
# libraries. If it is on the PATH, then we append its paths here.
vcpkg = shutil.which('vcpkg')
if vcpkg:
vcpkg_dir = os.path.dirname(vcpkg)
if platform.architecture()[0] == '32bit':
specifier = 'x86'
else:
specifier = 'x64'
vcpkg_installed = os.path.join(vcpkg_dir, 'installed')
for vcpkg_root in [
os.path.join(vcpkg_installed, specifier + '-windows'),
os.path.join(vcpkg_installed, specifier + '-windows-static'),
]:
add_system_root(vcpkg_root)
# Conda is another popular package manager that provides libraries
conda = shutil.which('conda')
if conda:
conda_dir = os.path.dirname(conda)
add_system_root(os.path.join(conda_dir, '..', 'Library'))
add_system_root(os.path.join(conda_dir, 'Library'))
else:
default_lib_dirs = libpaths(['/usr/local/lib', '/opt/lib', '/usr/lib',
'/opt/local/lib', '/sw/lib'], platform_bits)
default_runtime_dirs = []
default_include_dirs = ['/usr/local/include',
'/opt/include',
# path of umfpack under macports
'/opt/local/include/ufsparse',
'/opt/local/include', '/sw/include',
'/usr/include/suitesparse']
default_src_dirs = ['.', '/usr/local/src', '/opt/src', '/sw/src']
default_x11_lib_dirs = libpaths(['/usr/X11R6/lib', '/usr/X11/lib',
'/usr/lib'], platform_bits)
default_x11_include_dirs = ['/usr/X11R6/include', '/usr/X11/include']
if os.path.exists('/usr/lib/X11'):
globbed_x11_dir = glob('/usr/lib/*/libX11.so')
if globbed_x11_dir:
x11_so_dir = os.path.split(globbed_x11_dir[0])[0]
default_x11_lib_dirs.extend([x11_so_dir, '/usr/lib/X11'])
default_x11_include_dirs.extend(['/usr/lib/X11/include',
'/usr/include/X11'])
with open(os.devnull, 'w') as tmp:
try:
p = subprocess.Popen(["gcc", "-print-multiarch"], stdout=subprocess.PIPE,
stderr=tmp)
except (OSError, DistutilsError):
# OSError if gcc is not installed, or SandboxViolation (DistutilsError
# subclass) if an old setuptools bug is triggered (see gh-3160).
pass
else:
triplet = str(p.communicate()[0].decode().strip())
if p.returncode == 0:
# gcc supports the "-print-multiarch" option
default_x11_lib_dirs += [os.path.join("/usr/lib/", triplet)]
default_lib_dirs += [os.path.join("/usr/lib/", triplet)]
if os.path.join(sys.prefix, 'lib') not in default_lib_dirs:
default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib'))
default_include_dirs.append(os.path.join(sys.prefix, 'include'))
default_src_dirs.append(os.path.join(sys.prefix, 'src'))
The provided code snippet includes necessary dependencies for implementing the `get_standard_file` function. Write a Python function `def get_standard_file(fname)` to solve the following problem:
Returns a list of files named 'fname' from 1) System-wide directory (directory-location of this module) 2) Users HOME directory (os.environ['HOME']) 3) Local directory
Here is the function:
def get_standard_file(fname):
"""Returns a list of files named 'fname' from
1) System-wide directory (directory-location of this module)
2) Users HOME directory (os.environ['HOME'])
3) Local directory
"""
# System-wide file
filenames = []
try:
f = __file__
except NameError:
f = sys.argv[0]
sysfile = os.path.join(os.path.split(os.path.abspath(f))[0],
fname)
if os.path.isfile(sysfile):
filenames.append(sysfile)
# Home directory
# And look for the user config file
try:
f = os.path.expanduser('~')
except KeyError:
pass
else:
user_file = os.path.join(f, fname)
if os.path.isfile(user_file):
filenames.append(user_file)
# Local file
if os.path.isfile(fname):
filenames.append(os.path.abspath(fname))
return filenames | Returns a list of files named 'fname' from 1) System-wide directory (directory-location of this module) 2) Users HOME directory (os.environ['HOME']) 3) Local directory |
170,333 | import sys
import os
import re
import copy
import warnings
import subprocess
import textwrap
from glob import glob
from functools import reduce
from configparser import NoOptionError
from configparser import RawConfigParser as ConfigParser
from distutils.errors import DistutilsError
from distutils.dist import Distribution
import sysconfig
from numpy.distutils import log
from distutils.util import get_platform
from numpy.distutils.exec_command import (
find_executable, filepath_from_subprocess_output,
)
from numpy.distutils.misc_util import (is_sequence, is_string,
get_shared_lib_extension)
from numpy.distutils.command.config import config as cmd_config
from numpy.distutils import customized_ccompiler as _customized_ccompiler
from numpy.distutils import _shell_utils
import distutils.ccompiler
import tempfile
import shutil
import platform
if os.path.join(sys.prefix, 'lib') not in default_lib_dirs:
default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib'))
default_include_dirs.append(os.path.join(sys.prefix, 'include'))
default_src_dirs.append(os.path.join(sys.prefix, 'src'))
The provided code snippet includes necessary dependencies for implementing the `_parse_env_order` function. Write a Python function `def _parse_env_order(base_order, env)` to solve the following problem:
Parse an environment variable `env` by splitting with "," and only returning elements from `base_order` This method will sequence the environment variable and check for their individual elements in `base_order`. The items in the environment variable may be negated via '^item' or '!itema,itemb'. It must start with ^/! to negate all options. Raises ------ ValueError: for mixed negated and non-negated orders or multiple negated orders Parameters ---------- base_order : list of str the base list of orders env : str the environment variable to be parsed, if none is found, `base_order` is returned Returns ------- allow_order : list of str allowed orders in lower-case unknown_order : list of str for values not overlapping with `base_order`
Here is the function:
def _parse_env_order(base_order, env):
""" Parse an environment variable `env` by splitting with "," and only returning elements from `base_order`
This method will sequence the environment variable and check for their
individual elements in `base_order`.
The items in the environment variable may be negated via '^item' or '!itema,itemb'.
It must start with ^/! to negate all options.
Raises
------
ValueError: for mixed negated and non-negated orders or multiple negated orders
Parameters
----------
base_order : list of str
the base list of orders
env : str
the environment variable to be parsed, if none is found, `base_order` is returned
Returns
-------
allow_order : list of str
allowed orders in lower-case
unknown_order : list of str
for values not overlapping with `base_order`
"""
order_str = os.environ.get(env, None)
# ensure all base-orders are lower-case (for easier comparison)
base_order = [order.lower() for order in base_order]
if order_str is None:
return base_order, []
neg = order_str.startswith('^') or order_str.startswith('!')
# Check format
order_str_l = list(order_str)
sum_neg = order_str_l.count('^') + order_str_l.count('!')
if neg:
if sum_neg > 1:
raise ValueError(f"Environment variable '{env}' may only contain a single (prefixed) negation: {order_str}")
# remove prefix
order_str = order_str[1:]
elif sum_neg > 0:
raise ValueError(f"Environment variable '{env}' may not mix negated an non-negated items: {order_str}")
# Split and lower case
orders = order_str.lower().split(',')
# to inform callee about non-overlapping elements
unknown_order = []
# if negated, we have to remove from the order
if neg:
allow_order = base_order.copy()
for order in orders:
if not order:
continue
if order not in base_order:
unknown_order.append(order)
continue
if order in allow_order:
allow_order.remove(order)
else:
allow_order = []
for order in orders:
if not order:
continue
if order not in base_order:
unknown_order.append(order)
continue
if order not in allow_order:
allow_order.append(order)
return allow_order, unknown_order | Parse an environment variable `env` by splitting with "," and only returning elements from `base_order` This method will sequence the environment variable and check for their individual elements in `base_order`. The items in the environment variable may be negated via '^item' or '!itema,itemb'. It must start with ^/! to negate all options. Raises ------ ValueError: for mixed negated and non-negated orders or multiple negated orders Parameters ---------- base_order : list of str the base list of orders env : str the environment variable to be parsed, if none is found, `base_order` is returned Returns ------- allow_order : list of str allowed orders in lower-case unknown_order : list of str for values not overlapping with `base_order` |
170,334 | import sys
import os
import re
import copy
import warnings
import subprocess
import textwrap
from glob import glob
from functools import reduce
from configparser import NoOptionError
from configparser import RawConfigParser as ConfigParser
from distutils.errors import DistutilsError
from distutils.dist import Distribution
import sysconfig
from numpy.distutils import log
from distutils.util import get_platform
from numpy.distutils.exec_command import (
find_executable, filepath_from_subprocess_output,
)
from numpy.distutils.misc_util import (is_sequence, is_string,
get_shared_lib_extension)
from numpy.distutils.command.config import config as cmd_config
from numpy.distutils import customized_ccompiler as _customized_ccompiler
from numpy.distutils import _shell_utils
import distutils.ccompiler
import tempfile
import shutil
import platform
def _c_string_literal(s):
"""
Convert a python string into a literal suitable for inclusion into C code
"""
# only these three characters are forbidden in C strings
s = s.replace('\\', r'\\')
s = s.replace('"', r'\"')
s = s.replace('\n', r'\n')
return '"{}"'.format(s)
if os.path.join(sys.prefix, 'lib') not in default_lib_dirs:
default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib'))
default_include_dirs.append(os.path.join(sys.prefix, 'include'))
default_src_dirs.append(os.path.join(sys.prefix, 'src'))
atlas_version_c_text = r'''
/* This file is generated from numpy/distutils/system_info.py */
void ATL_buildinfo(void);
int main(void) {
ATL_buildinfo();
return 0;
}
'''
_cached_atlas_version = {}
def dict_append(d, **kws):
languages = []
for k, v in kws.items():
if k == 'language':
languages.append(v)
continue
if k in d:
if k in ['library_dirs', 'include_dirs',
'extra_compile_args', 'extra_link_args',
'runtime_library_dirs', 'define_macros']:
[d[k].append(vv) for vv in v if vv not in d[k]]
else:
d[k].extend(v)
else:
d[k] = v
if languages:
l = inv_language_map[max([language_map.get(l, 0) for l in languages])]
d['language'] = l
return
import warnings
warnings.warn("\n\n"
" `numpy.distutils` is deprecated since NumPy 1.23.0, as a result\n"
" of the deprecation of `distutils` itself. It will be removed for\n"
" Python >= 3.12. For older Python versions it will remain present.\n"
" It is recommended to use `setuptools < 60.0` for those Python versions.\n"
" For more details, see:\n"
" https://numpy.org/devdocs/reference/distutils_status_migration.html \n\n",
DeprecationWarning, stacklevel=2
)
del warnings
class config(old_config):
old_config.user_options += [
('fcompiler=', None, "specify the Fortran compiler type"),
]
def initialize_options(self):
self.fcompiler = None
old_config.initialize_options(self)
def _check_compiler (self):
old_config._check_compiler(self)
from numpy.distutils.fcompiler import FCompiler, new_fcompiler
if sys.platform == 'win32' and (self.compiler.compiler_type in
('msvc', 'intelw', 'intelemw')):
# XXX: hack to circumvent a python 2.6 bug with msvc9compiler:
# initialize call query_vcvarsall, which throws an IOError, and
# causes an error along the way without much information. We try to
# catch it here, hoping it is early enough, and print a helpful
# message instead of Error: None.
if not self.compiler.initialized:
try:
self.compiler.initialize()
except IOError as e:
msg = textwrap.dedent("""\
Could not initialize compiler instance: do you have Visual Studio
installed? If you are trying to build with MinGW, please use "python setup.py
build -c mingw32" instead. If you have Visual Studio installed, check it is
correctly installed, and the right version (VS 2015 as of this writing).
Original exception was: %s, and the Compiler class was %s
============================================================================""") \
% (e, self.compiler.__class__.__name__)
print(textwrap.dedent("""\
============================================================================"""))
raise distutils.errors.DistutilsPlatformError(msg) from e
# After MSVC is initialized, add an explicit /MANIFEST to linker
# flags. See issues gh-4245 and gh-4101 for details. Also
# relevant are issues 4431 and 16296 on the Python bug tracker.
from distutils import msvc9compiler
if msvc9compiler.get_build_version() >= 10:
for ldflags in [self.compiler.ldflags_shared,
self.compiler.ldflags_shared_debug]:
if '/MANIFEST' not in ldflags:
ldflags.append('/MANIFEST')
if not isinstance(self.fcompiler, FCompiler):
self.fcompiler = new_fcompiler(compiler=self.fcompiler,
dry_run=self.dry_run, force=1,
c_compiler=self.compiler)
if self.fcompiler is not None:
self.fcompiler.customize(self.distribution)
if self.fcompiler.get_version():
self.fcompiler.customize_cmd(self)
self.fcompiler.show_customization()
def _wrap_method(self, mth, lang, args):
from distutils.ccompiler import CompileError
from distutils.errors import DistutilsExecError
save_compiler = self.compiler
if lang in ['f77', 'f90']:
self.compiler = self.fcompiler
if self.compiler is None:
raise CompileError('%s compiler is not set' % (lang,))
try:
ret = mth(*((self,)+args))
except (DistutilsExecError, CompileError) as e:
self.compiler = save_compiler
raise CompileError from e
self.compiler = save_compiler
return ret
def _compile (self, body, headers, include_dirs, lang):
src, obj = self._wrap_method(old_config._compile, lang,
(body, headers, include_dirs, lang))
# _compile in unixcompiler.py sometimes creates .d dependency files.
# Clean them up.
self.temp_files.append(obj + '.d')
return src, obj
def _link (self, body,
headers, include_dirs,
libraries, library_dirs, lang):
if self.compiler.compiler_type=='msvc':
libraries = (libraries or [])[:]
library_dirs = (library_dirs or [])[:]
if lang in ['f77', 'f90']:
lang = 'c' # always use system linker when using MSVC compiler
if self.fcompiler:
for d in self.fcompiler.library_dirs or []:
# correct path when compiling in Cygwin but with
# normal Win Python
if d.startswith('/usr/lib'):
try:
d = subprocess.check_output(['cygpath',
'-w', d])
except (OSError, subprocess.CalledProcessError):
pass
else:
d = filepath_from_subprocess_output(d)
library_dirs.append(d)
for libname in self.fcompiler.libraries or []:
if libname not in libraries:
libraries.append(libname)
for libname in libraries:
if libname.startswith('msvc'): continue
fileexists = False
for libdir in library_dirs or []:
libfile = os.path.join(libdir, '%s.lib' % (libname))
if os.path.isfile(libfile):
fileexists = True
break
if fileexists: continue
# make g77-compiled static libs available to MSVC
fileexists = False
for libdir in library_dirs:
libfile = os.path.join(libdir, 'lib%s.a' % (libname))
if os.path.isfile(libfile):
# copy libname.a file to name.lib so that MSVC linker
# can find it
libfile2 = os.path.join(libdir, '%s.lib' % (libname))
copy_file(libfile, libfile2)
self.temp_files.append(libfile2)
fileexists = True
break
if fileexists: continue
log.warn('could not find library %r in directories %s' \
% (libname, library_dirs))
elif self.compiler.compiler_type == 'mingw32':
generate_manifest(self)
return self._wrap_method(old_config._link, lang,
(body, headers, include_dirs,
libraries, library_dirs, lang))
def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'):
self._check_compiler()
return self.try_compile(
"/* we need a dummy line to make distutils happy */",
[header], include_dirs)
def check_decl(self, symbol,
headers=None, include_dirs=None):
self._check_compiler()
body = textwrap.dedent("""
int main(void)
{
#ifndef %s
(void) %s;
#endif
;
return 0;
}""") % (symbol, symbol)
return self.try_compile(body, headers, include_dirs)
def check_macro_true(self, symbol,
headers=None, include_dirs=None):
self._check_compiler()
body = textwrap.dedent("""
int main(void)
{
#if %s
#else
#error false or undefined macro
#endif
;
return 0;
}""") % (symbol,)
return self.try_compile(body, headers, include_dirs)
def check_type(self, type_name, headers=None, include_dirs=None,
library_dirs=None):
"""Check type availability. Return True if the type can be compiled,
False otherwise"""
self._check_compiler()
# First check the type can be compiled
body = textwrap.dedent(r"""
int main(void) {
if ((%(name)s *) 0)
return 0;
if (sizeof (%(name)s))
return 0;
}
""") % {'name': type_name}
st = False
try:
try:
self._compile(body % {'type': type_name},
headers, include_dirs, 'c')
st = True
except distutils.errors.CompileError:
st = False
finally:
self._clean()
return st
def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None):
"""Check size of a given type."""
self._check_compiler()
# First check the type can be compiled
body = textwrap.dedent(r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];
test_array [0] = 0
;
return 0;
}
""")
self._compile(body % {'type': type_name},
headers, include_dirs, 'c')
self._clean()
if expected:
body = textwrap.dedent(r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)];
test_array [0] = 0
;
return 0;
}
""")
for size in expected:
try:
self._compile(body % {'type': type_name, 'size': size},
headers, include_dirs, 'c')
self._clean()
return size
except CompileError:
pass
# this fails to *compile* if size > sizeof(type)
body = textwrap.dedent(r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)];
test_array [0] = 0
;
return 0;
}
""")
# The principle is simple: we first find low and high bounds of size
# for the type, where low/high are looked up on a log scale. Then, we
# do a binary search to find the exact size between low and high
low = 0
mid = 0
while True:
try:
self._compile(body % {'type': type_name, 'size': mid},
headers, include_dirs, 'c')
self._clean()
break
except CompileError:
#log.info("failure to test for bound %d" % mid)
low = mid + 1
mid = 2 * mid + 1
high = mid
# Binary search:
while low != high:
mid = (high - low) // 2 + low
try:
self._compile(body % {'type': type_name, 'size': mid},
headers, include_dirs, 'c')
self._clean()
high = mid
except CompileError:
low = mid + 1
return low
def check_func(self, func,
headers=None, include_dirs=None,
libraries=None, library_dirs=None,
decl=False, call=False, call_args=None):
# clean up distutils's config a bit: add void to main(), and
# return a value.
self._check_compiler()
body = []
if decl:
if type(decl) == str:
body.append(decl)
else:
body.append("int %s (void);" % func)
# Handle MSVC intrinsics: force MS compiler to make a function call.
# Useful to test for some functions when built with optimization on, to
# avoid build error because the intrinsic and our 'fake' test
# declaration do not match.
body.append("#ifdef _MSC_VER")
body.append("#pragma function(%s)" % func)
body.append("#endif")
body.append("int main (void) {")
if call:
if call_args is None:
call_args = ''
body.append(" %s(%s);" % (func, call_args))
else:
body.append(" %s;" % func)
body.append(" return 0;")
body.append("}")
body = '\n'.join(body) + "\n"
return self.try_link(body, headers, include_dirs,
libraries, library_dirs)
def check_funcs_once(self, funcs,
headers=None, include_dirs=None,
libraries=None, library_dirs=None,
decl=False, call=False, call_args=None):
"""Check a list of functions at once.
This is useful to speed up things, since all the functions in the funcs
list will be put in one compilation unit.
Arguments
---------
funcs : seq
list of functions to test
include_dirs : seq
list of header paths
libraries : seq
list of libraries to link the code snippet to
library_dirs : seq
list of library paths
decl : dict
for every (key, value), the declaration in the value will be
used for function in key. If a function is not in the
dictionary, no declaration will be used.
call : dict
for every item (f, value), if the value is True, a call will be
done to the function f.
"""
self._check_compiler()
body = []
if decl:
for f, v in decl.items():
if v:
body.append("int %s (void);" % f)
# Handle MS intrinsics. See check_func for more info.
body.append("#ifdef _MSC_VER")
for func in funcs:
body.append("#pragma function(%s)" % func)
body.append("#endif")
body.append("int main (void) {")
if call:
for f in funcs:
if f in call and call[f]:
if not (call_args and f in call_args and call_args[f]):
args = ''
else:
args = call_args[f]
body.append(" %s(%s);" % (f, args))
else:
body.append(" %s;" % f)
else:
for f in funcs:
body.append(" %s;" % f)
body.append(" return 0;")
body.append("}")
body = '\n'.join(body) + "\n"
return self.try_link(body, headers, include_dirs,
libraries, library_dirs)
def check_inline(self):
"""Return the inline keyword recognized by the compiler, empty string
otherwise."""
return check_inline(self)
def check_restrict(self):
"""Return the restrict keyword recognized by the compiler, empty string
otherwise."""
return check_restrict(self)
def check_compiler_gcc(self):
"""Return True if the C compiler is gcc"""
return check_compiler_gcc(self)
def check_gcc_function_attribute(self, attribute, name):
return check_gcc_function_attribute(self, attribute, name)
def check_gcc_function_attribute_with_intrinsics(self, attribute, name,
code, include):
return check_gcc_function_attribute_with_intrinsics(self, attribute,
name, code, include)
def check_gcc_variable_attribute(self, attribute):
return check_gcc_variable_attribute(self, attribute)
def check_gcc_version_at_least(self, major, minor=0, patchlevel=0):
"""Return True if the GCC version is greater than or equal to the
specified version."""
return check_gcc_version_at_least(self, major, minor, patchlevel)
def get_output(self, body, headers=None, include_dirs=None,
libraries=None, library_dirs=None,
lang="c", use_tee=None):
"""Try to compile, link to an executable, and run a program
built from 'body' and 'headers'. Returns the exit status code
of the program and its output.
"""
# 2008-11-16, RemoveMe
warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n"
"Usage of get_output is deprecated: please do not \n"
"use it anymore, and avoid configuration checks \n"
"involving running executable on the target machine.\n"
"+++++++++++++++++++++++++++++++++++++++++++++++++\n",
DeprecationWarning, stacklevel=2)
self._check_compiler()
exitcode, output = 255, ''
try:
grabber = GrabStdout()
try:
src, obj, exe = self._link(body, headers, include_dirs,
libraries, library_dirs, lang)
grabber.restore()
except Exception:
output = grabber.data
grabber.restore()
raise
exe = os.path.join('.', exe)
try:
# specify cwd arg for consistency with
# historic usage pattern of exec_command()
# also, note that exe appears to be a string,
# which exec_command() handled, but we now
# use a list for check_output() -- this assumes
# that exe is always a single command
output = subprocess.check_output([exe], cwd='.')
except subprocess.CalledProcessError as exc:
exitstatus = exc.returncode
output = ''
except OSError:
# preserve the EnvironmentError exit status
# used historically in exec_command()
exitstatus = 127
output = ''
else:
output = filepath_from_subprocess_output(output)
if hasattr(os, 'WEXITSTATUS'):
exitcode = os.WEXITSTATUS(exitstatus)
if os.WIFSIGNALED(exitstatus):
sig = os.WTERMSIG(exitstatus)
log.error('subprocess exited with signal %d' % (sig,))
if sig == signal.SIGINT:
# control-C
raise KeyboardInterrupt
else:
exitcode = exitstatus
log.info("success!")
except (CompileError, LinkError):
log.info("failure.")
self._clean()
return exitcode, output
def get_atlas_version(**config):
libraries = config.get('libraries', [])
library_dirs = config.get('library_dirs', [])
key = (tuple(libraries), tuple(library_dirs))
if key in _cached_atlas_version:
return _cached_atlas_version[key]
c = cmd_config(Distribution())
atlas_version = None
info = {}
try:
s, o = c.get_output(atlas_version_c_text,
libraries=libraries, library_dirs=library_dirs,
)
if s and re.search(r'undefined reference to `_gfortran', o, re.M):
s, o = c.get_output(atlas_version_c_text,
libraries=libraries + ['gfortran'],
library_dirs=library_dirs,
)
if not s:
warnings.warn(textwrap.dedent("""
*****************************************************
Linkage with ATLAS requires gfortran. Use
python setup.py config_fc --fcompiler=gnu95 ...
when building extension libraries that use ATLAS.
Make sure that -lgfortran is used for C++ extensions.
*****************************************************
"""), stacklevel=2)
dict_append(info, language='f90',
define_macros=[('ATLAS_REQUIRES_GFORTRAN', None)])
except Exception: # failed to get version from file -- maybe on Windows
# look at directory name
for o in library_dirs:
m = re.search(r'ATLAS_(?P<version>\d+[.]\d+[.]\d+)_', o)
if m:
atlas_version = m.group('version')
if atlas_version is not None:
break
# final choice --- look at ATLAS_VERSION environment
# variable
if atlas_version is None:
atlas_version = os.environ.get('ATLAS_VERSION', None)
if atlas_version:
dict_append(info, define_macros=[(
'ATLAS_INFO', _c_string_literal(atlas_version))
])
else:
dict_append(info, define_macros=[('NO_ATLAS_INFO', -1)])
return atlas_version or '?.?.?', info
if not s:
m = re.search(r'ATLAS version (?P<version>\d+[.]\d+[.]\d+)', o)
if m:
atlas_version = m.group('version')
if atlas_version is None:
if re.search(r'undefined symbol: ATL_buildinfo', o, re.M):
atlas_version = '3.2.1_pre3.3.6'
else:
log.info('Status: %d', s)
log.info('Output: %s', o)
elif atlas_version == '3.2.1_pre3.3.6':
dict_append(info, define_macros=[('NO_ATLAS_INFO', -2)])
else:
dict_append(info, define_macros=[(
'ATLAS_INFO', _c_string_literal(atlas_version))
])
result = _cached_atlas_version[key] = atlas_version, info
return result | null |
170,335 | import sys
import os
import re
import copy
import warnings
import subprocess
import textwrap
from glob import glob
from functools import reduce
from configparser import NoOptionError
from configparser import RawConfigParser as ConfigParser
from distutils.errors import DistutilsError
from distutils.dist import Distribution
import sysconfig
from numpy.distutils import log
from distutils.util import get_platform
from numpy.distutils.exec_command import (
find_executable, filepath_from_subprocess_output,
)
from numpy.distutils.misc_util import (is_sequence, is_string,
get_shared_lib_extension)
from numpy.distutils.command.config import config as cmd_config
from numpy.distutils import customized_ccompiler as _customized_ccompiler
from numpy.distutils import _shell_utils
import distutils.ccompiler
import tempfile
import shutil
import platform
if os.path.join(sys.prefix, 'lib') not in default_lib_dirs:
default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib'))
default_include_dirs.append(os.path.join(sys.prefix, 'include'))
default_src_dirs.append(os.path.join(sys.prefix, 'src'))
def glob(pathname, recursive=False):
"""Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
"""
return list(iglob(pathname, recursive=recursive))
def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ...
def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ...
def is_string(s):
return isinstance(s, str)
The provided code snippet includes necessary dependencies for implementing the `combine_paths` function. Write a Python function `def combine_paths(*args, **kws)` to solve the following problem:
Return a list of existing paths composed by all combinations of items from arguments.
Here is the function:
def combine_paths(*args, **kws):
""" Return a list of existing paths composed by all combinations of
items from arguments.
"""
r = []
for a in args:
if not a:
continue
if is_string(a):
a = [a]
r.append(a)
args = r
if not args:
return []
if len(args) == 1:
result = reduce(lambda a, b: a + b, map(glob, args[0]), [])
elif len(args) == 2:
result = []
for a0 in args[0]:
for a1 in args[1]:
result.extend(glob(os.path.join(a0, a1)))
else:
result = combine_paths(*(combine_paths(args[0], args[1]) + args[2:]))
log.debug('(paths: %s)', ','.join(result))
return result | Return a list of existing paths composed by all combinations of items from arguments. |
170,336 | import sys
import os
import re
import copy
import warnings
import subprocess
import textwrap
from glob import glob
from functools import reduce
from configparser import NoOptionError
from configparser import RawConfigParser as ConfigParser
from distutils.errors import DistutilsError
from distutils.dist import Distribution
import sysconfig
from numpy.distutils import log
from distutils.util import get_platform
from numpy.distutils.exec_command import (
find_executable, filepath_from_subprocess_output,
)
from numpy.distutils.misc_util import (is_sequence, is_string,
get_shared_lib_extension)
from numpy.distutils.command.config import config as cmd_config
from numpy.distutils import customized_ccompiler as _customized_ccompiler
from numpy.distutils import _shell_utils
import distutils.ccompiler
import tempfile
import shutil
import platform
if sys.platform == 'win32':
default_lib_dirs = ['C:\\',
os.path.join(sysconfig.get_config_var('exec_prefix'),
'libs')]
default_runtime_dirs = []
default_include_dirs = []
default_src_dirs = ['.']
default_x11_lib_dirs = []
default_x11_include_dirs = []
_include_dirs = [
'include',
'include/suitesparse',
]
_lib_dirs = [
'lib',
]
_include_dirs = [d.replace('/', os.sep) for d in _include_dirs]
_lib_dirs = [d.replace('/', os.sep) for d in _lib_dirs]
# VCpkg is the de-facto package manager on windows for C/C++
# libraries. If it is on the PATH, then we append its paths here.
vcpkg = shutil.which('vcpkg')
if vcpkg:
vcpkg_dir = os.path.dirname(vcpkg)
if platform.architecture()[0] == '32bit':
specifier = 'x86'
else:
specifier = 'x64'
vcpkg_installed = os.path.join(vcpkg_dir, 'installed')
for vcpkg_root in [
os.path.join(vcpkg_installed, specifier + '-windows'),
os.path.join(vcpkg_installed, specifier + '-windows-static'),
]:
add_system_root(vcpkg_root)
# Conda is another popular package manager that provides libraries
conda = shutil.which('conda')
if conda:
conda_dir = os.path.dirname(conda)
add_system_root(os.path.join(conda_dir, '..', 'Library'))
add_system_root(os.path.join(conda_dir, 'Library'))
else:
default_lib_dirs = libpaths(['/usr/local/lib', '/opt/lib', '/usr/lib',
'/opt/local/lib', '/sw/lib'], platform_bits)
default_runtime_dirs = []
default_include_dirs = ['/usr/local/include',
'/opt/include',
# path of umfpack under macports
'/opt/local/include/ufsparse',
'/opt/local/include', '/sw/include',
'/usr/include/suitesparse']
default_src_dirs = ['.', '/usr/local/src', '/opt/src', '/sw/src']
default_x11_lib_dirs = libpaths(['/usr/X11R6/lib', '/usr/X11/lib',
'/usr/lib'], platform_bits)
default_x11_include_dirs = ['/usr/X11R6/include', '/usr/X11/include']
if os.path.exists('/usr/lib/X11'):
globbed_x11_dir = glob('/usr/lib/*/libX11.so')
if globbed_x11_dir:
x11_so_dir = os.path.split(globbed_x11_dir[0])[0]
default_x11_lib_dirs.extend([x11_so_dir, '/usr/lib/X11'])
default_x11_include_dirs.extend(['/usr/lib/X11/include',
'/usr/include/X11'])
with open(os.devnull, 'w') as tmp:
try:
p = subprocess.Popen(["gcc", "-print-multiarch"], stdout=subprocess.PIPE,
stderr=tmp)
except (OSError, DistutilsError):
# OSError if gcc is not installed, or SandboxViolation (DistutilsError
# subclass) if an old setuptools bug is triggered (see gh-3160).
pass
else:
triplet = str(p.communicate()[0].decode().strip())
if p.returncode == 0:
# gcc supports the "-print-multiarch" option
default_x11_lib_dirs += [os.path.join("/usr/lib/", triplet)]
default_lib_dirs += [os.path.join("/usr/lib/", triplet)]
def get_info(name, notfound_action=0):
"""
notfound_action:
0 - do nothing
1 - display warning message
2 - raise error
"""
cl = {'armpl': armpl_info,
'blas_armpl': blas_armpl_info,
'lapack_armpl': lapack_armpl_info,
'fftw3_armpl': fftw3_armpl_info,
'atlas': atlas_info, # use lapack_opt or blas_opt instead
'atlas_threads': atlas_threads_info, # ditto
'atlas_blas': atlas_blas_info,
'atlas_blas_threads': atlas_blas_threads_info,
'lapack_atlas': lapack_atlas_info, # use lapack_opt instead
'lapack_atlas_threads': lapack_atlas_threads_info, # ditto
'atlas_3_10': atlas_3_10_info, # use lapack_opt or blas_opt instead
'atlas_3_10_threads': atlas_3_10_threads_info, # ditto
'atlas_3_10_blas': atlas_3_10_blas_info,
'atlas_3_10_blas_threads': atlas_3_10_blas_threads_info,
'lapack_atlas_3_10': lapack_atlas_3_10_info, # use lapack_opt instead
'lapack_atlas_3_10_threads': lapack_atlas_3_10_threads_info, # ditto
'flame': flame_info, # use lapack_opt instead
'mkl': mkl_info,
# openblas which may or may not have embedded lapack
'openblas': openblas_info, # use blas_opt instead
# openblas with embedded lapack
'openblas_lapack': openblas_lapack_info, # use blas_opt instead
'openblas_clapack': openblas_clapack_info, # use blas_opt instead
'blis': blis_info, # use blas_opt instead
'lapack_mkl': lapack_mkl_info, # use lapack_opt instead
'blas_mkl': blas_mkl_info, # use blas_opt instead
'accelerate': accelerate_info, # use blas_opt instead
'openblas64_': openblas64__info,
'openblas64__lapack': openblas64__lapack_info,
'openblas_ilp64': openblas_ilp64_info,
'openblas_ilp64_lapack': openblas_ilp64_lapack_info,
'x11': x11_info,
'fft_opt': fft_opt_info,
'fftw': fftw_info,
'fftw2': fftw2_info,
'fftw3': fftw3_info,
'dfftw': dfftw_info,
'sfftw': sfftw_info,
'fftw_threads': fftw_threads_info,
'dfftw_threads': dfftw_threads_info,
'sfftw_threads': sfftw_threads_info,
'djbfft': djbfft_info,
'blas': blas_info, # use blas_opt instead
'lapack': lapack_info, # use lapack_opt instead
'lapack_src': lapack_src_info,
'blas_src': blas_src_info,
'numpy': numpy_info,
'f2py': f2py_info,
'Numeric': Numeric_info,
'numeric': Numeric_info,
'numarray': numarray_info,
'numerix': numerix_info,
'lapack_opt': lapack_opt_info,
'lapack_ilp64_opt': lapack_ilp64_opt_info,
'lapack_ilp64_plain_opt': lapack_ilp64_plain_opt_info,
'lapack64__opt': lapack64__opt_info,
'blas_opt': blas_opt_info,
'blas_ilp64_opt': blas_ilp64_opt_info,
'blas_ilp64_plain_opt': blas_ilp64_plain_opt_info,
'blas64__opt': blas64__opt_info,
'boost_python': boost_python_info,
'agg2': agg2_info,
'wx': wx_info,
'gdk_pixbuf_xlib_2': gdk_pixbuf_xlib_2_info,
'gdk-pixbuf-xlib-2.0': gdk_pixbuf_xlib_2_info,
'gdk_pixbuf_2': gdk_pixbuf_2_info,
'gdk-pixbuf-2.0': gdk_pixbuf_2_info,
'gdk': gdk_info,
'gdk_2': gdk_2_info,
'gdk-2.0': gdk_2_info,
'gdk_x11_2': gdk_x11_2_info,
'gdk-x11-2.0': gdk_x11_2_info,
'gtkp_x11_2': gtkp_x11_2_info,
'gtk+-x11-2.0': gtkp_x11_2_info,
'gtkp_2': gtkp_2_info,
'gtk+-2.0': gtkp_2_info,
'xft': xft_info,
'freetype2': freetype2_info,
'umfpack': umfpack_info,
'amd': amd_info,
}.get(name.lower(), system_info)
return cl().get_info(notfound_action)
class system_info:
""" get_info() is the only public method. Don't use others.
"""
dir_env_var = None
# XXX: search_static_first is disabled by default, may disappear in
# future unless it is proved to be useful.
search_static_first = 0
# The base-class section name is a random word "ALL" and is not really
# intended for general use. It cannot be None nor can it be DEFAULT as
# these break the ConfigParser. See gh-15338
section = 'ALL'
saved_results = {}
notfounderror = NotFoundError
def __init__(self,
default_lib_dirs=default_lib_dirs,
default_include_dirs=default_include_dirs,
):
self.__class__.info = {}
self.local_prefixes = []
defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
'include_dirs': os.pathsep.join(default_include_dirs),
'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
'rpath': '',
'src_dirs': os.pathsep.join(default_src_dirs),
'search_static_first': str(self.search_static_first),
'extra_compile_args': '', 'extra_link_args': ''}
self.cp = ConfigParser(defaults)
self.files = []
self.files.extend(get_standard_file('.numpy-site.cfg'))
self.files.extend(get_standard_file('site.cfg'))
self.parse_config_files()
if self.section is not None:
self.search_static_first = self.cp.getboolean(
self.section, 'search_static_first')
assert isinstance(self.search_static_first, int)
def parse_config_files(self):
self.cp.read(self.files)
if not self.cp.has_section(self.section):
if self.section is not None:
self.cp.add_section(self.section)
def calc_libraries_info(self):
libs = self.get_libraries()
dirs = self.get_lib_dirs()
# The extensions use runtime_library_dirs
r_dirs = self.get_runtime_lib_dirs()
# Intrinsic distutils use rpath, we simply append both entries
# as though they were one entry
r_dirs.extend(self.get_runtime_lib_dirs(key='rpath'))
info = {}
for lib in libs:
i = self.check_libs(dirs, [lib])
if i is not None:
dict_append(info, **i)
else:
log.info('Library %s was not found. Ignoring' % (lib))
if r_dirs:
i = self.check_libs(r_dirs, [lib])
if i is not None:
# Swap library keywords found to runtime_library_dirs
# the libraries are insisting on the user having defined
# them using the library_dirs, and not necessarily by
# runtime_library_dirs
del i['libraries']
i['runtime_library_dirs'] = i.pop('library_dirs')
dict_append(info, **i)
else:
log.info('Runtime library %s was not found. Ignoring' % (lib))
return info
def set_info(self, **info):
if info:
lib_info = self.calc_libraries_info()
dict_append(info, **lib_info)
# Update extra information
extra_info = self.calc_extra_info()
dict_append(info, **extra_info)
self.saved_results[self.__class__.__name__] = info
def get_option_single(self, *options):
""" Ensure that only one of `options` are found in the section
Parameters
----------
*options : list of str
a list of options to be found in the section (``self.section``)
Returns
-------
str :
the option that is uniquely found in the section
Raises
------
AliasedOptionError :
in case more than one of the options are found
"""
found = [self.cp.has_option(self.section, opt) for opt in options]
if sum(found) == 1:
return options[found.index(True)]
elif sum(found) == 0:
# nothing is found anyways
return options[0]
# Else we have more than 1 key found
if AliasedOptionError.__doc__ is None:
raise AliasedOptionError()
raise AliasedOptionError(AliasedOptionError.__doc__.format(
section=self.section, options='[{}]'.format(', '.join(options))))
def has_info(self):
return self.__class__.__name__ in self.saved_results
def calc_extra_info(self):
""" Updates the information in the current information with
respect to these flags:
extra_compile_args
extra_link_args
"""
info = {}
for key in ['extra_compile_args', 'extra_link_args']:
# Get values
opt = self.cp.get(self.section, key)
opt = _shell_utils.NativeParser.split(opt)
if opt:
tmp = {key: opt}
dict_append(info, **tmp)
return info
def get_info(self, notfound_action=0):
""" Return a dictionary with items that are compatible
with numpy.distutils.setup keyword arguments.
"""
flag = 0
if not self.has_info():
flag = 1
log.info(self.__class__.__name__ + ':')
if hasattr(self, 'calc_info'):
self.calc_info()
if notfound_action:
if not self.has_info():
if notfound_action == 1:
warnings.warn(self.notfounderror.__doc__, stacklevel=2)
elif notfound_action == 2:
raise self.notfounderror(self.notfounderror.__doc__)
else:
raise ValueError(repr(notfound_action))
if not self.has_info():
log.info(' NOT AVAILABLE')
self.set_info()
else:
log.info(' FOUND:')
res = self.saved_results.get(self.__class__.__name__)
if log.get_threshold() <= log.INFO and flag:
for k, v in res.items():
v = str(v)
if k in ['sources', 'libraries'] and len(v) > 270:
v = v[:120] + '...\n...\n...' + v[-120:]
log.info(' %s = %s', k, v)
log.info('')
return copy.deepcopy(res)
def get_paths(self, section, key):
dirs = self.cp.get(section, key).split(os.pathsep)
env_var = self.dir_env_var
if env_var:
if is_sequence(env_var):
e0 = env_var[-1]
for e in env_var:
if e in os.environ:
e0 = e
break
if not env_var[0] == e0:
log.info('Setting %s=%s' % (env_var[0], e0))
env_var = e0
if env_var and env_var in os.environ:
d = os.environ[env_var]
if d == 'None':
log.info('Disabled %s: %s',
self.__class__.__name__, '(%s is None)'
% (env_var,))
return []
if os.path.isfile(d):
dirs = [os.path.dirname(d)] + dirs
l = getattr(self, '_lib_names', [])
if len(l) == 1:
b = os.path.basename(d)
b = os.path.splitext(b)[0]
if b[:3] == 'lib':
log.info('Replacing _lib_names[0]==%r with %r' \
% (self._lib_names[0], b[3:]))
self._lib_names[0] = b[3:]
else:
ds = d.split(os.pathsep)
ds2 = []
for d in ds:
if os.path.isdir(d):
ds2.append(d)
for dd in ['include', 'lib']:
d1 = os.path.join(d, dd)
if os.path.isdir(d1):
ds2.append(d1)
dirs = ds2 + dirs
default_dirs = self.cp.get(self.section, key).split(os.pathsep)
dirs.extend(default_dirs)
ret = []
for d in dirs:
if len(d) > 0 and not os.path.isdir(d):
warnings.warn('Specified path %s is invalid.' % d, stacklevel=2)
continue
if d not in ret:
ret.append(d)
log.debug('( %s = %s )', key, ':'.join(ret))
return ret
def get_lib_dirs(self, key='library_dirs'):
return self.get_paths(self.section, key)
def get_runtime_lib_dirs(self, key='runtime_library_dirs'):
path = self.get_paths(self.section, key)
if path == ['']:
path = []
return path
def get_include_dirs(self, key='include_dirs'):
return self.get_paths(self.section, key)
def get_src_dirs(self, key='src_dirs'):
return self.get_paths(self.section, key)
def get_libs(self, key, default):
try:
libs = self.cp.get(self.section, key)
except NoOptionError:
if not default:
return []
if is_string(default):
return [default]
return default
return [b for b in [a.strip() for a in libs.split(',')] if b]
def get_libraries(self, key='libraries'):
if hasattr(self, '_lib_names'):
return self.get_libs(key, default=self._lib_names)
else:
return self.get_libs(key, '')
def library_extensions(self):
c = customized_ccompiler()
static_exts = []
if c.compiler_type != 'msvc':
# MSVC doesn't understand binutils
static_exts.append('.a')
if sys.platform == 'win32':
static_exts.append('.lib') # .lib is used by MSVC and others
if self.search_static_first:
exts = static_exts + [so_ext]
else:
exts = [so_ext] + static_exts
if sys.platform == 'cygwin':
exts.append('.dll.a')
if sys.platform == 'darwin':
exts.append('.dylib')
return exts
def check_libs(self, lib_dirs, libs, opt_libs=[]):
"""If static or shared libraries are available then return
their info dictionary.
Checks for all libraries as shared libraries first, then
static (or vice versa if self.search_static_first is True).
"""
exts = self.library_extensions()
info = None
for ext in exts:
info = self._check_libs(lib_dirs, libs, opt_libs, [ext])
if info is not None:
break
if not info:
log.info(' libraries %s not found in %s', ','.join(libs),
lib_dirs)
return info
def check_libs2(self, lib_dirs, libs, opt_libs=[]):
"""If static or shared libraries are available then return
their info dictionary.
Checks each library for shared or static.
"""
exts = self.library_extensions()
info = self._check_libs(lib_dirs, libs, opt_libs, exts)
if not info:
log.info(' libraries %s not found in %s', ','.join(libs),
lib_dirs)
return info
def _find_lib(self, lib_dir, lib, exts):
assert is_string(lib_dir)
# under windows first try without 'lib' prefix
if sys.platform == 'win32':
lib_prefixes = ['', 'lib']
else:
lib_prefixes = ['lib']
# for each library name, see if we can find a file for it.
for ext in exts:
for prefix in lib_prefixes:
p = self.combine_paths(lib_dir, prefix + lib + ext)
if p:
break
if p:
assert len(p) == 1
# ??? splitext on p[0] would do this for cygwin
# doesn't seem correct
if ext == '.dll.a':
lib += '.dll'
if ext == '.lib':
lib = prefix + lib
return lib
return False
def _find_libs(self, lib_dirs, libs, exts):
# make sure we preserve the order of libs, as it can be important
found_dirs, found_libs = [], []
for lib in libs:
for lib_dir in lib_dirs:
found_lib = self._find_lib(lib_dir, lib, exts)
if found_lib:
found_libs.append(found_lib)
if lib_dir not in found_dirs:
found_dirs.append(lib_dir)
break
return found_dirs, found_libs
def _check_libs(self, lib_dirs, libs, opt_libs, exts):
"""Find mandatory and optional libs in expected paths.
Missing optional libraries are silently forgotten.
"""
if not is_sequence(lib_dirs):
lib_dirs = [lib_dirs]
# First, try to find the mandatory libraries
found_dirs, found_libs = self._find_libs(lib_dirs, libs, exts)
if len(found_libs) > 0 and len(found_libs) == len(libs):
# Now, check for optional libraries
opt_found_dirs, opt_found_libs = self._find_libs(lib_dirs, opt_libs, exts)
found_libs.extend(opt_found_libs)
for lib_dir in opt_found_dirs:
if lib_dir not in found_dirs:
found_dirs.append(lib_dir)
info = {'libraries': found_libs, 'library_dirs': found_dirs}
return info
else:
return None
def combine_paths(self, *args):
"""Return a list of existing paths composed by all combinations
of items from the arguments.
"""
return combine_paths(*args)
def parseCmdLine(argv=(None,)):
import optparse
parser = optparse.OptionParser("usage: %prog [-v] [info objs]")
parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
default=False,
help='be verbose and print more messages')
opts, args = parser.parse_args(args=argv[1:])
return opts, args
def show_all(argv=None):
import inspect
if argv is None:
argv = sys.argv
opts, args = parseCmdLine(argv)
if opts.verbose:
log.set_threshold(log.DEBUG)
else:
log.set_threshold(log.INFO)
show_only = []
for n in args:
if n[-5:] != '_info':
n = n + '_info'
show_only.append(n)
show_all = not show_only
_gdict_ = globals().copy()
for name, c in _gdict_.items():
if not inspect.isclass(c):
continue
if not issubclass(c, system_info) or c is system_info:
continue
if not show_all:
if name not in show_only:
continue
del show_only[show_only.index(name)]
conf = c()
conf.verbosity = 2
# we don't need the result, but we want
# the side effect of printing diagnostics
conf.get_info()
if show_only:
log.info('Info classes not defined: %s', ','.join(show_only)) | null |
170,337 | import os
import sys
import subprocess
import shlex
from distutils.errors import CompileError, DistutilsExecError, LibError
from distutils.unixccompiler import UnixCCompiler
from numpy.distutils.ccompiler import replace_method
from numpy.distutils.misc_util import _commandline_dep_string
from numpy.distutils import log
def _commandline_dep_string(cc_args, extra_postargs, pp_opts):
"""
Return commandline representation used to determine if a file needs
to be recompiled
"""
cmdline = 'commandline: '
cmdline += ' '.join(cc_args)
cmdline += ' '.join(extra_postargs)
cmdline += ' '.join(pp_opts) + '\n'
return cmdline
def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform. Generally this includes
everything needed to build extensions and install both pure modules and
extensions. On Unix, this means every variable defined in Python's
installed Makefile; on Windows it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global _config_vars
if _config_vars is None:
func = globals().get("_init_" + os.name)
if func:
func()
else:
_config_vars = {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# Distutils.
_config_vars['prefix'] = PREFIX
_config_vars['exec_prefix'] = EXEC_PREFIX
if not IS_PYPY:
# For backward compatibility, see issue19555
SO = _config_vars.get('EXT_SUFFIX')
if SO is not None:
_config_vars['SO'] = SO
# Always convert srcdir to an absolute path
srcdir = _config_vars.get('srcdir', project_base)
if os.name == 'posix':
if python_build:
# If srcdir is a relative path (typically '.' or '..')
# then it should be interpreted relative to the directory
# containing Makefile.
base = os.path.dirname(get_makefile_filename())
srcdir = os.path.join(base, srcdir)
else:
# srcdir is not meaningful since the installation is
# spread about the filesystem. We choose the
# directory containing the Makefile since we know it
# exists.
srcdir = os.path.dirname(get_makefile_filename())
_config_vars['srcdir'] = os.path.abspath(os.path.normpath(srcdir))
# Convert srcdir into an absolute path if it appears necessary.
# Normally it is relative to the build directory. However, during
# testing, for example, we might be running a non-installed python
# from a different directory.
if python_build and os.name == "posix":
base = project_base
if (not os.path.isabs(_config_vars['srcdir']) and
base != os.getcwd()):
# srcdir is relative and we are not in the same directory
# as the executable. Assume executable is in the build
# directory and make srcdir absolute.
srcdir = os.path.join(base, _config_vars['srcdir'])
_config_vars['srcdir'] = os.path.normpath(srcdir)
# OS X platforms require special customization to handle
# multi-architecture, multi-os-version installers
if sys.platform == 'darwin':
import _osx_support
_osx_support.customize_config_vars(_config_vars)
if args:
vals = []
for name in args:
vals.append(_config_vars.get(name))
return vals
else:
return _config_vars
The provided code snippet includes necessary dependencies for implementing the `UnixCCompiler__compile` function. Write a Python function `def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts)` to solve the following problem:
Compile a single source files with a Unix-style compiler.
Here is the function:
def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
"""Compile a single source files with a Unix-style compiler."""
# HP ad-hoc fix, see ticket 1383
ccomp = self.compiler_so
if ccomp[0] == 'aCC':
# remove flags that will trigger ANSI-C mode for aCC
if '-Ae' in ccomp:
ccomp.remove('-Ae')
if '-Aa' in ccomp:
ccomp.remove('-Aa')
# add flags for (almost) sane C++ handling
ccomp += ['-AA']
self.compiler_so = ccomp
# ensure OPT environment variable is read
if 'OPT' in os.environ:
# XXX who uses this?
from sysconfig import get_config_vars
opt = shlex.join(shlex.split(os.environ['OPT']))
gcv_opt = shlex.join(shlex.split(get_config_vars('OPT')[0]))
ccomp_s = shlex.join(self.compiler_so)
if opt not in ccomp_s:
ccomp_s = ccomp_s.replace(gcv_opt, opt)
self.compiler_so = shlex.split(ccomp_s)
llink_s = shlex.join(self.linker_so)
if opt not in llink_s:
self.linker_so = self.linker_so + shlex.split(opt)
display = '%s: %s' % (os.path.basename(self.compiler_so[0]), src)
# gcc style automatic dependencies, outputs a makefile (-MF) that lists
# all headers needed by a c file as a side effect of compilation (-MMD)
if getattr(self, '_auto_depends', False):
deps = ['-MMD', '-MF', obj + '.d']
else:
deps = []
try:
self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + deps +
extra_postargs, display = display)
except DistutilsExecError as e:
msg = str(e)
raise CompileError(msg) from None
# add commandline flags to dependency file
if deps:
# After running the compiler, the file created will be in EBCDIC
# but will not be tagged as such. This tags it so the file does not
# have multiple different encodings being written to it
if sys.platform == 'zos':
subprocess.check_output(['chtag', '-tc', 'IBM1047', obj + '.d'])
with open(obj + '.d', 'a') as f:
f.write(_commandline_dep_string(cc_args, extra_postargs, pp_opts)) | Compile a single source files with a Unix-style compiler. |
170,338 | import os
import sys
import subprocess
import shlex
from distutils.errors import CompileError, DistutilsExecError, LibError
from distutils.unixccompiler import UnixCCompiler
from numpy.distutils.ccompiler import replace_method
from numpy.distutils.misc_util import _commandline_dep_string
from numpy.distutils import log
The provided code snippet includes necessary dependencies for implementing the `UnixCCompiler_create_static_lib` function. Write a Python function `def UnixCCompiler_create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None)` to solve the following problem:
Build a static library in a separate sub-process. Parameters ---------- objects : list or tuple of str List of paths to object files used to build the static library. output_libname : str The library name as an absolute or relative (if `output_dir` is used) path. output_dir : str, optional The path to the output directory. Default is None, in which case the ``output_dir`` attribute of the UnixCCompiler instance. debug : bool, optional This parameter is not used. target_lang : str, optional This parameter is not used. Returns ------- None
Here is the function:
def UnixCCompiler_create_static_lib(self, objects, output_libname,
output_dir=None, debug=0, target_lang=None):
"""
Build a static library in a separate sub-process.
Parameters
----------
objects : list or tuple of str
List of paths to object files used to build the static library.
output_libname : str
The library name as an absolute or relative (if `output_dir` is used)
path.
output_dir : str, optional
The path to the output directory. Default is None, in which case
the ``output_dir`` attribute of the UnixCCompiler instance.
debug : bool, optional
This parameter is not used.
target_lang : str, optional
This parameter is not used.
Returns
-------
None
"""
objects, output_dir = self._fix_object_args(objects, output_dir)
output_filename = \
self.library_filename(output_libname, output_dir=output_dir)
if self._need_link(objects, output_filename):
try:
# previous .a may be screwed up; best to remove it first
# and recreate.
# Also, ar on OS X doesn't handle updating universal archives
os.unlink(output_filename)
except OSError:
pass
self.mkpath(os.path.dirname(output_filename))
tmp_objects = objects + self.objects
while tmp_objects:
objects = tmp_objects[:50]
tmp_objects = tmp_objects[50:]
display = '%s: adding %d object files to %s' % (
os.path.basename(self.archiver[0]),
len(objects), output_filename)
self.spawn(self.archiver + [output_filename] + objects,
display = display)
# Not many Unices required ranlib anymore -- SunOS 4.x is, I
# think the only major Unix that does. Maybe we need some
# platform intelligence here to skip ranlib if it's not
# needed -- or maybe Python's configure script took care of
# it for us, hence the check for leading colon.
if self.ranlib:
display = '%s:@ %s' % (os.path.basename(self.ranlib[0]),
output_filename)
try:
self.spawn(self.ranlib + [output_filename],
display = display)
except DistutilsExecError as e:
msg = str(e)
raise LibError(msg) from None
else:
log.debug("skipping %s (up-to-date)", output_filename)
return | Build a static library in a separate sub-process. Parameters ---------- objects : list or tuple of str List of paths to object files used to build the static library. output_libname : str The library name as an absolute or relative (if `output_dir` is used) path. output_dir : str, optional The path to the output directory. Default is None, in which case the ``output_dir`` attribute of the UnixCCompiler instance. debug : bool, optional This parameter is not used. target_lang : str, optional This parameter is not used. Returns ------- None |
170,339 | import re
import os
import sys
import warnings
import platform
import tempfile
import hashlib
import base64
import subprocess
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.exec_command import filepath_from_subprocess_output
from numpy.distutils.fcompiler import FCompiler
from distutils.version import LooseVersion
def is_win64():
return sys.platform == "win32" and platform.architecture()[0] == "64bit" | null |
170,340 | import re
import os
import sys
import warnings
import platform
import tempfile
import hashlib
import base64
import subprocess
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.exec_command import filepath_from_subprocess_output
from numpy.distutils.fcompiler import FCompiler
from distutils.version import LooseVersion
PIPE: int
STDOUT: int
class Popen(Generic[AnyStr]):
args: _CMD
stdin: Optional[IO[AnyStr]]
stdout: Optional[IO[AnyStr]]
stderr: Optional[IO[AnyStr]]
pid: int
returncode: int
universal_newlines: bool
# Technically it is wrong that Popen provides __new__ instead of __init__
# but this shouldn't come up hopefully?
if sys.version_info >= (3, 7):
# text is added in 3.7
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
text: Optional[bool] = ...,
encoding: str,
errors: Optional[str] = ...,
) -> Popen[str]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
text: Optional[bool] = ...,
encoding: Optional[str] = ...,
errors: str,
) -> Popen[str]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
*,
universal_newlines: Literal[True],
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
# where the *real* keyword only args start
text: Optional[bool] = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
) -> Popen[str]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
text: Literal[True],
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
) -> Popen[str]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: Literal[False] = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
text: Literal[None, False] = ...,
encoding: None = ...,
errors: None = ...,
) -> Popen[bytes]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
text: Optional[bool] = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
) -> Popen[Any]: ...
else:
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
encoding: str,
errors: Optional[str] = ...,
) -> Popen[str]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
encoding: Optional[str] = ...,
errors: str,
) -> Popen[str]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
*,
universal_newlines: Literal[True],
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
# where the *real* keyword only args start
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
) -> Popen[str]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: Literal[False] = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
encoding: None = ...,
errors: None = ...,
) -> Popen[bytes]: ...
def __new__(
cls,
args: _CMD,
bufsize: int = ...,
executable: Optional[AnyPath] = ...,
stdin: Optional[_FILE] = ...,
stdout: Optional[_FILE] = ...,
stderr: Optional[_FILE] = ...,
preexec_fn: Optional[Callable[[], Any]] = ...,
close_fds: bool = ...,
shell: bool = ...,
cwd: Optional[AnyPath] = ...,
env: Optional[_ENV] = ...,
universal_newlines: bool = ...,
startupinfo: Optional[Any] = ...,
creationflags: int = ...,
restore_signals: bool = ...,
start_new_session: bool = ...,
pass_fds: Any = ...,
*,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
) -> Popen[Any]: ...
def poll(self) -> Optional[int]: ...
if sys.version_info >= (3, 7):
def wait(self, timeout: Optional[float] = ...) -> int: ...
else:
def wait(self, timeout: Optional[float] = ..., endtime: Optional[float] = ...) -> int: ...
# Return str/bytes
def communicate(
self,
input: Optional[AnyStr] = ...,
timeout: Optional[float] = ...,
# morally this should be optional
) -> Tuple[AnyStr, AnyStr]: ...
def send_signal(self, sig: int) -> None: ...
def terminate(self) -> None: ...
def kill(self) -> None: ...
def __enter__(self: _S) -> _S: ...
def __exit__(
self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]
) -> None: ...
if sys.version_info >= (3, 9):
def __class_getitem__(cls, item: Any) -> GenericAlias: ...
The provided code snippet includes necessary dependencies for implementing the `_can_target` function. Write a Python function `def _can_target(cmd, arch)` to solve the following problem:
Return true if the architecture supports the -arch flag
Here is the function:
def _can_target(cmd, arch):
"""Return true if the architecture supports the -arch flag"""
newcmd = cmd[:]
fid, filename = tempfile.mkstemp(suffix=".f")
os.close(fid)
try:
d = os.path.dirname(filename)
output = os.path.splitext(filename)[0] + ".o"
try:
newcmd.extend(["-arch", arch, "-c", filename])
p = Popen(newcmd, stderr=STDOUT, stdout=PIPE, cwd=d)
p.communicate()
return p.returncode == 0
finally:
if os.path.exists(output):
os.remove(output)
finally:
os.remove(filename) | Return true if the architecture supports the -arch flag |
170,341 | import sys
from numpy.distutils.ccompiler import simple_version_match
from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file
def simple_version_match(pat=r'[-.\d]+', ignore='', start=''):
def intel_version_match(type):
# Match against the important stuff in the version string
return simple_version_match(start=r'Intel.*?Fortran.*?(?:%s).*?Version' % (type,)) | null |
170,342 | import os
from distutils.msvccompiler import MSVCCompiler as _MSVCCompiler
from .system_info import platform_bits
The provided code snippet includes necessary dependencies for implementing the `_merge` function. Write a Python function `def _merge(old, new)` to solve the following problem:
Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current environment, or the same as the old string if obtained from the same environment. The aim here is not to append the new string if it is already contained in the old string so as to limit the growth of the environment string. Parameters ---------- old : string Previous environment string. new : string New environment string. Returns ------- ret : string Updated environment string.
Here is the function:
def _merge(old, new):
"""Concatenate two environment paths avoiding repeats.
Here `old` is the environment string before the base class initialize
function is called and `new` is the string after the call. The new string
will be a fixed string if it is not obtained from the current environment,
or the same as the old string if obtained from the same environment. The aim
here is not to append the new string if it is already contained in the old
string so as to limit the growth of the environment string.
Parameters
----------
old : string
Previous environment string.
new : string
New environment string.
Returns
-------
ret : string
Updated environment string.
"""
if new in old:
return old
if not old:
return new
# Neither new nor old is empty. Give old priority.
return ';'.join([old, new]) | Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current environment, or the same as the old string if obtained from the same environment. The aim here is not to append the new string if it is already contained in the old string so as to limit the growth of the environment string. Parameters ---------- old : string Previous environment string. new : string New environment string. Returns ------- ret : string Updated environment string. |
170,343 | import os
import re
import sys
def dos2unix_one_dir(modified_files, dir_name, file_names):
for file in file_names:
full_path = os.path.join(dir_name, file)
file = dos2unix(full_path)
if file is not None:
modified_files.append(file)
def dos2unix_dir(dir_name):
modified_files = []
os.path.walk(dir_name, dos2unix_one_dir, modified_files)
return modified_files | null |
170,344 | import os
import re
import sys
def unix2dos_one_dir(modified_files, dir_name, file_names):
for file in file_names:
full_path = os.path.join(dir_name, file)
unix2dos(full_path)
if file is not None:
modified_files.append(file)
def unix2dos_dir(dir_name):
modified_files = []
os.path.walk(dir_name, unix2dos_one_dir, modified_files)
return modified_files | null |
170,345 | import os
import sys
import re
def process_str(astr):
code = [header]
code.extend(parse_string(astr, global_names, 0, 1))
return ''.join(code)
def resolve_includes(source):
d = os.path.dirname(source)
with open(source) as fid:
lines = []
for line in fid:
m = include_src_re.match(line)
if m:
fn = m.group('name')
if not os.path.isabs(fn):
fn = os.path.join(d, fn)
if os.path.isfile(fn):
lines.extend(resolve_includes(fn))
else:
lines.append(line)
else:
lines.append(line)
return lines
def process_file(source):
lines = resolve_includes(source)
sourcefile = os.path.normcase(source).replace("\\", "\\\\")
try:
code = process_str(''.join(lines))
except ValueError as e:
raise ValueError('In "%s" loop at %s' % (sourcefile, e)) from None
return '#line 1 "%s"\n%s' % (sourcefile, code) | null |
170,346 | import os
import sys
import re
def unique_key(adict):
# this obtains a unique key given a dictionary
# currently it works by appending together n of the letters of the
# current keys and increasing n until a unique key is found
# -- not particularly quick
allkeys = list(adict.keys())
done = False
n = 1
while not done:
newkey = "".join([x[:n] for x in allkeys])
if newkey in allkeys:
n += 1
else:
done = True
return newkey | null |
170,347 | import os
import sys
import subprocess
import locale
import warnings
from numpy.distutils.misc_util import is_sequence, make_temp_file
from numpy.distutils import log
import warnings
warnings.warn("\n\n"
" `numpy.distutils` is deprecated since NumPy 1.23.0, as a result\n"
" of the deprecation of `distutils` itself. It will be removed for\n"
" Python >= 3.12. For older Python versions it will remain present.\n"
" It is recommended to use `setuptools < 60.0` for those Python versions.\n"
" For more details, see:\n"
" https://numpy.org/devdocs/reference/distutils_status_migration.html \n\n",
DeprecationWarning, stacklevel=2
)
del warnings
def make_temp_file(suffix='', prefix='', text=True):
if not hasattr(_tdata, 'tempdir'):
_tdata.tempdir = tempfile.mkdtemp()
_tmpdirs.append(_tdata.tempdir)
fid, name = tempfile.mkstemp(suffix=suffix,
prefix=prefix,
dir=_tdata.tempdir,
text=text)
fo = os.fdopen(fid, 'w')
return fo, name
def temp_file_name():
# 2019-01-30, 1.17
warnings.warn('temp_file_name is deprecated since NumPy v1.17, use '
'tempfile.mkstemp instead', DeprecationWarning, stacklevel=1)
fo, name = make_temp_file()
fo.close()
return name | null |
170,348 | import os
import sys
import subprocess
import locale
import warnings
from numpy.distutils.misc_util import is_sequence, make_temp_file
from numpy.distutils import log
def get_pythonexe():
pythonexe = sys.executable
if os.name in ['nt', 'dos']:
fdir, fn = os.path.split(pythonexe)
fn = fn.upper().replace('PYTHONW', 'PYTHON')
pythonexe = os.path.join(fdir, fn)
assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,)
return pythonexe | null |
170,349 | import os
import sys
import subprocess
import locale
import warnings
from numpy.distutils.misc_util import is_sequence, make_temp_file
from numpy.distutils import log
The provided code snippet includes necessary dependencies for implementing the `find_executable` function. Write a Python function `def find_executable(exe, path=None, _cache={})` to solve the following problem:
Return full path of a executable or None. Symbolic links are not followed.
Here is the function:
def find_executable(exe, path=None, _cache={}):
"""Return full path of a executable or None.
Symbolic links are not followed.
"""
key = exe, path
try:
return _cache[key]
except KeyError:
pass
log.debug('find_executable(%r)' % exe)
orig_exe = exe
if path is None:
path = os.environ.get('PATH', os.defpath)
if os.name=='posix':
realpath = os.path.realpath
else:
realpath = lambda a:a
if exe.startswith('"'):
exe = exe[1:-1]
suffixes = ['']
if os.name in ['nt', 'dos', 'os2']:
fn, ext = os.path.splitext(exe)
extra_suffixes = ['.exe', '.com', '.bat']
if ext.lower() not in extra_suffixes:
suffixes = extra_suffixes
if os.path.isabs(exe):
paths = ['']
else:
paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]
for path in paths:
fn = os.path.join(path, exe)
for s in suffixes:
f_ext = fn+s
if not os.path.islink(f_ext):
f_ext = realpath(f_ext)
if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):
log.info('Found executable %s' % f_ext)
_cache[key] = f_ext
return f_ext
log.warn('Could not locate executable %s' % orig_exe)
return None | Return full path of a executable or None. Symbolic links are not followed. |
170,350 | import os
import sys
import subprocess
import locale
import warnings
from numpy.distutils.misc_util import is_sequence, make_temp_file
from numpy.distutils import log
def _preserve_environment( names ):
log.debug('_preserve_environment(%r)' % (names))
env = {name: os.environ.get(name) for name in names}
return env
def _update_environment( **env ):
log.debug('_update_environment(...)')
for name, value in env.items():
os.environ[name] = value or ''
def _exec_command(command, use_shell=None, use_tee = None, **env):
"""
Internal workhorse for exec_command().
"""
if use_shell is None:
use_shell = os.name=='posix'
if use_tee is None:
use_tee = os.name=='posix'
if os.name == 'posix' and use_shell:
# On POSIX, subprocess always uses /bin/sh, override
sh = os.environ.get('SHELL', '/bin/sh')
if is_sequence(command):
command = [sh, '-c', ' '.join(command)]
else:
command = [sh, '-c', command]
use_shell = False
elif os.name == 'nt' and is_sequence(command):
# On Windows, join the string for CreateProcess() ourselves as
# subprocess does it a bit differently
command = ' '.join(_quote_arg(arg) for arg in command)
# Inherit environment by default
env = env or None
try:
# text is set to False so that communicate()
# will return bytes. We need to decode the output ourselves
# so that Python will not raise a UnicodeDecodeError when
# it encounters an invalid character; rather, we simply replace it
proc = subprocess.Popen(command, shell=use_shell, env=env, text=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
except OSError:
# Return 127, as os.spawn*() and /bin/sh do
return 127, ''
text, err = proc.communicate()
mylocale = locale.getpreferredencoding(False)
if mylocale is None:
mylocale = 'ascii'
text = text.decode(mylocale, errors='replace')
text = text.replace('\r\n', '\n')
# Another historical oddity
if text[-1:] == '\n':
text = text[:-1]
if use_tee and text:
print(text)
return proc.returncode, text
import warnings
warnings.warn("\n\n"
" `numpy.distutils` is deprecated since NumPy 1.23.0, as a result\n"
" of the deprecation of `distutils` itself. It will be removed for\n"
" Python >= 3.12. For older Python versions it will remain present.\n"
" It is recommended to use `setuptools < 60.0` for those Python versions.\n"
" For more details, see:\n"
" https://numpy.org/devdocs/reference/distutils_status_migration.html \n\n",
DeprecationWarning, stacklevel=2
)
del warnings
The provided code snippet includes necessary dependencies for implementing the `exec_command` function. Write a Python function `def exec_command(command, execute_in='', use_shell=None, use_tee=None, _with_python = 1, **env )` to solve the following problem:
Return (status,output) of executed command. .. deprecated:: 1.17 Use subprocess.Popen instead Parameters ---------- command : str A concatenated string of executable and arguments. execute_in : str Before running command ``cd execute_in`` and after ``cd -``. use_shell : {bool, None}, optional If True, execute ``sh -c command``. Default None (True) use_tee : {bool, None}, optional If True use tee. Default None (True) Returns ------- res : str Both stdout and stderr messages. Notes ----- On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0.
Here is the function:
def exec_command(command, execute_in='', use_shell=None, use_tee=None,
_with_python = 1, **env ):
"""
Return (status,output) of executed command.
.. deprecated:: 1.17
Use subprocess.Popen instead
Parameters
----------
command : str
A concatenated string of executable and arguments.
execute_in : str
Before running command ``cd execute_in`` and after ``cd -``.
use_shell : {bool, None}, optional
If True, execute ``sh -c command``. Default None (True)
use_tee : {bool, None}, optional
If True use tee. Default None (True)
Returns
-------
res : str
Both stdout and stderr messages.
Notes
-----
On NT, DOS systems the returned status is correct for external commands.
Wild cards will not work for non-posix systems or when use_shell=0.
"""
# 2019-01-30, 1.17
warnings.warn('exec_command is deprecated since NumPy v1.17, use '
'subprocess.Popen instead', DeprecationWarning, stacklevel=1)
log.debug('exec_command(%r,%s)' % (command,
','.join(['%s=%r'%kv for kv in env.items()])))
if use_tee is None:
use_tee = os.name=='posix'
if use_shell is None:
use_shell = os.name=='posix'
execute_in = os.path.abspath(execute_in)
oldcwd = os.path.abspath(os.getcwd())
if __name__[-12:] == 'exec_command':
exec_dir = os.path.dirname(os.path.abspath(__file__))
elif os.path.isfile('exec_command.py'):
exec_dir = os.path.abspath('.')
else:
exec_dir = os.path.abspath(sys.argv[0])
if os.path.isfile(exec_dir):
exec_dir = os.path.dirname(exec_dir)
if oldcwd!=execute_in:
os.chdir(execute_in)
log.debug('New cwd: %s' % execute_in)
else:
log.debug('Retaining cwd: %s' % oldcwd)
oldenv = _preserve_environment( list(env.keys()) )
_update_environment( **env )
try:
st = _exec_command(command,
use_shell=use_shell,
use_tee=use_tee,
**env)
finally:
if oldcwd!=execute_in:
os.chdir(oldcwd)
log.debug('Restored cwd to %s' % oldcwd)
_update_environment(**oldenv)
return st | Return (status,output) of executed command. .. deprecated:: 1.17 Use subprocess.Popen instead Parameters ---------- command : str A concatenated string of executable and arguments. execute_in : str Before running command ``cd execute_in`` and after ``cd -``. use_shell : {bool, None}, optional If True, execute ``sh -c command``. Default None (True) use_tee : {bool, None}, optional If True use tee. Default None (True) Returns ------- res : str Both stdout and stderr messages. Notes ----- On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0. |
170,351 | import atexit
import inspect
import os
import pprint
import re
import subprocess
import textwrap
class CCompilerOpt(_Config, _Distutils, _Cache, _CCompiler, _Feature, _Parse):
"""
A helper class for `CCompiler` aims to provide extra build options
to effectively control of compiler optimizations that are directly
related to CPU features.
"""
def __init__(self, ccompiler, cpu_baseline="min", cpu_dispatch="max", cache_path=None):
_Config.__init__(self)
_Distutils.__init__(self, ccompiler)
_Cache.__init__(self, cache_path, self.dist_info(), cpu_baseline, cpu_dispatch)
_CCompiler.__init__(self)
_Feature.__init__(self)
if not self.cc_noopt and self.cc_has_native:
self.dist_log(
"native flag is specified through environment variables. "
"force cpu-baseline='native'"
)
cpu_baseline = "native"
_Parse.__init__(self, cpu_baseline, cpu_dispatch)
# keep the requested features untouched, need it later for report
# and trace purposes
self._requested_baseline = cpu_baseline
self._requested_dispatch = cpu_dispatch
# key is the dispatch-able source and value is a tuple
# contains two items (has_baseline[boolean], dispatched-features[list])
self.sources_status = getattr(self, "sources_status", {})
# every instance should has a separate one
self.cache_private.add("sources_status")
# set it at the end to make sure the cache writing was done after init
# this class
self.hit_cache = hasattr(self, "hit_cache")
def is_cached(self):
"""
Returns True if the class loaded from the cache file
"""
return self.cache_infile and self.hit_cache
def cpu_baseline_flags(self):
"""
Returns a list of final CPU baseline compiler flags
"""
return self.parse_baseline_flags
def cpu_baseline_names(self):
"""
return a list of final CPU baseline feature names
"""
return self.parse_baseline_names
def cpu_dispatch_names(self):
"""
return a list of final CPU dispatch feature names
"""
return self.parse_dispatch_names
def try_dispatch(self, sources, src_dir=None, ccompiler=None, **kwargs):
"""
Compile one or more dispatch-able sources and generates object files,
also generates abstract C config headers and macros that
used later for the final runtime dispatching process.
The mechanism behind it is to takes each source file that specified
in 'sources' and branching it into several files depend on
special configuration statements that must be declared in the
top of each source which contains targeted CPU features,
then it compiles every branched source with the proper compiler flags.
Parameters
----------
sources : list
Must be a list of dispatch-able sources file paths,
and configuration statements must be declared inside
each file.
src_dir : str
Path of parent directory for the generated headers and wrapped sources.
If None(default) the files will generated in-place.
ccompiler : CCompiler
Distutils `CCompiler` instance to be used for compilation.
If None (default), the provided instance during the initialization
will be used instead.
**kwargs : any
Arguments to pass on to the `CCompiler.compile()`
Returns
-------
list : generated object files
Raises
------
CompileError
Raises by `CCompiler.compile()` on compiling failure.
DistutilsError
Some errors during checking the sanity of configuration statements.
See Also
--------
parse_targets :
Parsing the configuration statements of dispatch-able sources.
"""
to_compile = {}
baseline_flags = self.cpu_baseline_flags()
include_dirs = kwargs.setdefault("include_dirs", [])
for src in sources:
output_dir = os.path.dirname(src)
if src_dir:
if not output_dir.startswith(src_dir):
output_dir = os.path.join(src_dir, output_dir)
if output_dir not in include_dirs:
# To allow including the generated config header(*.dispatch.h)
# by the dispatch-able sources
include_dirs.append(output_dir)
has_baseline, targets, extra_flags = self.parse_targets(src)
nochange = self._generate_config(output_dir, src, targets, has_baseline)
for tar in targets:
tar_src = self._wrap_target(output_dir, src, tar, nochange=nochange)
flags = tuple(extra_flags + self.feature_flags(tar))
to_compile.setdefault(flags, []).append(tar_src)
if has_baseline:
flags = tuple(extra_flags + baseline_flags)
to_compile.setdefault(flags, []).append(src)
self.sources_status[src] = (has_baseline, targets)
# For these reasons, the sources are compiled in a separate loop:
# - Gathering all sources with the same flags to benefit from
# the parallel compiling as much as possible.
# - To generate all config headers of the dispatchable sources,
# before the compilation in case if there are dependency relationships
# among them.
objects = []
for flags, srcs in to_compile.items():
objects += self.dist_compile(
srcs, list(flags), ccompiler=ccompiler, **kwargs
)
return objects
def generate_dispatch_header(self, header_path):
"""
Generate the dispatch header which contains the #definitions and headers
for platform-specific instruction-sets for the enabled CPU baseline and
dispatch-able features.
Its highly recommended to take a look at the generated header
also the generated source files via `try_dispatch()`
in order to get the full picture.
"""
self.dist_log("generate CPU dispatch header: (%s)" % header_path)
baseline_names = self.cpu_baseline_names()
dispatch_names = self.cpu_dispatch_names()
baseline_len = len(baseline_names)
dispatch_len = len(dispatch_names)
header_dir = os.path.dirname(header_path)
if not os.path.exists(header_dir):
self.dist_log(
f"dispatch header dir {header_dir} does not exist, creating it",
stderr=True
)
os.makedirs(header_dir)
with open(header_path, 'w') as f:
baseline_calls = ' \\\n'.join([
(
"\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))"
) % (self.conf_c_prefix, f)
for f in baseline_names
])
dispatch_calls = ' \\\n'.join([
(
"\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))"
) % (self.conf_c_prefix, f)
for f in dispatch_names
])
f.write(textwrap.dedent("""\
/*
* AUTOGENERATED DON'T EDIT
* Please make changes to the code generator (distutils/ccompiler_opt.py)
*/
#define {pfx}WITH_CPU_BASELINE "{baseline_str}"
#define {pfx}WITH_CPU_DISPATCH "{dispatch_str}"
#define {pfx}WITH_CPU_BASELINE_N {baseline_len}
#define {pfx}WITH_CPU_DISPATCH_N {dispatch_len}
#define {pfx}WITH_CPU_EXPAND_(X) X
#define {pfx}WITH_CPU_BASELINE_CALL(MACRO_TO_CALL, ...) \\
{baseline_calls}
#define {pfx}WITH_CPU_DISPATCH_CALL(MACRO_TO_CALL, ...) \\
{dispatch_calls}
""").format(
pfx=self.conf_c_prefix, baseline_str=" ".join(baseline_names),
dispatch_str=" ".join(dispatch_names), baseline_len=baseline_len,
dispatch_len=dispatch_len, baseline_calls=baseline_calls,
dispatch_calls=dispatch_calls
))
baseline_pre = ''
for name in baseline_names:
baseline_pre += self.feature_c_preprocessor(name, tabs=1) + '\n'
dispatch_pre = ''
for name in dispatch_names:
dispatch_pre += textwrap.dedent("""\
#ifdef {pfx}CPU_TARGET_{name}
{pre}
#endif /*{pfx}CPU_TARGET_{name}*/
""").format(
pfx=self.conf_c_prefix_, name=name, pre=self.feature_c_preprocessor(
name, tabs=1
))
f.write(textwrap.dedent("""\
/******* baseline features *******/
{baseline_pre}
/******* dispatch features *******/
{dispatch_pre}
""").format(
pfx=self.conf_c_prefix_, baseline_pre=baseline_pre,
dispatch_pre=dispatch_pre
))
def report(self, full=False):
report = []
platform_rows = []
baseline_rows = []
dispatch_rows = []
report.append(("Platform", platform_rows))
report.append(("", ""))
report.append(("CPU baseline", baseline_rows))
report.append(("", ""))
report.append(("CPU dispatch", dispatch_rows))
########## platform ##########
platform_rows.append(("Architecture", (
"unsupported" if self.cc_on_noarch else self.cc_march)
))
platform_rows.append(("Compiler", (
"unix-like" if self.cc_is_nocc else self.cc_name)
))
########## baseline ##########
if self.cc_noopt:
baseline_rows.append(("Requested", "optimization disabled"))
else:
baseline_rows.append(("Requested", repr(self._requested_baseline)))
baseline_names = self.cpu_baseline_names()
baseline_rows.append((
"Enabled", (' '.join(baseline_names) if baseline_names else "none")
))
baseline_flags = self.cpu_baseline_flags()
baseline_rows.append((
"Flags", (' '.join(baseline_flags) if baseline_flags else "none")
))
extra_checks = []
for name in baseline_names:
extra_checks += self.feature_extra_checks(name)
baseline_rows.append((
"Extra checks", (' '.join(extra_checks) if extra_checks else "none")
))
########## dispatch ##########
if self.cc_noopt:
baseline_rows.append(("Requested", "optimization disabled"))
else:
dispatch_rows.append(("Requested", repr(self._requested_dispatch)))
dispatch_names = self.cpu_dispatch_names()
dispatch_rows.append((
"Enabled", (' '.join(dispatch_names) if dispatch_names else "none")
))
########## Generated ##########
# TODO:
# - collect object names from 'try_dispatch()'
# then get size of each object and printed
# - give more details about the features that not
# generated due compiler support
# - find a better output's design.
#
target_sources = {}
for source, (_, targets) in self.sources_status.items():
for tar in targets:
target_sources.setdefault(tar, []).append(source)
if not full or not target_sources:
generated = ""
for tar in self.feature_sorted(target_sources):
sources = target_sources[tar]
name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
generated += name + "[%d] " % len(sources)
dispatch_rows.append(("Generated", generated[:-1] if generated else "none"))
else:
dispatch_rows.append(("Generated", ''))
for tar in self.feature_sorted(target_sources):
sources = target_sources[tar]
pretty_name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
flags = ' '.join(self.feature_flags(tar))
implies = ' '.join(self.feature_sorted(self.feature_implies(tar)))
detect = ' '.join(self.feature_detect(tar))
extra_checks = []
for name in ((tar,) if isinstance(tar, str) else tar):
extra_checks += self.feature_extra_checks(name)
extra_checks = (' '.join(extra_checks) if extra_checks else "none")
dispatch_rows.append(('', ''))
dispatch_rows.append((pretty_name, implies))
dispatch_rows.append(("Flags", flags))
dispatch_rows.append(("Extra checks", extra_checks))
dispatch_rows.append(("Detect", detect))
for src in sources:
dispatch_rows.append(("", src))
###############################
# TODO: add support for 'markdown' format
text = []
secs_len = [len(secs) for secs, _ in report]
cols_len = [len(col) for _, rows in report for col, _ in rows]
tab = ' ' * 2
pad = max(max(secs_len), max(cols_len))
for sec, rows in report:
if not sec:
text.append("") # empty line
continue
sec += ' ' * (pad - len(sec))
text.append(sec + tab + ': ')
for col, val in rows:
col += ' ' * (pad - len(col))
text.append(tab + col + ': ' + val)
return '\n'.join(text)
def _wrap_target(self, output_dir, dispatch_src, target, nochange=False):
assert(isinstance(target, (str, tuple)))
if isinstance(target, str):
ext_name = target_name = target
else:
# multi-target
ext_name = '.'.join(target)
target_name = '__'.join(target)
wrap_path = os.path.join(output_dir, os.path.basename(dispatch_src))
wrap_path = "{0}.{2}{1}".format(*os.path.splitext(wrap_path), ext_name.lower())
if nochange and os.path.exists(wrap_path):
return wrap_path
self.dist_log("wrap dispatch-able target -> ", wrap_path)
# sorting for readability
features = self.feature_sorted(self.feature_implies_c(target))
target_join = "#define %sCPU_TARGET_" % self.conf_c_prefix_
target_defs = [target_join + f for f in features]
target_defs = '\n'.join(target_defs)
with open(wrap_path, "w") as fd:
fd.write(textwrap.dedent("""\
/**
* AUTOGENERATED DON'T EDIT
* Please make changes to the code generator \
(distutils/ccompiler_opt.py)
*/
#define {pfx}CPU_TARGET_MODE
#define {pfx}CPU_TARGET_CURRENT {target_name}
{target_defs}
#include "{path}"
""").format(
pfx=self.conf_c_prefix_, target_name=target_name,
path=os.path.abspath(dispatch_src), target_defs=target_defs
))
return wrap_path
def _generate_config(self, output_dir, dispatch_src, targets, has_baseline=False):
config_path = os.path.basename(dispatch_src)
config_path = os.path.splitext(config_path)[0] + '.h'
config_path = os.path.join(output_dir, config_path)
# check if targets didn't change to avoid recompiling
cache_hash = self.cache_hash(targets, has_baseline)
try:
with open(config_path) as f:
last_hash = f.readline().split("cache_hash:")
if len(last_hash) == 2 and int(last_hash[1]) == cache_hash:
return True
except OSError:
pass
os.makedirs(os.path.dirname(config_path), exist_ok=True)
self.dist_log("generate dispatched config -> ", config_path)
dispatch_calls = []
for tar in targets:
if isinstance(tar, str):
target_name = tar
else: # multi target
target_name = '__'.join([t for t in tar])
req_detect = self.feature_detect(tar)
req_detect = '&&'.join([
"CHK(%s)" % f for f in req_detect
])
dispatch_calls.append(
"\t%sCPU_DISPATCH_EXPAND_(CB((%s), %s, __VA_ARGS__))" % (
self.conf_c_prefix_, req_detect, target_name
))
dispatch_calls = ' \\\n'.join(dispatch_calls)
if has_baseline:
baseline_calls = (
"\t%sCPU_DISPATCH_EXPAND_(CB(__VA_ARGS__))"
) % self.conf_c_prefix_
else:
baseline_calls = ''
with open(config_path, "w") as fd:
fd.write(textwrap.dedent("""\
// cache_hash:{cache_hash}
/**
* AUTOGENERATED DON'T EDIT
* Please make changes to the code generator (distutils/ccompiler_opt.py)
*/
#ifndef {pfx}CPU_DISPATCH_EXPAND_
#define {pfx}CPU_DISPATCH_EXPAND_(X) X
#endif
#undef {pfx}CPU_DISPATCH_BASELINE_CALL
#undef {pfx}CPU_DISPATCH_CALL
#define {pfx}CPU_DISPATCH_BASELINE_CALL(CB, ...) \\
{baseline_calls}
#define {pfx}CPU_DISPATCH_CALL(CHK, CB, ...) \\
{dispatch_calls}
""").format(
pfx=self.conf_c_prefix_, baseline_calls=baseline_calls,
dispatch_calls=dispatch_calls, cache_hash=cache_hash
))
return False
The provided code snippet includes necessary dependencies for implementing the `new_ccompiler_opt` function. Write a Python function `def new_ccompiler_opt(compiler, dispatch_hpath, **kwargs)` to solve the following problem:
Create a new instance of 'CCompilerOpt' and generate the dispatch header which contains the #definitions and headers of platform-specific instruction-sets for the enabled CPU baseline and dispatch-able features. Parameters ---------- compiler : CCompiler instance dispatch_hpath : str path of the dispatch header **kwargs: passed as-is to `CCompilerOpt(...)` Returns ------- new instance of CCompilerOpt
Here is the function:
def new_ccompiler_opt(compiler, dispatch_hpath, **kwargs):
"""
Create a new instance of 'CCompilerOpt' and generate the dispatch header
which contains the #definitions and headers of platform-specific instruction-sets for
the enabled CPU baseline and dispatch-able features.
Parameters
----------
compiler : CCompiler instance
dispatch_hpath : str
path of the dispatch header
**kwargs: passed as-is to `CCompilerOpt(...)`
Returns
-------
new instance of CCompilerOpt
"""
opt = CCompilerOpt(compiler, **kwargs)
if not os.path.exists(dispatch_hpath) or not opt.is_cached():
opt.generate_dispatch_header(dispatch_hpath)
return opt | Create a new instance of 'CCompilerOpt' and generate the dispatch header which contains the #definitions and headers of platform-specific instruction-sets for the enabled CPU baseline and dispatch-able features. Parameters ---------- compiler : CCompiler instance dispatch_hpath : str path of the dispatch header **kwargs: passed as-is to `CCompilerOpt(...)` Returns ------- new instance of CCompilerOpt |
170,352 | import sys
import re
import os
from configparser import RawConfigParser
class FormatError(OSError):
"""
Exception thrown when there is a problem parsing a configuration file.
"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class VariableSet:
"""
Container object for the variables defined in a config file.
`VariableSet` can be used as a plain dictionary, with the variable names
as keys.
Parameters
----------
d : dict
Dict of items in the "variables" section of the configuration file.
"""
def __init__(self, d):
self._raw_data = dict([(k, v) for k, v in d.items()])
self._re = {}
self._re_sub = {}
self._init_parse()
def _init_parse(self):
for k, v in self._raw_data.items():
self._init_parse_var(k, v)
def _init_parse_var(self, name, value):
self._re[name] = re.compile(r'\$\{%s\}' % name)
self._re_sub[name] = value
def interpolate(self, value):
# Brute force: we keep interpolating until there is no '${var}' anymore
# or until interpolated string is equal to input string
def _interpolate(value):
for k in self._re.keys():
value = self._re[k].sub(self._re_sub[k], value)
return value
while _VAR.search(value):
nvalue = _interpolate(value)
if nvalue == value:
break
value = nvalue
return value
def variables(self):
"""
Return the list of variable names.
Parameters
----------
None
Returns
-------
names : list of str
The names of all variables in the `VariableSet` instance.
"""
return list(self._raw_data.keys())
# Emulate a dict to set/get variables values
def __getitem__(self, name):
return self._raw_data[name]
def __setitem__(self, name, value):
self._raw_data[name] = value
self._init_parse_var(name, value)
def parse_variables(config):
if not config.has_section('variables'):
raise FormatError("No variables section found !")
d = {}
for name, value in config.items("variables"):
d[name] = value
return VariableSet(d) | null |
170,353 | import sys
import re
import os
from configparser import RawConfigParser
def parse_sections(config):
return meta_d, r | null |
170,354 | import os
from distutils.msvc9compiler import MSVCCompiler as _MSVCCompiler
from .system_info import platform_bits
The provided code snippet includes necessary dependencies for implementing the `_merge` function. Write a Python function `def _merge(old, new)` to solve the following problem:
Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current environment, or the same as the old string if obtained from the same environment. The aim here is not to append the new string if it is already contained in the old string so as to limit the growth of the environment string. Parameters ---------- old : string Previous environment string. new : string New environment string. Returns ------- ret : string Updated environment string.
Here is the function:
def _merge(old, new):
"""Concatenate two environment paths avoiding repeats.
Here `old` is the environment string before the base class initialize
function is called and `new` is the string after the call. The new string
will be a fixed string if it is not obtained from the current environment,
or the same as the old string if obtained from the same environment. The aim
here is not to append the new string if it is already contained in the old
string so as to limit the growth of the environment string.
Parameters
----------
old : string
Previous environment string.
new : string
New environment string.
Returns
-------
ret : string
Updated environment string.
"""
if not old:
return new
if new in old:
return old
# Neither new nor old is empty. Give old priority.
return ';'.join([old, new]) | Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current environment, or the same as the old string if obtained from the same environment. The aim here is not to append the new string if it is already contained in the old string so as to limit the growth of the environment string. Parameters ---------- old : string Previous environment string. new : string New environment string. Returns ------- ret : string Updated environment string. |
170,355 | import os
import platform
import re
import sys
import types
import warnings
from subprocess import getstatusoutput
def getoutput(cmd, successful_status=(0,), stacklevel=1):
try:
status, output = getstatusoutput(cmd)
except OSError as e:
warnings.warn(str(e), UserWarning, stacklevel=stacklevel)
return False, ""
if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status:
return True, output
return False, output
def command_info(successful_status=(0,), stacklevel=1, **kw):
info = {}
for key in kw:
ok, output = getoutput(kw[key], successful_status=successful_status,
stacklevel=stacklevel+1)
if ok:
info[key] = output.strip()
return info | null |
170,356 | import os
import platform
import re
import sys
import types
import warnings
from subprocess import getstatusoutput
def command_by_line(cmd, successful_status=(0,), stacklevel=1):
ok, output = getoutput(cmd, successful_status=successful_status,
stacklevel=stacklevel+1)
if not ok:
return
for line in output.splitlines():
yield line.strip()
def key_value_from_command(cmd, sep, successful_status=(0,),
stacklevel=1):
d = {}
for line in command_by_line(cmd, successful_status=successful_status,
stacklevel=stacklevel+1):
l = [s.strip() for s in line.split(sep, 1)]
if len(l) == 2:
d[l[0]] = l[1]
return d | null |
170,357 | import os
import platform
import sys
import subprocess
import re
import textwrap
import numpy.distutils.ccompiler
from numpy.distutils import log
import distutils.cygwinccompiler
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import UnknownFileError
from numpy.distutils.misc_util import (msvc_runtime_library,
msvc_runtime_version,
msvc_runtime_major,
get_build_architecture)
def msvc_runtime_library():
"Return name of MSVC runtime library if Python was built with MSVC >= 7"
ver = msvc_runtime_major ()
if ver:
if ver < 140:
return "msvcr%i" % ver
else:
return "vcruntime%i" % ver
else:
return None
The provided code snippet includes necessary dependencies for implementing the `get_msvcr_replacement` function. Write a Python function `def get_msvcr_replacement()` to solve the following problem:
Replacement for outdated version of get_msvcr from cygwinccompiler
Here is the function:
def get_msvcr_replacement():
"""Replacement for outdated version of get_msvcr from cygwinccompiler"""
msvcr = msvc_runtime_library()
return [] if msvcr is None else [msvcr] | Replacement for outdated version of get_msvcr from cygwinccompiler |
170,358 | import os
import platform
import sys
import subprocess
import re
import textwrap
import numpy.distutils.ccompiler
from numpy.distutils import log
import distutils.cygwinccompiler
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import UnknownFileError
from numpy.distutils.misc_util import (msvc_runtime_library,
msvc_runtime_version,
msvc_runtime_major,
get_build_architecture)
def generate_def(dll, dfile):
def find_dll(dll_name):
if sys.platform == 'win32':
try:
import msvcrt
# I took one version in my SxS directory: no idea if it is the good
# one, and we can't retrieve it from python
_MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42"
_MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8"
# Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0
# on Windows XP:
_MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460"
crt_ver = getattr(msvcrt, 'CRT_ASSEMBLY_VERSION', None)
if crt_ver is not None: # Available at least back to Python 3.3
maj, min = re.match(r'(\d+)\.(\d)', crt_ver).groups()
_MSVCRVER_TO_FULLVER[maj + min] = crt_ver
del maj, min
del crt_ver
except ImportError:
# If we are here, means python was not built with MSVC. Not sure what
# to do in that case: manifest building will fail, but it should not be
# used in that case anyway
log.warn('Cannot import msvcrt: using manifest will not be possible')
def msvc_runtime_library():
def msvc_runtime_major():
def build_msvcr_library(debug=False):
if os.name != 'nt':
return False
# If the version number is None, then we couldn't find the MSVC runtime at
# all, because we are running on a Python distribution which is customed
# compiled; trust that the compiler is the same as the one available to us
# now, and that it is capable of linking with the correct runtime without
# any extra options.
msvcr_ver = msvc_runtime_major()
if msvcr_ver is None:
log.debug('Skip building import library: '
'Runtime is not compiled with MSVC')
return False
# Skip using a custom library for versions < MSVC 8.0
if msvcr_ver < 80:
log.debug('Skip building msvcr library:'
' custom functionality not present')
return False
msvcr_name = msvc_runtime_library()
if debug:
msvcr_name += 'd'
# Skip if custom library already exists
out_name = "lib%s.a" % msvcr_name
out_file = os.path.join(sys.prefix, 'libs', out_name)
if os.path.isfile(out_file):
log.debug('Skip building msvcr library: "%s" exists' %
(out_file,))
return True
# Find the msvcr dll
msvcr_dll_name = msvcr_name + '.dll'
dll_file = find_dll(msvcr_dll_name)
if not dll_file:
log.warn('Cannot build msvcr library: "%s" not found' %
msvcr_dll_name)
return False
def_name = "lib%s.def" % msvcr_name
def_file = os.path.join(sys.prefix, 'libs', def_name)
log.info('Building msvcr library: "%s" (from %s)' \
% (out_file, dll_file))
# Generate a symbol definition file from the msvcr dll
generate_def(dll_file, def_file)
# Create a custom mingw library for the given symbol definitions
cmd = ['dlltool', '-d', def_file, '-l', out_file]
retcode = subprocess.call(cmd)
# Clean up symbol definitions
os.remove(def_file)
return (not retcode) | null |
170,359 | import os
import platform
import sys
import subprocess
import re
import textwrap
import numpy.distutils.ccompiler
from numpy.distutils import log
import distutils.cygwinccompiler
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import UnknownFileError
from numpy.distutils.misc_util import (msvc_runtime_library,
msvc_runtime_version,
msvc_runtime_major,
get_build_architecture)
def _build_import_library_amd64():
out_exists, out_file = _check_for_import_lib()
if out_exists:
log.debug('Skip building import library: "%s" exists', out_file)
return
# get the runtime dll for which we are building import library
dll_file = find_python_dll()
log.info('Building import library (arch=AMD64): "%s" (from %s)' %
(out_file, dll_file))
# generate symbol list from this library
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
generate_def(dll_file, def_file)
# generate import library from this symbol list
cmd = ['dlltool', '-d', def_file, '-l', out_file]
subprocess.check_call(cmd)
def _build_import_library_x86():
""" Build the import libraries for Mingw32-gcc on Windows
"""
out_exists, out_file = _check_for_import_lib()
if out_exists:
log.debug('Skip building import library: "%s" exists', out_file)
return
lib_name = "python%d%d.lib" % tuple(sys.version_info[:2])
lib_file = os.path.join(sys.prefix, 'libs', lib_name)
if not os.path.isfile(lib_file):
# didn't find library file in virtualenv, try base distribution, too,
# and use that instead if found there. for Python 2.7 venvs, the base
# directory is in attribute real_prefix instead of base_prefix.
if hasattr(sys, 'base_prefix'):
base_lib = os.path.join(sys.base_prefix, 'libs', lib_name)
elif hasattr(sys, 'real_prefix'):
base_lib = os.path.join(sys.real_prefix, 'libs', lib_name)
else:
base_lib = '' # os.path.isfile('') == False
if os.path.isfile(base_lib):
lib_file = base_lib
else:
log.warn('Cannot build import library: "%s" not found', lib_file)
return
log.info('Building import library (ARCH=x86): "%s"', out_file)
from numpy.distutils import lib2def
def_name = "python%d%d.def" % tuple(sys.version_info[:2])
def_file = os.path.join(sys.prefix, 'libs', def_name)
nm_output = lib2def.getnm(
lib2def.DEFAULT_NM + [lib_file], shell=False)
dlist, flist = lib2def.parse_nm(nm_output)
with open(def_file, 'w') as fid:
lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, fid)
dll_name = find_python_dll ()
cmd = ["dlltool",
"--dllname", dll_name,
"--def", def_file,
"--output-lib", out_file]
status = subprocess.check_output(cmd)
if status:
log.warn('Failed to build import library for gcc. Linking will fail.')
return
def get_build_architecture():
# Importing distutils.msvccompiler triggers a warning on non-Windows
# systems, so delay the import to here.
from distutils.msvccompiler import get_build_architecture
return get_build_architecture()
def build_import_library():
if os.name != 'nt':
return
arch = get_build_architecture()
if arch == 'AMD64':
return _build_import_library_amd64()
elif arch == 'Intel':
return _build_import_library_x86()
else:
raise ValueError("Unhandled arch %s" % arch) | null |
170,360 | import os
import platform
import sys
import subprocess
import re
import textwrap
import numpy.distutils.ccompiler
from numpy.distutils import log
import distutils.cygwinccompiler
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import UnknownFileError
from numpy.distutils.misc_util import (msvc_runtime_library,
msvc_runtime_version,
msvc_runtime_major,
get_build_architecture)
The provided code snippet includes necessary dependencies for implementing the `manifest_rc` function. Write a Python function `def manifest_rc(name, type='dll')` to solve the following problem:
Return the rc file used to generate the res file which will be embedded as manifest for given manifest file name, of given type ('dll' or 'exe'). Parameters ---------- name : str name of the manifest file to embed type : str {'dll', 'exe'} type of the binary which will embed the manifest
Here is the function:
def manifest_rc(name, type='dll'):
"""Return the rc file used to generate the res file which will be embedded
as manifest for given manifest file name, of given type ('dll' or
'exe').
Parameters
----------
name : str
name of the manifest file to embed
type : str {'dll', 'exe'}
type of the binary which will embed the manifest
"""
if type == 'dll':
rctype = 2
elif type == 'exe':
rctype = 1
else:
raise ValueError("Type %s not supported" % type)
return """\
#include "winuser.h"
%d RT_MANIFEST %s""" % (rctype, name) | Return the rc file used to generate the res file which will be embedded as manifest for given manifest file name, of given type ('dll' or 'exe'). Parameters ---------- name : str name of the manifest file to embed type : str {'dll', 'exe'} type of the binary which will embed the manifest |
170,361 | import os
import platform
import sys
import subprocess
import re
import textwrap
import numpy.distutils.ccompiler
from numpy.distutils import log
import distutils.cygwinccompiler
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import UnknownFileError
from numpy.distutils.misc_util import (msvc_runtime_library,
msvc_runtime_version,
msvc_runtime_major,
get_build_architecture)
def configtest_name(config):
base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c"))
return os.path.splitext(base)[0]
def rc_name(config):
# Get configtest name (including suffix)
root = configtest_name(config)
return root + ".rc" | null |
170,362 | import os
import platform
import sys
import subprocess
import re
import textwrap
import numpy.distutils.ccompiler
from numpy.distutils import log
import distutils.cygwinccompiler
from distutils.unixccompiler import UnixCCompiler
from distutils.msvccompiler import get_build_version as get_build_msvc_version
from distutils.errors import UnknownFileError
from numpy.distutils.misc_util import (msvc_runtime_library,
msvc_runtime_version,
msvc_runtime_major,
get_build_architecture)
def msvc_manifest_xml(maj, min):
"""Given a major and minor version of the MSVCR, returns the
corresponding XML file."""
try:
fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)]
except KeyError:
raise ValueError("Version %d,%d of MSVCRT not supported yet" %
(maj, min)) from None
# Don't be fooled, it looks like an XML, but it is not. In particular, it
# should not have any space before starting, and its size should be
# divisible by 4, most likely for alignment constraints when the xml is
# embedded in the binary...
# This template was copied directly from the python 2.6 binary (using
# strings.exe from mingw on python.exe).
template = textwrap.dedent("""\
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
</dependentAssembly>
</dependency>
</assembly>""")
return template % {'fullver': fullver, 'maj': maj, 'min': min}
def check_embedded_msvcr_match_linked(msver):
"""msver is the ms runtime version used for the MANIFEST."""
# check msvcr major version are the same for linking and
# embedding
maj = msvc_runtime_major()
if maj:
if not maj == int(msver):
raise ValueError(
"Discrepancy between linked msvcr " \
"(%d) and the one about to be embedded " \
"(%d)" % (int(msver), maj))
def manifest_name(config):
# Get configest name (including suffix)
root = configtest_name(config)
exext = config.compiler.exe_extension
return root + exext + ".manifest"
def generate_manifest(config):
msver = get_build_msvc_version()
if msver is not None:
if msver >= 8:
check_embedded_msvcr_match_linked(msver)
ma_str, mi_str = str(msver).split('.')
# Write the manifest file
manxml = msvc_manifest_xml(int(ma_str), int(mi_str))
with open(manifest_name(config), "w") as man:
config.temp_files.append(manifest_name(config))
man.write(manxml) | null |
170,363 | import sys
from distutils.log import *
from distutils.log import Log as old_Log
from distutils.log import _global_log
from numpy.distutils.misc_util import (red_text, default_text, cyan_text,
green_text, is_sequence, is_string)
def is_string(s):
return isinstance(s, str)
def is_sequence(seq):
if is_string(seq):
return False
try:
len(seq)
except Exception:
return False
return True
def _fix_args(args,flag=1):
if is_string(args):
return args.replace('%', '%%')
if flag and is_sequence(args):
return tuple([_fix_args(a, flag=0) for a in args])
return args | null |
170,364 | import os
import sys
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {})) | null |
170,365 | import os
import sys
The provided code snippet includes necessary dependencies for implementing the `show` function. Write a Python function `def show()` to solve the following problem:
Show libraries in the system on which NumPy was built. Print information about various resources (libraries, library directories, include directories, etc.) in the system on which NumPy was built. See Also -------- get_include : Returns the directory containing NumPy C header files. Notes ----- 1. Classes specifying the information to be printed are defined in the `numpy.distutils.system_info` module. Information may include: * ``language``: language used to write the libraries (mostly C or f77) * ``libraries``: names of libraries found in the system * ``library_dirs``: directories containing the libraries * ``include_dirs``: directories containing library header files * ``src_dirs``: directories containing library source files * ``define_macros``: preprocessor macros used by ``distutils.setup`` * ``baseline``: minimum CPU features required * ``found``: dispatched features supported in the system * ``not found``: dispatched features that are not supported in the system 2. NumPy BLAS/LAPACK Installation Notes Installing a numpy wheel (``pip install numpy`` or force it via ``pip install numpy --only-binary :numpy: numpy``) includes an OpenBLAS implementation of the BLAS and LAPACK linear algebra APIs. In this case, ``library_dirs`` reports the original build time configuration as compiled with gcc/gfortran; at run time the OpenBLAS library is in ``site-packages/numpy.libs/`` (linux), or ``site-packages/numpy/.dylibs/`` (macOS), or ``site-packages/numpy/.libs/`` (windows). Installing numpy from source (``pip install numpy --no-binary numpy``) searches for BLAS and LAPACK dynamic link libraries at build time as influenced by environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER; or the optional file ``~/.numpy-site.cfg``. NumPy remembers those locations and expects to load the same libraries at run-time. In NumPy 1.21+ on macOS, 'accelerate' (Apple's Accelerate BLAS library) is in the default build-time search order after 'openblas'. Examples -------- >>> import numpy as np >>> np.show_config() blas_opt_info: language = c define_macros = [('HAVE_CBLAS', None)] libraries = ['openblas', 'openblas'] library_dirs = ['/usr/local/lib']
Here is the function:
def show():
"""
Show libraries in the system on which NumPy was built.
Print information about various resources (libraries, library
directories, include directories, etc.) in the system on which
NumPy was built.
See Also
--------
get_include : Returns the directory containing NumPy C
header files.
Notes
-----
1. Classes specifying the information to be printed are defined
in the `numpy.distutils.system_info` module.
Information may include:
* ``language``: language used to write the libraries (mostly
C or f77)
* ``libraries``: names of libraries found in the system
* ``library_dirs``: directories containing the libraries
* ``include_dirs``: directories containing library header files
* ``src_dirs``: directories containing library source files
* ``define_macros``: preprocessor macros used by
``distutils.setup``
* ``baseline``: minimum CPU features required
* ``found``: dispatched features supported in the system
* ``not found``: dispatched features that are not supported
in the system
2. NumPy BLAS/LAPACK Installation Notes
Installing a numpy wheel (``pip install numpy`` or force it
via ``pip install numpy --only-binary :numpy: numpy``) includes
an OpenBLAS implementation of the BLAS and LAPACK linear algebra
APIs. In this case, ``library_dirs`` reports the original build
time configuration as compiled with gcc/gfortran; at run time
the OpenBLAS library is in
``site-packages/numpy.libs/`` (linux), or
``site-packages/numpy/.dylibs/`` (macOS), or
``site-packages/numpy/.libs/`` (windows).
Installing numpy from source
(``pip install numpy --no-binary numpy``) searches for BLAS and
LAPACK dynamic link libraries at build time as influenced by
environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and
NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER;
or the optional file ``~/.numpy-site.cfg``.
NumPy remembers those locations and expects to load the same
libraries at run-time.
In NumPy 1.21+ on macOS, 'accelerate' (Apple's Accelerate BLAS
library) is in the default build-time search order after
'openblas'.
Examples
--------
>>> import numpy as np
>>> np.show_config()
blas_opt_info:
language = c
define_macros = [('HAVE_CBLAS', None)]
libraries = ['openblas', 'openblas']
library_dirs = ['/usr/local/lib']
"""
from numpy.core._multiarray_umath import (
__cpu_features__, __cpu_baseline__, __cpu_dispatch__
)
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not type({}): continue
print(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
features_found, features_not_found = [], []
for feature in __cpu_dispatch__:
if __cpu_features__[feature]:
features_found.append(feature)
else:
features_not_found.append(feature)
print("Supported SIMD extensions in this NumPy install:")
print(" baseline = %s" % (','.join(__cpu_baseline__)))
print(" found = %s" % (','.join(features_found)))
print(" not found = %s" % (','.join(features_not_found))) | Show libraries in the system on which NumPy was built. Print information about various resources (libraries, library directories, include directories, etc.) in the system on which NumPy was built. See Also -------- get_include : Returns the directory containing NumPy C header files. Notes ----- 1. Classes specifying the information to be printed are defined in the `numpy.distutils.system_info` module. Information may include: * ``language``: language used to write the libraries (mostly C or f77) * ``libraries``: names of libraries found in the system * ``library_dirs``: directories containing the libraries * ``include_dirs``: directories containing library header files * ``src_dirs``: directories containing library source files * ``define_macros``: preprocessor macros used by ``distutils.setup`` * ``baseline``: minimum CPU features required * ``found``: dispatched features supported in the system * ``not found``: dispatched features that are not supported in the system 2. NumPy BLAS/LAPACK Installation Notes Installing a numpy wheel (``pip install numpy`` or force it via ``pip install numpy --only-binary :numpy: numpy``) includes an OpenBLAS implementation of the BLAS and LAPACK linear algebra APIs. In this case, ``library_dirs`` reports the original build time configuration as compiled with gcc/gfortran; at run time the OpenBLAS library is in ``site-packages/numpy.libs/`` (linux), or ``site-packages/numpy/.dylibs/`` (macOS), or ``site-packages/numpy/.libs/`` (windows). Installing numpy from source (``pip install numpy --no-binary numpy``) searches for BLAS and LAPACK dynamic link libraries at build time as influenced by environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER; or the optional file ``~/.numpy-site.cfg``. NumPy remembers those locations and expects to load the same libraries at run-time. In NumPy 1.21+ on macOS, 'accelerate' (Apple's Accelerate BLAS library) is in the default build-time search order after 'openblas'. Examples -------- >>> import numpy as np >>> np.show_config() blas_opt_info: language = c define_macros = [('HAVE_CBLAS', None)] libraries = ['openblas', 'openblas'] library_dirs = ['/usr/local/lib'] |
170,368 | import re
import traitlets
import datetime as dt
The provided code snippet includes necessary dependencies for implementing the `datetime_from_json` function. Write a Python function `def datetime_from_json(js, manager)` to solve the following problem:
Deserialize a Python datetime object from json.
Here is the function:
def datetime_from_json(js, manager):
"""Deserialize a Python datetime object from json."""
if js is None:
return None
else:
try:
return dt.datetime(
js["year"],
js["month"] + 1, # Months are 1-based in Python
js["date"],
js["hours"],
js["minutes"],
js["seconds"],
js["milliseconds"] * 1000,
).astimezone()
except (ValueError, OSError):
# If year is outside valid range for conversion,
# return UTC datetime
return dt.datetime(
js["year"],
js["month"] + 1, # Months are 1-based in Python
js["date"],
js["hours"],
js["minutes"],
js["seconds"],
js["milliseconds"] * 1000,
dt.timezone.utc,
) | Deserialize a Python datetime object from json. |
170,369 | import re
import traitlets
import datetime as dt
The provided code snippet includes necessary dependencies for implementing the `naive_to_json` function. Write a Python function `def naive_to_json(pydt, manager)` to solve the following problem:
Serialize a naive Python datetime object to json. Instantiating a JavaScript Date object with a string assumes that the string is a UTC string, while instantiating it with constructor arguments assumes that it's in local time: >>> cdate = new Date('2015-05-12') Mon May 11 2015 20:00:00 GMT-0400 (Eastern Daylight Time) >>> cdate = new Date(2015, 4, 12) // Months are 0-based indices in JS Tue May 12 2015 00:00:00 GMT-0400 (Eastern Daylight Time) Attributes of this dictionary are to be passed to the JavaScript Date constructor.
Here is the function:
def naive_to_json(pydt, manager):
"""Serialize a naive Python datetime object to json.
Instantiating a JavaScript Date object with a string assumes that the
string is a UTC string, while instantiating it with constructor arguments
assumes that it's in local time:
>>> cdate = new Date('2015-05-12')
Mon May 11 2015 20:00:00 GMT-0400 (Eastern Daylight Time)
>>> cdate = new Date(2015, 4, 12) // Months are 0-based indices in JS
Tue May 12 2015 00:00:00 GMT-0400 (Eastern Daylight Time)
Attributes of this dictionary are to be passed to the JavaScript Date
constructor.
"""
if pydt is None:
return None
else:
naivedt = pydt.replace(tzinfo=None)
return dict(
year=naivedt.year,
month=naivedt.month - 1, # Months are 0-based indices in JS
date=naivedt.day,
hours=naivedt.hour, # Hours, Minutes, Seconds and Milliseconds
minutes=naivedt.minute, # are plural in JS
seconds=naivedt.second,
milliseconds=naivedt.microsecond / 1000,
) | Serialize a naive Python datetime object to json. Instantiating a JavaScript Date object with a string assumes that the string is a UTC string, while instantiating it with constructor arguments assumes that it's in local time: >>> cdate = new Date('2015-05-12') Mon May 11 2015 20:00:00 GMT-0400 (Eastern Daylight Time) >>> cdate = new Date(2015, 4, 12) // Months are 0-based indices in JS Tue May 12 2015 00:00:00 GMT-0400 (Eastern Daylight Time) Attributes of this dictionary are to be passed to the JavaScript Date constructor. |
170,370 | import re
import traitlets
import datetime as dt
The provided code snippet includes necessary dependencies for implementing the `naive_from_json` function. Write a Python function `def naive_from_json(js, manager)` to solve the following problem:
Deserialize a naive Python datetime object from json.
Here is the function:
def naive_from_json(js, manager):
"""Deserialize a naive Python datetime object from json."""
if js is None:
return None
else:
return dt.datetime(
js["year"],
js["month"] + 1, # Months are 1-based in Python
js["date"],
js["hours"],
js["minutes"],
js["seconds"],
js["milliseconds"] * 1000,
) | Deserialize a naive Python datetime object from json. |
170,371 | import re
import traitlets
import datetime as dt
The provided code snippet includes necessary dependencies for implementing the `date_to_json` function. Write a Python function `def date_to_json(pydate, manager)` to solve the following problem:
Serialize a Python date object. Attributes of this dictionary are to be passed to the JavaScript Date constructor.
Here is the function:
def date_to_json(pydate, manager):
"""Serialize a Python date object.
Attributes of this dictionary are to be passed to the JavaScript Date
constructor.
"""
if pydate is None:
return None
else:
return dict(
year=pydate.year,
month=pydate.month - 1, # Months are 0-based indices in JS
date=pydate.day
) | Serialize a Python date object. Attributes of this dictionary are to be passed to the JavaScript Date constructor. |
170,372 | import re
import traitlets
import datetime as dt
The provided code snippet includes necessary dependencies for implementing the `date_from_json` function. Write a Python function `def date_from_json(js, manager)` to solve the following problem:
Deserialize a Javascript date.
Here is the function:
def date_from_json(js, manager):
"""Deserialize a Javascript date."""
if js is None:
return None
else:
return dt.date(
js['year'],
js['month'] + 1, # Months are 1-based in Python
js['date'],
) | Deserialize a Javascript date. |
170,373 | import re
import traitlets
import datetime as dt
The provided code snippet includes necessary dependencies for implementing the `time_to_json` function. Write a Python function `def time_to_json(pyt, manager)` to solve the following problem:
Serialize a Python time object to json.
Here is the function:
def time_to_json(pyt, manager):
"""Serialize a Python time object to json."""
if pyt is None:
return None
else:
return dict(
hours=pyt.hour, # Hours, Minutes, Seconds and Milliseconds
minutes=pyt.minute, # are plural in JS
seconds=pyt.second,
milliseconds=pyt.microsecond / 1000,
) | Serialize a Python time object to json. |
170,374 | import re
import traitlets
import datetime as dt
The provided code snippet includes necessary dependencies for implementing the `time_from_json` function. Write a Python function `def time_from_json(js, manager)` to solve the following problem:
Deserialize a Python time object from json.
Here is the function:
def time_from_json(js, manager):
"""Deserialize a Python time object from json."""
if js is None:
return None
else:
return dt.time(
js["hours"], js["minutes"], js["seconds"], js["milliseconds"] * 1000
) | Deserialize a Python time object from json. |
170,375 | import re
import traitlets
import datetime as dt
The provided code snippet includes necessary dependencies for implementing the `datetime_from_json` function. Write a Python function `def datetime_from_json(js, manager)` to solve the following problem:
Deserialize a Python datetime object from json.
Here is the function:
def datetime_from_json(js, manager):
"""Deserialize a Python datetime object from json."""
if js is None:
return None
else:
try:
return dt.datetime(
js["year"],
js["month"] + 1, # Months are 1-based in Python
js["date"],
js["hours"],
js["minutes"],
js["seconds"],
js["milliseconds"] * 1000,
dt.timezone.utc,
).astimezone()
except (ValueError, OSError):
# If year is outside valid range for conversion,
# return naive datetime
return dt.datetime(
js["year"],
js["month"] + 1, # Months are 1-based in Python
js["date"],
js["hours"],
js["minutes"],
js["seconds"],
js["milliseconds"] * 1000,
dt.timezone.utc,
) | Deserialize a Python datetime object from json. |
170,376 | import re
import traitlets
import datetime as dt
def bytes_from_json(js, obj):
return None if js is None else js.tobytes() | null |
170,377 | from pathlib import Path
import sys
import inspect
import warnings
def _external_stacklevel(internal):
"""Find the stacklevel of the first frame that doesn't contain any of the given internal strings
The depth will be 1 at minimum in order to start checking at the caller of
the function that called this utility method.
"""
# Get the level of my caller's caller
level = 2
frame = _get_frame(level)
# Normalize the path separators:
normalized_internal = [str(Path(s)) for s in internal]
# climb the stack frames while we see internal frames
while frame and any(s in str(Path(frame.f_code.co_filename)) for s in normalized_internal):
level +=1
frame = frame.f_back
# Return the stack level from the perspective of whoever called us (i.e., one level up)
return level-1
The provided code snippet includes necessary dependencies for implementing the `deprecation` function. Write a Python function `def deprecation(message, internal='ipywidgets/widgets/')` to solve the following problem:
Generate a deprecation warning targeting the first frame that is not 'internal' internal is a string or list of strings, which if they appear in filenames in the frames, the frames will be considered internal. Changing this can be useful if, for examnple, we know that ipywidgets is calling out to traitlets internally.
Here is the function:
def deprecation(message, internal='ipywidgets/widgets/'):
"""Generate a deprecation warning targeting the first frame that is not 'internal'
internal is a string or list of strings, which if they appear in filenames in the
frames, the frames will be considered internal. Changing this can be useful if, for examnple,
we know that ipywidgets is calling out to traitlets internally.
"""
if isinstance(internal, str):
internal = [internal]
# stack level of the first external frame from here
stacklevel = _external_stacklevel(internal)
# The call to .warn adds one frame, so bump the stacklevel up by one
warnings.warn(message, DeprecationWarning, stacklevel=stacklevel+1) | Generate a deprecation warning targeting the first frame that is not 'internal' internal is a string or list of strings, which if they appear in filenames in the frames, the frames will be considered internal. Changing this can be useful if, for examnple, we know that ipywidgets is calling out to traitlets internally. |
170,378 | from .widget import Widget, register, widget_serialization
from .widget_core import CoreWidget
from traitlets import Unicode, Tuple, Instance, TraitError
class Link(CoreWidget):
"""Link Widget
source: a (Widget, 'trait_name') tuple for the source trait
target: a (Widget, 'trait_name') tuple that should be updated
"""
_model_name = Unicode('LinkModel').tag(sync=True)
target = WidgetTraitTuple(help="The target (widget, 'trait_name') pair").tag(sync=True, **widget_serialization)
source = WidgetTraitTuple(help="The source (widget, 'trait_name') pair").tag(sync=True, **widget_serialization)
def __init__(self, source, target, **kwargs):
kwargs['source'] = source
kwargs['target'] = target
super().__init__(**kwargs)
# for compatibility with traitlet links
def unlink(self):
self.close()
The provided code snippet includes necessary dependencies for implementing the `jslink` function. Write a Python function `def jslink(attr1, attr2)` to solve the following problem:
Link two widget attributes on the frontend so they remain in sync. The link is created in the front-end and does not rely on a roundtrip to the backend. Parameters ---------- source : a (Widget, 'trait_name') tuple for the first trait target : a (Widget, 'trait_name') tuple for the second trait Examples -------- >>> c = link((widget1, 'value'), (widget2, 'value'))
Here is the function:
def jslink(attr1, attr2):
"""Link two widget attributes on the frontend so they remain in sync.
The link is created in the front-end and does not rely on a roundtrip
to the backend.
Parameters
----------
source : a (Widget, 'trait_name') tuple for the first trait
target : a (Widget, 'trait_name') tuple for the second trait
Examples
--------
>>> c = link((widget1, 'value'), (widget2, 'value'))
"""
return Link(attr1, attr2) | Link two widget attributes on the frontend so they remain in sync. The link is created in the front-end and does not rely on a roundtrip to the backend. Parameters ---------- source : a (Widget, 'trait_name') tuple for the first trait target : a (Widget, 'trait_name') tuple for the second trait Examples -------- >>> c = link((widget1, 'value'), (widget2, 'value')) |
170,379 | from .widget import Widget, register, widget_serialization
from .widget_core import CoreWidget
from traitlets import Unicode, Tuple, Instance, TraitError
class DirectionalLink(Link):
"""A directional link
source: a (Widget, 'trait_name') tuple for the source trait
target: a (Widget, 'trait_name') tuple that should be updated
when the source trait changes.
"""
_model_name = Unicode('DirectionalLinkModel').tag(sync=True)
The provided code snippet includes necessary dependencies for implementing the `jsdlink` function. Write a Python function `def jsdlink(source, target)` to solve the following problem:
Link a source widget attribute with a target widget attribute. The link is created in the front-end and does not rely on a roundtrip to the backend. Parameters ---------- source : a (Widget, 'trait_name') tuple for the source trait target : a (Widget, 'trait_name') tuple for the target trait Examples -------- >>> c = dlink((src_widget, 'value'), (tgt_widget, 'value'))
Here is the function:
def jsdlink(source, target):
"""Link a source widget attribute with a target widget attribute.
The link is created in the front-end and does not rely on a roundtrip
to the backend.
Parameters
----------
source : a (Widget, 'trait_name') tuple for the source trait
target : a (Widget, 'trait_name') tuple for the target trait
Examples
--------
>>> c = dlink((src_widget, 'value'), (tgt_widget, 'value'))
"""
return DirectionalLink(source, target) | Link a source widget attribute with a target widget attribute. The link is created in the front-end and does not rely on a roundtrip to the backend. Parameters ---------- source : a (Widget, 'trait_name') tuple for the source trait target : a (Widget, 'trait_name') tuple for the target trait Examples -------- >>> c = dlink((src_widget, 'value'), (tgt_widget, 'value')) |
170,380 | from .widget_description import DescriptionWidget, DescriptionStyle
from .valuewidget import ValueWidget
from .widget import register, widget_serialization
from .widget_core import CoreWidget
from traitlets import Instance
from .trait_types import Color, InstanceDict, NumberFormat
from traitlets import (
Unicode, CInt, Bool, CaselessStrEnum, Tuple, TraitError, default, validate
)
_int_doc_t = """
Parameters
----------
value: integer
The initial value.
"""
The provided code snippet includes necessary dependencies for implementing the `_int_doc` function. Write a Python function `def _int_doc(cls)` to solve the following problem:
Add int docstring template to class init.
Here is the function:
def _int_doc(cls):
"""Add int docstring template to class init."""
def __init__(self, value=None, **kwargs):
if value is not None:
kwargs['value'] = value
super(cls, self).__init__(**kwargs)
__init__.__doc__ = _int_doc_t
cls.__init__ = __init__
return cls | Add int docstring template to class init. |
170,381 | from .widget_description import DescriptionWidget, DescriptionStyle
from .valuewidget import ValueWidget
from .widget import register, widget_serialization
from .widget_core import CoreWidget
from traitlets import Instance
from .trait_types import Color, InstanceDict, NumberFormat
from traitlets import (
Unicode, CInt, Bool, CaselessStrEnum, Tuple, TraitError, default, validate
)
_bounded_int_doc_t = """
Parameters
----------
value: integer
The initial value.
min: integer
The lower limit for the value.
max: integer
The upper limit for the value.
step: integer
The step between allowed values.
behavior : str
slider handle and connector dragging behavior. Default is 'drag-tap'.
"""
The provided code snippet includes necessary dependencies for implementing the `_bounded_int_doc` function. Write a Python function `def _bounded_int_doc(cls)` to solve the following problem:
Add bounded int docstring template to class init.
Here is the function:
def _bounded_int_doc(cls):
"""Add bounded int docstring template to class init."""
def __init__(self, value=None, min=None, max=None, step=None, **kwargs):
if value is not None:
kwargs['value'] = value
if min is not None:
kwargs['min'] = min
if max is not None:
kwargs['max'] = max
if step is not None:
kwargs['step'] = step
super(cls, self).__init__(**kwargs)
__init__.__doc__ = _bounded_int_doc_t
cls.__init__ = __init__
return cls | Add bounded int docstring template to class init. |
170,382 | from collections.abc import Iterable, Mapping
from inspect import signature, Parameter
from inspect import getcallargs
from inspect import getfullargspec as check_argspec
import sys
from IPython import get_ipython
from . import (Widget, ValueWidget, Text,
FloatSlider, IntSlider, Checkbox, Dropdown,
VBox, Button, DOMWidget, Output)
from IPython.display import display, clear_output
from traitlets import HasTraits, Any, Unicode, observe
from numbers import Real, Integral
from warnings import warn
def show_inline_matplotlib_plots():
"""Show matplotlib plots immediately if using the inline backend.
With ipywidgets 6.0, matplotlib plots don't work well with interact when
using the inline backend that comes with ipykernel. Basically, the inline
backend only shows the plot after the entire cell executes, which does not
play well with drawing plots inside of an interact function. See
https://github.com/jupyter-widgets/ipywidgets/issues/1181/ and
https://github.com/ipython/ipython/issues/10376 for more details. This
function displays any matplotlib plots if the backend is the inline backend.
"""
if 'matplotlib' not in sys.modules:
# matplotlib hasn't been imported, nothing to do.
return
try:
import matplotlib as mpl
from ipykernel.pylab.backend_inline import flush_figures
except ImportError:
return
if (mpl.get_backend() == 'module://ipykernel.pylab.backend_inline' or
mpl.get_backend() == 'module://matplotlib_inline.backend_inline'):
flush_figures()
The provided code snippet includes necessary dependencies for implementing the `interactive_output` function. Write a Python function `def interactive_output(f, controls)` to solve the following problem:
Connect widget controls to a function. This function does not generate a user interface for the widgets (unlike `interact`). This enables customisation of the widget user interface layout. The user interface layout must be defined and displayed manually.
Here is the function:
def interactive_output(f, controls):
"""Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually.
"""
out = Output()
def observer(change):
kwargs = {k:v.value for k,v in controls.items()}
show_inline_matplotlib_plots()
with out:
clear_output(wait=True)
f(**kwargs)
show_inline_matplotlib_plots()
for k,w in controls.items():
w.observe(observer, 'value')
show_inline_matplotlib_plots()
observer(None)
return out | Connect widget controls to a function. This function does not generate a user interface for the widgets (unlike `interact`). This enables customisation of the widget user interface layout. The user interface layout must be defined and displayed manually. |
170,383 | from collections.abc import Iterable, Mapping
from inspect import signature, Parameter
from inspect import getcallargs
from inspect import getfullargspec as check_argspec
import sys
from IPython import get_ipython
from . import (Widget, ValueWidget, Text,
FloatSlider, IntSlider, Checkbox, Dropdown,
VBox, Button, DOMWidget, Output)
from IPython.display import display, clear_output
from traitlets import HasTraits, Any, Unicode, observe
from numbers import Real, Integral
from warnings import warn
The provided code snippet includes necessary dependencies for implementing the `_matches` function. Write a Python function `def _matches(o, pattern)` to solve the following problem:
Match a pattern of types in a sequence.
Here is the function:
def _matches(o, pattern):
"""Match a pattern of types in a sequence."""
if not len(o) == len(pattern):
return False
comps = zip(o,pattern)
return all(isinstance(obj,kind) for obj,kind in comps) | Match a pattern of types in a sequence. |
170,384 | from collections.abc import Iterable, Mapping
from inspect import signature, Parameter
from inspect import getcallargs
from inspect import getfullargspec as check_argspec
import sys
from IPython import get_ipython
from . import (Widget, ValueWidget, Text,
FloatSlider, IntSlider, Checkbox, Dropdown,
VBox, Button, DOMWidget, Output)
from IPython.display import display, clear_output
from traitlets import HasTraits, Any, Unicode, observe
from numbers import Real, Integral
from warnings import warn
class Real(Complex, SupportsFloat):
def __float__(self) -> float: ...
def __trunc__(self) -> int: ...
if sys.version_info >= (3, 0):
def __floor__(self) -> int: ...
def __ceil__(self) -> int: ...
def __round__(self, ndigits: None = ...) -> int: ...
def __round__(self, ndigits: int) -> Any: ...
def __divmod__(self, other: Any) -> Any: ...
def __rdivmod__(self, other: Any) -> Any: ...
def __floordiv__(self, other: Any) -> int: ...
def __rfloordiv__(self, other: Any) -> int: ...
def __mod__(self, other: Any) -> Any: ...
def __rmod__(self, other: Any) -> Any: ...
def __lt__(self, other: Any) -> bool: ...
def __le__(self, other: Any) -> bool: ...
def __complex__(self) -> complex: ...
def real(self) -> Any: ...
def imag(self) -> Any: ...
def conjugate(self) -> Any: ...
The provided code snippet includes necessary dependencies for implementing the `_get_min_max_value` function. Write a Python function `def _get_min_max_value(min, max, value=None, step=None)` to solve the following problem:
Return min, max, value given input values with possible None.
Here is the function:
def _get_min_max_value(min, max, value=None, step=None):
"""Return min, max, value given input values with possible None."""
# Either min and max need to be given, or value needs to be given
if value is None:
if min is None or max is None:
raise ValueError('unable to infer range, value from: ({}, {}, {})'.format(min, max, value))
diff = max - min
value = min + (diff / 2)
# Ensure that value has the same type as diff
if not isinstance(value, type(diff)):
value = min + (diff // 2)
else: # value is not None
if not isinstance(value, Real):
raise TypeError('expected a real number, got: %r' % value)
# Infer min/max from value
if value == 0:
# This gives (0, 1) of the correct type
vrange = (value, value + 1)
elif value > 0:
vrange = (-value, 3*value)
else:
vrange = (3*value, -value)
if min is None:
min = vrange[0]
if max is None:
max = vrange[1]
if step is not None:
# ensure value is on a step
tick = int((value - min) / step)
value = min + tick * step
if not min <= value <= max:
raise ValueError('value must be between min and max (min={}, value={}, max={})'.format(min, value, max))
return min, max, value | Return min, max, value given input values with possible None. |
170,385 | from collections.abc import Iterable, Mapping
from inspect import signature, Parameter
from inspect import getcallargs
from inspect import getfullargspec as check_argspec
import sys
from IPython import get_ipython
from . import (Widget, ValueWidget, Text,
FloatSlider, IntSlider, Checkbox, Dropdown,
VBox, Button, DOMWidget, Output)
from IPython.display import display, clear_output
from traitlets import HasTraits, Any, Unicode, observe
from numbers import Real, Integral
from warnings import warn
empty = Parameter.empty
class Parameter:
def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ...
empty: Any = ...
name: str
default: Any
annotation: Any
kind: _ParameterKind
POSITIONAL_ONLY: ClassVar[Literal[_ParameterKind.POSITIONAL_ONLY]]
POSITIONAL_OR_KEYWORD: ClassVar[Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]]
VAR_POSITIONAL: ClassVar[Literal[_ParameterKind.VAR_POSITIONAL]]
KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]]
VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]]
def replace(
self, *, name: Optional[str] = ..., kind: Optional[_ParameterKind] = ..., default: Any = ..., annotation: Any = ...
) -> Parameter: ...
The provided code snippet includes necessary dependencies for implementing the `_yield_abbreviations_for_parameter` function. Write a Python function `def _yield_abbreviations_for_parameter(param, kwargs)` to solve the following problem:
Get an abbreviation for a function parameter.
Here is the function:
def _yield_abbreviations_for_parameter(param, kwargs):
"""Get an abbreviation for a function parameter."""
name = param.name
kind = param.kind
default = param.default
not_found = (name, empty, empty)
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
if name in kwargs:
value = kwargs.pop(name)
elif default is not empty:
value = default
else:
yield not_found
yield (name, value, default)
elif kind == Parameter.VAR_KEYWORD:
# In this case name=kwargs and we yield the items in kwargs with their keys.
for k, v in kwargs.copy().items():
kwargs.pop(k)
yield k, v, empty | Get an abbreviation for a function parameter. |
170,386 |
The provided code snippet includes necessary dependencies for implementing the `doc_subst` function. Write a Python function `def doc_subst(snippets)` to solve the following problem:
Substitute format strings in class or function docstring
Here is the function:
def doc_subst(snippets):
""" Substitute format strings in class or function docstring """
def decorator(cls):
# Running python with -OO will discard docstrings (__doc__ is None).
if cls.__doc__ is not None:
# Strip the snippets to avoid trailing new lines and whitespace
stripped_snippets = {
key: snippet.strip() for (key, snippet) in snippets.items()
}
cls.__doc__ = cls.__doc__.format(**stripped_snippets)
return cls
return decorator | Substitute format strings in class or function docstring |
170,387 | from collections.abc import Iterable, Mapping
from itertools import chain
from .widget_description import DescriptionWidget, DescriptionStyle
from .valuewidget import ValueWidget
from .widget_core import CoreWidget
from .widget_style import Style
from .trait_types import InstanceDict, TypedTuple
from .widget import register, widget_serialization
from .widget_int import SliderStyle
from .docutils import doc_subst
from traitlets import (Unicode, Bool, Int, Any, Dict, TraitError, CaselessStrEnum,
Tuple, Union, observe, validate)
The provided code snippet includes necessary dependencies for implementing the `_exhaust_iterable` function. Write a Python function `def _exhaust_iterable(x)` to solve the following problem:
Exhaust any non-mapping iterable into a tuple
Here is the function:
def _exhaust_iterable(x):
"""Exhaust any non-mapping iterable into a tuple"""
if isinstance(x, Iterable) and not isinstance(x, Mapping):
return tuple(x)
return x | Exhaust any non-mapping iterable into a tuple |
170,388 | from collections.abc import Iterable, Mapping
from itertools import chain
from .widget_description import DescriptionWidget, DescriptionStyle
from .valuewidget import ValueWidget
from .widget_core import CoreWidget
from .widget_style import Style
from .trait_types import InstanceDict, TypedTuple
from .widget import register, widget_serialization
from .widget_int import SliderStyle
from .docutils import doc_subst
from traitlets import (Unicode, Bool, Int, Any, Dict, TraitError, CaselessStrEnum,
Tuple, Union, observe, validate)
The provided code snippet includes necessary dependencies for implementing the `_make_options` function. Write a Python function `def _make_options(x)` to solve the following problem:
Standardize the options tuple format. The returned tuple should be in the format (('label', value), ('label', value), ...). The input can be * an iterable of (label, value) pairs * an iterable of values, and labels will be generated * a Mapping between labels and values
Here is the function:
def _make_options(x):
"""Standardize the options tuple format.
The returned tuple should be in the format (('label', value), ('label', value), ...).
The input can be
* an iterable of (label, value) pairs
* an iterable of values, and labels will be generated
* a Mapping between labels and values
"""
if isinstance(x, Mapping):
x = x.items()
# only iterate once through the options.
xlist = tuple(x)
# Check if x is an iterable of (label, value) pairs
if all((isinstance(i, (list, tuple)) and len(i) == 2) for i in xlist):
return tuple((str(k), v) for k, v in xlist)
# Otherwise, assume x is an iterable of values
return tuple((str(i), i) for i in xlist) | Standardize the options tuple format. The returned tuple should be in the format (('label', value), ('label', value), ...). The input can be * an iterable of (label, value) pairs * an iterable of values, and labels will be generated * a Mapping between labels and values |
170,389 | from collections.abc import Iterable, Mapping
from itertools import chain
from .widget_description import DescriptionWidget, DescriptionStyle
from .valuewidget import ValueWidget
from .widget_core import CoreWidget
from .widget_style import Style
from .trait_types import InstanceDict, TypedTuple
from .widget import register, widget_serialization
from .widget_int import SliderStyle
from .docutils import doc_subst
from traitlets import (Unicode, Bool, Int, Any, Dict, TraitError, CaselessStrEnum,
Tuple, Union, observe, validate)
The provided code snippet includes necessary dependencies for implementing the `findvalue` function. Write a Python function `def findvalue(array, value, compare = lambda x, y: x == y)` to solve the following problem:
A function that uses the compare function to return a value from the list.
Here is the function:
def findvalue(array, value, compare = lambda x, y: x == y):
"A function that uses the compare function to return a value from the list."
try:
return next(x for x in array if compare(x, value))
except StopIteration:
raise ValueError('%r not in array'%value) | A function that uses the compare function to return a value from the list. |
170,390 | import os
import typing
from contextlib import contextmanager
from collections.abc import Iterable
from IPython import get_ipython
from traitlets import (
Any, HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
from json import loads as jsonloads, dumps as jsondumps
from base64 import standard_b64encode
from .utils import deprecation, _get_frame
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
import inspect
The provided code snippet includes necessary dependencies for implementing the `envset` function. Write a Python function `def envset(name, default)` to solve the following problem:
Return True if the given environment variable is turned on, otherwise False If the environment variable is set, True will be returned if it is assigned to a value other than 'no', 'n', 'false', 'off', '0', or '0.0' (case insensitive). If the environment variable is not set, the default value is returned.
Here is the function:
def envset(name, default):
"""Return True if the given environment variable is turned on, otherwise False
If the environment variable is set, True will be returned if it is assigned to a value
other than 'no', 'n', 'false', 'off', '0', or '0.0' (case insensitive).
If the environment variable is not set, the default value is returned.
"""
if name in os.environ:
return os.environ[name].lower() not in ['no', 'n', 'false', 'off', '0', '0.0']
else:
return bool(default) | Return True if the given environment variable is turned on, otherwise False If the environment variable is set, True will be returned if it is assigned to a value other than 'no', 'n', 'false', 'off', '0', or '0.0' (case insensitive). If the environment variable is not set, the default value is returned. |
170,391 | import os
import typing
from contextlib import contextmanager
from collections.abc import Iterable
from IPython import get_ipython
from traitlets import (
Any, HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
from json import loads as jsonloads, dumps as jsondumps
from base64 import standard_b64encode
from .utils import deprecation, _get_frame
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
import inspect
class Widget(LoggingHasTraits):
#-------------------------------------------------------------------------
# Class attributes
#-------------------------------------------------------------------------
_widget_construction_callback = None
_control_comm = None
def widgets():
# Because this is a static attribute, it will be accessed when initializing this class. In that case, since a user
# did not explicitly try to use this attribute, we do not want to throw a deprecation warning.
# So we check if the thing calling this static property is one of the known initialization functions in traitlets.
frame = _get_frame(2)
if not (frame.f_code.co_filename == TRAITLETS_FILE and (frame.f_code.co_name in ('getmembers', 'setup_instance', 'setup_class'))):
deprecation("Widget.widgets is deprecated.")
return _instances
def _active_widgets():
# Because this is a static attribute, it will be accessed when initializing this class. In that case, since a user
# did not explicitly try to use this attribute, we do not want to throw a deprecation warning.
# So we check if the thing calling this static property is one of the known initialization functions in traitlets.
frame = _get_frame(2)
if not (frame.f_code.co_filename == TRAITLETS_FILE and (frame.f_code.co_name in ('getmembers', 'setup_instance', 'setup_class'))):
deprecation("Widget._active_widgets is deprecated.")
return _instances
def _widget_types():
# Because this is a static attribute, it will be accessed when initializing this class. In that case, since a user
# did not explicitly try to use this attribute, we do not want to throw a deprecation warning.
# So we check if the thing calling this static property is one of the known initialization functions in traitlets.
frame = _get_frame(2)
if not (frame.f_code.co_filename == TRAITLETS_FILE and (frame.f_code.co_name in ('getmembers', 'setup_instance', 'setup_class'))):
deprecation("Widget._widget_types is deprecated.")
return _registry
def widget_types():
# Because this is a static attribute, it will be accessed when initializing this class. In that case, since a user
# did not explicitly try to use this attribute, we do not want to throw a deprecation warning.
# So we check if the thing calling this static property is one of the known initialization functions in traitlets.
frame = _get_frame(2)
if not (frame.f_code.co_filename == TRAITLETS_FILE and (frame.f_code.co_name in ('getmembers', 'setup_instance', 'setup_class'))):
deprecation("Widget.widget_types is deprecated.")
return _registry
def close_all(cls):
for widget in list(_instances.values()):
widget.close()
def on_widget_constructed(callback):
"""Registers a callback to be called when a widget is constructed.
The callback must have the following signature:
callback(widget)"""
Widget._widget_construction_callback = callback
def _call_widget_constructed(widget):
"""Static method, called when a widget is constructed."""
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
Widget._widget_construction_callback(widget)
def handle_control_comm_opened(cls, comm, msg):
"""
Class method, called when the comm-open message on the
"jupyter.widget.control" comm channel is received
"""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != CONTROL_PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget control protocol versions: received version %r, expected version %r"%(version, __control_protocol_version__))
cls._control_comm = comm
cls._control_comm.on_msg(cls._handle_control_comm_msg)
def _handle_control_comm_msg(cls, msg):
# This shouldn't happen unless someone calls this method manually
if cls._control_comm is None:
raise RuntimeError('Control comm has not been properly opened')
data = msg['content']['data']
method = data['method']
if method == 'request_states':
# Send back the full widgets state
cls.get_manager_state()
widgets = _instances.values()
full_state = {}
drop_defaults = False
for widget in widgets:
full_state[widget.model_id] = {
'model_name': widget._model_name,
'model_module': widget._model_module,
'model_module_version': widget._model_module_version,
'state': widget.get_state(drop_defaults=drop_defaults),
}
full_state, buffer_paths, buffers = _remove_buffers(full_state)
cls._control_comm.send(dict(
method='update_states',
states=full_state,
buffer_paths=buffer_paths
), buffers=buffers)
else:
raise RuntimeError('Unknown front-end to back-end widget control msg with method "%s"' % method)
def handle_comm_opened(comm, msg):
"""Static method, called when a widget is constructed."""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget protocol versions: received version %r, expected version %r"%(version, __protocol_version__))
data = msg['content']['data']
state = data['state']
# Find the widget class to instantiate in the registered widgets
widget_class = _registry.get(state['_model_module'],
state['_model_module_version'],
state['_model_name'],
state['_view_module'],
state['_view_module_version'],
state['_view_name'])
widget = widget_class(comm=comm)
if 'buffer_paths' in data:
_put_buffers(state, data['buffer_paths'], msg['buffers'])
widget.set_state(state)
def get_manager_state(drop_defaults=False, widgets=None):
"""Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
"""
state = {}
if widgets is None:
widgets = _instances.values()
for widget in widgets:
state[widget.model_id] = widget._get_embed_state(drop_defaults=drop_defaults)
return {'version_major': 2, 'version_minor': 0, 'state': state}
def _get_embed_state(self, drop_defaults=False):
state = {
'model_name': self._model_name,
'model_module': self._model_module,
'model_module_version': self._model_module_version
}
model_state, buffer_paths, buffers = _remove_buffers(self.get_state(drop_defaults=drop_defaults))
state['state'] = model_state
if len(buffers) > 0:
state['buffers'] = [{'encoding': 'base64',
'path': p,
'data': standard_b64encode(d).decode('ascii')}
for p, d in zip(buffer_paths, buffers)]
return state
def get_view_spec(self):
return dict(version_major=2, version_minor=0, model_id=self._model_id)
#-------------------------------------------------------------------------
# Traits
#-------------------------------------------------------------------------
_model_name = Unicode('WidgetModel',
help="Name of the model.", read_only=True).tag(sync=True)
_model_module = Unicode('@jupyter-widgets/base',
help="The namespace for the model.", read_only=True).tag(sync=True)
_model_module_version = Unicode(__jupyter_widgets_base_version__,
help="A semver requirement for namespace version containing the model.", read_only=True).tag(sync=True)
_view_name = Unicode(None, allow_none=True,
help="Name of the view.").tag(sync=True)
_view_module = Unicode(None, allow_none=True,
help="The namespace for the view.").tag(sync=True)
_view_module_version = Unicode('',
help="A semver requirement for the namespace version containing the view.").tag(sync=True)
_view_count = Int(None, allow_none=True,
help="EXPERIMENTAL: The number of views of the model displayed in the frontend. This attribute is experimental and may change or be removed in the future. None signifies that views will not be tracked. Set this to 0 to start tracking view creation/deletion.").tag(sync=True)
comm = Any(allow_none=True)
keys = List(help="The traits which are synced.")
def _default_keys(self):
return [name for name in self.traits(sync=True)]
_property_lock = Dict()
_holding_sync = False
_states_to_send = Set()
_msg_callbacks = Instance(CallbackDispatcher, ())
#-------------------------------------------------------------------------
# (Con/de)structor
#-------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Public constructor"""
self._model_id = kwargs.pop('model_id', None)
super().__init__(**kwargs)
Widget._call_widget_constructed(self)
self.open()
def __del__(self):
"""Object disposal"""
self.close()
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
def open(self):
"""Open a comm to the frontend if one isn't already open."""
if self.comm is None:
state, buffer_paths, buffers = _remove_buffers(self.get_state())
args = dict(target_name='jupyter.widget',
data={'state': state, 'buffer_paths': buffer_paths},
buffers=buffers,
metadata={'version': __protocol_version__}
)
if self._model_id is not None:
args['comm_id'] = self._model_id
try:
from comm import create_comm
except ImportError:
def create_comm(**kwargs):
from ipykernel.comm import Comm
return Comm(**kwargs)
self.comm = create_comm(**args)
def _comm_changed(self, change):
"""Called when the comm is changed."""
if change['new'] is None:
return
self._model_id = self.model_id
self.comm.on_msg(self._handle_msg)
_instances[self.model_id] = self
def model_id(self):
"""Gets the model id of this widget.
If a Comm doesn't exist yet, a Comm will be created automagically."""
return self.comm.comm_id
#-------------------------------------------------------------------------
# Methods
#-------------------------------------------------------------------------
def close(self):
"""Close method.
Closes the underlying comm.
When the comm is closed, all of the widget views are automatically
removed from the front-end."""
if self.comm is not None:
_instances.pop(self.model_id, None)
self.comm.close()
self.comm = None
self._repr_mimebundle_ = None
def send_state(self, key=None):
"""Sends the widget state, or a piece of it, to the front-end, if it exists.
Parameters
----------
key : unicode, or iterable (optional)
A single property's name or iterable of property names to sync with the front-end.
"""
state = self.get_state(key=key)
if len(state) > 0:
if self._property_lock: # we need to keep this dict up to date with the front-end values
for name, value in state.items():
if name in self._property_lock:
self._property_lock[name] = value
state, buffer_paths, buffers = _remove_buffers(state)
msg = {'method': 'update', 'state': state, 'buffer_paths': buffer_paths}
self._send(msg, buffers=buffers)
def get_state(self, key=None, drop_defaults=False):
"""Gets the widget state, or a piece of it.
Parameters
----------
key : unicode or iterable (optional)
A single property's name or iterable of property names to get.
Returns
-------
state : dict of states
metadata : dict
metadata for each field: {key: metadata}
"""
if key is None:
keys = self.keys
elif isinstance(key, str):
keys = [key]
elif isinstance(key, Iterable):
keys = key
else:
raise ValueError("key must be a string, an iterable of keys, or None")
state = {}
traits = self.traits()
for k in keys:
to_json = self.trait_metadata(k, 'to_json', self._trait_to_json)
value = to_json(getattr(self, k), self)
if not drop_defaults or not self._compare(value, traits[k].default_value):
state[k] = value
return state
def _is_numpy(self, x):
return x.__class__.__name__ == 'ndarray' and x.__class__.__module__ == 'numpy'
def _compare(self, a, b):
if self._is_numpy(a) or self._is_numpy(b):
import numpy as np
return np.array_equal(a, b)
else:
return a == b
def set_state(self, sync_data):
"""Called when a state is received from the front-end."""
# Send an echo update message immediately
if JUPYTER_WIDGETS_ECHO:
echo_state = {}
for attr, value in sync_data.items():
if attr in self.keys and self.trait_metadata(attr, 'echo_update', default=True):
echo_state[attr] = value
if echo_state:
echo_state, echo_buffer_paths, echo_buffers = _remove_buffers(echo_state)
msg = {
'method': 'echo_update',
'state': echo_state,
'buffer_paths': echo_buffer_paths,
}
self._send(msg, buffers=echo_buffers)
# The order of these context managers is important. Properties must
# be locked when the hold_trait_notification context manager is
# released and notifications are fired.
with self._lock_property(**sync_data), self.hold_trait_notifications():
for name in sync_data:
if name in self.keys:
from_json = self.trait_metadata(name, 'from_json',
self._trait_from_json)
self.set_trait(name, from_json(sync_data[name], self))
def send(self, content, buffers=None):
"""Sends a custom msg to the widget model in the front-end.
Parameters
----------
content : dict
Content of the message to send.
buffers : list of binary buffers
Binary buffers to send with message
"""
self._send({"method": "custom", "content": content}, buffers=buffers)
def on_msg(self, callback, remove=False):
"""(Un)Register a custom msg receive callback.
Parameters
----------
callback: callable
callback will be passed three arguments when a message arrives::
callback(widget, content, buffers)
remove: bool
True if the callback should be unregistered."""
self._msg_callbacks.register_callback(callback, remove=remove)
def add_traits(self, **traits):
"""Dynamically add trait attributes to the Widget."""
super().add_traits(**traits)
for name, trait in traits.items():
if trait.get_metadata('sync'):
self.keys.append(name)
self.send_state(name)
def notify_change(self, change):
"""Called when a property has changed."""
# Send the state to the frontend before the user-registered callbacks
# are called.
name = change['name']
if self.comm is not None and getattr(self.comm, 'kernel', True) is not None:
# Make sure this isn't information that the front-end just sent us.
if name in self.keys and self._should_send_property(name, getattr(self, name)):
# Send new state to front-end
self.send_state(key=name)
super().notify_change(change)
def __repr__(self):
return self._gen_repr_from_keys(self._repr_keys())
#-------------------------------------------------------------------------
# Support methods
#-------------------------------------------------------------------------
def _lock_property(self, **properties):
"""Lock a property-value pair.
The value should be the JSON state of the property.
NOTE: This, in addition to the single lock for all state changes, is
flawed. In the future we may want to look into buffering state changes
back to the front-end."""
self._property_lock = properties
try:
yield
finally:
self._property_lock = {}
def hold_sync(self):
"""Hold syncing any state until the outermost context manager exits"""
if self._holding_sync is True:
yield
else:
try:
self._holding_sync = True
yield
finally:
self._holding_sync = False
self.send_state(self._states_to_send)
self._states_to_send.clear()
def _should_send_property(self, key, value):
"""Check the property lock (property_lock)"""
to_json = self.trait_metadata(key, 'to_json', self._trait_to_json)
if key in self._property_lock:
# model_state, buffer_paths, buffers
split_value = _remove_buffers({ key: to_json(value, self)})
split_lock = _remove_buffers({ key: self._property_lock[key]})
# A roundtrip conversion through json in the comparison takes care of
# idiosyncracies of how python data structures map to json, for example
# tuples get converted to lists.
if (jsonloads(jsondumps(split_value[0])) == split_lock[0]
and split_value[1] == split_lock[1]
and _buffer_list_equal(split_value[2], split_lock[2])):
if self._holding_sync:
self._states_to_send.discard(key)
return False
if self._holding_sync:
self._states_to_send.add(key)
return False
else:
return True
# Event handlers
def _handle_msg(self, msg):
"""Called when a msg is received from the front-end"""
data = msg['content']['data']
method = data['method']
if method == 'update':
if 'state' in data:
state = data['state']
if 'buffer_paths' in data:
_put_buffers(state, data['buffer_paths'], msg['buffers'])
self.set_state(state)
# Handle a state request.
elif method == 'request_state':
self.send_state()
# Handle a custom msg from the front-end.
elif method == 'custom':
if 'content' in data:
self._handle_custom_msg(data['content'], msg['buffers'])
# Catch remainder.
else:
self.log.error('Unknown front-end to back-end widget msg with method "%s"' % method)
def _handle_custom_msg(self, content, buffers):
"""Called when a custom msg is received."""
self._msg_callbacks(self, content, buffers)
def _trait_to_json(x, self):
"""Convert a trait value to json."""
return x
def _trait_from_json(x, self):
"""Convert json values to objects."""
return x
def _repr_mimebundle_(self, **kwargs):
plaintext = repr(self)
if len(plaintext) > 110:
plaintext = plaintext[:110] + '…'
data = {
'text/plain': plaintext,
}
if self._view_name is not None:
# The 'application/vnd.jupyter.widget-view+json' mimetype has not been registered yet.
# See the registration process and naming convention at
# http://tools.ietf.org/html/rfc6838
# and the currently registered mimetypes at
# http://www.iana.org/assignments/media-types/media-types.xhtml.
data['application/vnd.jupyter.widget-view+json'] = {
'version_major': 2,
'version_minor': 0,
'model_id': self._model_id
}
return data
def _send(self, msg, buffers=None):
"""Sends a message to the model in the front-end."""
if self.comm is not None and (self.comm.kernel is not None if hasattr(self.comm, "kernel") else True):
self.comm.send(data=msg, buffers=buffers)
def _repr_keys(self):
traits = self.traits()
for key in sorted(self.keys):
# Exclude traits that start with an underscore
if key[0] == '_':
continue
# Exclude traits who are equal to their default value
value = getattr(self, key)
trait = traits[key]
if self._compare(value, trait.default_value):
continue
elif (isinstance(trait, (Container, Dict)) and
trait.default_value == Undefined and
(value is None or len(value) == 0)):
# Empty container, and dynamic default will be empty
continue
yield key
def _gen_repr_from_keys(self, keys):
class_name = self.__class__.__name__
signature = ', '.join(
'{}={!r}'.format(key, getattr(self, key))
for key in keys
)
return '{}({})'.format(class_name, signature)
def _widget_to_json(x, obj):
if isinstance(x, dict):
return {k: _widget_to_json(v, obj) for k, v in x.items()}
elif isinstance(x, (list, tuple)):
return [_widget_to_json(v, obj) for v in x]
elif isinstance(x, Widget):
return "IPY_MODEL_" + x.model_id
else:
return x | null |
170,392 | import os
import typing
from contextlib import contextmanager
from collections.abc import Iterable
from IPython import get_ipython
from traitlets import (
Any, HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
from json import loads as jsonloads, dumps as jsondumps
from base64 import standard_b64encode
from .utils import deprecation, _get_frame
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
import inspect
_instances : typing.MutableMapping[str, "Widget"] = {}
def _json_to_widget(x, obj):
if isinstance(x, dict):
return {k: _json_to_widget(v, obj) for k, v in x.items()}
elif isinstance(x, (list, tuple)):
return [_json_to_widget(v, obj) for v in x]
elif isinstance(x, str) and x.startswith('IPY_MODEL_') and x[10:] in _instances:
return _instances[x[10:]]
else:
return x | null |
170,393 | import os
import typing
from contextlib import contextmanager
from collections.abc import Iterable
from IPython import get_ipython
from traitlets import (
Any, HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
from json import loads as jsonloads, dumps as jsondumps
from base64 import standard_b64encode
from .utils import deprecation, _get_frame
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
import inspect
The provided code snippet includes necessary dependencies for implementing the `_put_buffers` function. Write a Python function `def _put_buffers(state, buffer_paths, buffers)` to solve the following problem:
The inverse of _remove_buffers, except here we modify the existing dict/lists. Modifying should be fine, since this is used when state comes from the wire.
Here is the function:
def _put_buffers(state, buffer_paths, buffers):
"""The inverse of _remove_buffers, except here we modify the existing dict/lists.
Modifying should be fine, since this is used when state comes from the wire.
"""
for buffer_path, buffer in zip(buffer_paths, buffers):
# we'd like to set say sync_data['x'][0]['y'] = buffer
# where buffer_path in this example would be ['x', 0, 'y']
obj = state
for key in buffer_path[:-1]:
obj = obj[key]
obj[buffer_path[-1]] = buffer | The inverse of _remove_buffers, except here we modify the existing dict/lists. Modifying should be fine, since this is used when state comes from the wire. |
170,394 | import os
import typing
from contextlib import contextmanager
from collections.abc import Iterable
from IPython import get_ipython
from traitlets import (
Any, HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
from json import loads as jsonloads, dumps as jsondumps
from base64 import standard_b64encode
from .utils import deprecation, _get_frame
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
import inspect
def _separate_buffers(substate, path, buffer_paths, buffers):
"""For internal, see _remove_buffers"""
# remove binary types from dicts and lists, but keep track of their paths
# any part of the dict/list that needs modification will be cloned, so the original stays untouched
# e.g. {'x': {'ar': ar}, 'y': [ar2, ar3]}, where ar/ar2/ar3 are binary types
# will result in {'x': {}, 'y': [None, None]}, [ar, ar2, ar3], [['x', 'ar'], ['y', 0], ['y', 1]]
# instead of removing elements from the list, this will make replacing the buffers on the js side much easier
if isinstance(substate, (list, tuple)):
is_cloned = False
for i, v in enumerate(substate):
if isinstance(v, _binary_types):
if not is_cloned:
substate = list(substate) # shallow clone list/tuple
is_cloned = True
substate[i] = None
buffers.append(v)
buffer_paths.append(path + [i])
elif isinstance(v, (dict, list, tuple)):
vnew = _separate_buffers(v, path + [i], buffer_paths, buffers)
if v is not vnew: # only assign when value changed
if not is_cloned:
substate = list(substate) # clone list/tuple
is_cloned = True
substate[i] = vnew
elif isinstance(substate, dict):
is_cloned = False
for k, v in substate.items():
if isinstance(v, _binary_types):
if not is_cloned:
substate = dict(substate) # shallow clone dict
is_cloned = True
del substate[k]
buffers.append(v)
buffer_paths.append(path + [k])
elif isinstance(v, (dict, list, tuple)):
vnew = _separate_buffers(v, path + [k], buffer_paths, buffers)
if v is not vnew: # only assign when value changed
if not is_cloned:
substate = dict(substate) # clone list/tuple
is_cloned = True
substate[k] = vnew
else:
raise ValueError("expected state to be a list or dict, not %r" % substate)
return substate
The provided code snippet includes necessary dependencies for implementing the `_remove_buffers` function. Write a Python function `def _remove_buffers(state)` to solve the following problem:
Return (state_without_buffers, buffer_paths, buffers) for binary message parts A binary message part is a memoryview, bytearray, or python 3 bytes object. As an example: >>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memoryview(ar2)}} >>> _remove_buffers(state) ({'plain': [0, 'text']}, {'x': {}, 'y': {'shape': (10, 10)}}, [['x', 'ar'], ['y', 'data']], [<memory at 0x107ffec48>, <memory at 0x107ffed08>])
Here is the function:
def _remove_buffers(state):
"""Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memoryview(ar2)}}
>>> _remove_buffers(state)
({'plain': [0, 'text']}, {'x': {}, 'y': {'shape': (10, 10)}}, [['x', 'ar'], ['y', 'data']],
[<memory at 0x107ffec48>, <memory at 0x107ffed08>])
"""
buffer_paths, buffers = [], []
state = _separate_buffers(state, [], buffer_paths, buffers)
return state, buffer_paths, buffers | Return (state_without_buffers, buffer_paths, buffers) for binary message parts A binary message part is a memoryview, bytearray, or python 3 bytes object. As an example: >>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memoryview(ar2)}} >>> _remove_buffers(state) ({'plain': [0, 'text']}, {'x': {}, 'y': {'shape': (10, 10)}}, [['x', 'ar'], ['y', 'data']], [<memory at 0x107ffec48>, <memory at 0x107ffed08>]) |
170,395 | import os
import typing
from contextlib import contextmanager
from collections.abc import Iterable
from IPython import get_ipython
from traitlets import (
Any, HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
from json import loads as jsonloads, dumps as jsondumps
from base64 import standard_b64encode
from .utils import deprecation, _get_frame
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
import inspect
The provided code snippet includes necessary dependencies for implementing the `_buffer_list_equal` function. Write a Python function `def _buffer_list_equal(a, b)` to solve the following problem:
Compare two lists of buffers for equality. Used to decide whether two sequences of buffers (memoryviews, bytearrays, or python 3 bytes) differ, such that a sync is needed. Returns True if equal, False if unequal
Here is the function:
def _buffer_list_equal(a, b):
"""Compare two lists of buffers for equality.
Used to decide whether two sequences of buffers (memoryviews,
bytearrays, or python 3 bytes) differ, such that a sync is needed.
Returns True if equal, False if unequal
"""
if len(a) != len(b):
return False
if a == b:
return True
for ia, ib in zip(a, b):
# Check byte equality, since bytes are what is actually synced
# NOTE: Simple ia != ib does not always work as intended, as
# e.g. memoryview(np.frombuffer(ia, dtype='float32')) !=
# memoryview(np.frombuffer(b)), since the format info differs.
# Compare without copying.
if memoryview(ia).cast('B') != memoryview(ib).cast('B'):
return False
return True | Compare two lists of buffers for equality. Used to decide whether two sequences of buffers (memoryviews, bytearrays, or python 3 bytes) differ, such that a sync is needed. Returns True if equal, False if unequal |
170,396 | import os
import typing
from contextlib import contextmanager
from collections.abc import Iterable
from IPython import get_ipython
from traitlets import (
Any, HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
from json import loads as jsonloads, dumps as jsondumps
from base64 import standard_b64encode
from .utils import deprecation, _get_frame
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
import inspect
The provided code snippet includes necessary dependencies for implementing the `_show_traceback` function. Write a Python function `def _show_traceback(method)` to solve the following problem:
decorator for showing tracebacks
Here is the function:
def _show_traceback(method):
"""decorator for showing tracebacks"""
def m(self, *args, **kwargs):
try:
return(method(self, *args, **kwargs))
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warning("Exception in widget method %s: %s", method, e, exc_info=True)
else:
ip.showtraceback()
return m | decorator for showing tracebacks |
170,397 | import os
import typing
from contextlib import contextmanager
from collections.abc import Iterable
from IPython import get_ipython
from traitlets import (
Any, HasTraits, Unicode, Dict, Instance, List, Int, Set, Bytes, observe, default, Container,
Undefined)
from json import loads as jsonloads, dumps as jsondumps
from base64 import standard_b64encode
from .utils import deprecation, _get_frame
from .._version import __protocol_version__, __control_protocol_version__, __jupyter_widgets_base_version__
import inspect
_registry = WidgetRegistry()
The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(widget)` to solve the following problem:
A decorator registering a widget class in the widget registry.
Here is the function:
def register(widget):
"""A decorator registering a widget class in the widget registry."""
w = widget.class_traits()
_registry.register(w['_model_module'].default_value,
w['_model_module_version'].default_value,
w['_model_name'].default_value,
w['_view_module'].default_value,
w['_view_module_version'].default_value,
w['_view_name'].default_value,
widget)
return widget | A decorator registering a widget class in the widget registry. |
170,398 | from .widget_box import Box
from .widget import register
from .widget_core import CoreWidget
from traitlets import Unicode, Dict, CInt, TraitError, validate, observe
from .trait_types import TypedTuple
from itertools import chain, repeat, islice
def repeat(object: _T) -> Iterator[_T]: ...
def repeat(object: _T, times: int) -> Iterator[_T]: ...
class chain(Iterator[_T], Generic[_T]):
def __init__(self, *iterables: Iterable[_T]) -> None: ...
def __next__(self) -> _T: ...
def __iter__(self) -> Iterator[_T]: ...
def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ...
def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ...
def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], step: Optional[int] = ...) -> Iterator[_T]: ...
The provided code snippet includes necessary dependencies for implementing the `pad` function. Write a Python function `def pad(iterable, padding=None, length=None)` to solve the following problem:
Returns the sequence elements and then returns None up to the given size (or indefinitely if size is None).
Here is the function:
def pad(iterable, padding=None, length=None):
"""Returns the sequence elements and then returns None up to the given size (or indefinitely if size is None)."""
return islice(chain(iterable, repeat(padding)), length) | Returns the sequence elements and then returns None up to the given size (or indefinitely if size is None). |
170,399 | import datetime as dt
from traitlets import (
observe, default, Unicode, Dict, Int, Bool, Bytes, CaselessStrEnum
)
from .widget_description import DescriptionWidget
from .valuewidget import ValueWidget
from .widget_core import CoreWidget
from .widget_button import ButtonStyle
from .widget import register, widget_serialization
from .trait_types import InstanceDict, TypedTuple
from traitlets import Bunch
def _deserialize_single_file(js):
uploaded_file = Bunch()
for attribute in ['name', 'type', 'size', 'content']:
uploaded_file[attribute] = js[attribute]
uploaded_file['last_modified'] = dt.datetime.fromtimestamp(
js['last_modified'] / 1000,
tz=dt.timezone.utc
)
return uploaded_file
def _deserialize_value(js, _):
return [_deserialize_single_file(entry) for entry in js] | null |
170,400 | import datetime as dt
from traitlets import (
observe, default, Unicode, Dict, Int, Bool, Bytes, CaselessStrEnum
)
from .widget_description import DescriptionWidget
from .valuewidget import ValueWidget
from .widget_core import CoreWidget
from .widget_button import ButtonStyle
from .widget import register, widget_serialization
from .trait_types import InstanceDict, TypedTuple
from traitlets import Bunch
def _serialize_single_file(uploaded_file):
js = {}
for attribute in ['name', 'type', 'size', 'content']:
js[attribute] = uploaded_file[attribute]
js['last_modified'] = int(uploaded_file['last_modified'].timestamp() * 1000)
return js
def _serialize_value(value, _):
return [_serialize_single_file(entry) for entry in value] | null |
170,401 | import json
import re
from .widgets import Widget, DOMWidget, widget as widget_module
from .widgets.widget_link import Link
from .widgets.docutils import doc_subst
from ._version import __html_manager_version__
def _get_recursive_state(widget, store=None, drop_defaults=False):
"""Gets the embed state of a widget, and all other widgets it refers to as well"""
if store is None:
store = dict()
state = widget._get_embed_state(drop_defaults=drop_defaults)
store[widget.model_id] = state
# Loop over all values included in state (i.e. don't consider excluded values):
for ref in _find_widget_refs_by_state(widget, state['state']):
if ref.model_id not in store:
_get_recursive_state(ref, store, drop_defaults=drop_defaults)
return store
def add_resolved_links(store, drop_defaults):
"""Adds the state of any link models between two models in store"""
for widget_id, widget in widget_module._instances.items(): # go over all widgets
if isinstance(widget, Link) and widget_id not in store:
if widget.source[0].model_id in store and widget.target[0].model_id in store:
store[widget.model_id] = widget._get_embed_state(drop_defaults=drop_defaults)
The provided code snippet includes necessary dependencies for implementing the `dependency_state` function. Write a Python function `def dependency_state(widgets, drop_defaults=True)` to solve the following problem:
Get the state of all widgets specified, and their dependencies. This uses a simple dependency finder, including: - any widget directly referenced in the state of an included widget - any widget in a list/tuple attribute in the state of an included widget - any widget in a dict attribute in the state of an included widget - any jslink/jsdlink between two included widgets What this alogorithm does not do: - Find widget references in nested list/dict structures - Find widget references in other types of attributes Note that this searches the state of the widgets for references, so if a widget reference is not included in the serialized state, it won't be considered as a dependency. Parameters ---------- widgets: single widget or list of widgets. This function will return the state of every widget mentioned and of all their dependencies. drop_defaults: boolean Whether to drop default values from the widget states. Returns ------- A dictionary with the state of the widgets and any widget they depend on.
Here is the function:
def dependency_state(widgets, drop_defaults=True):
"""Get the state of all widgets specified, and their dependencies.
This uses a simple dependency finder, including:
- any widget directly referenced in the state of an included widget
- any widget in a list/tuple attribute in the state of an included widget
- any widget in a dict attribute in the state of an included widget
- any jslink/jsdlink between two included widgets
What this alogorithm does not do:
- Find widget references in nested list/dict structures
- Find widget references in other types of attributes
Note that this searches the state of the widgets for references, so if
a widget reference is not included in the serialized state, it won't
be considered as a dependency.
Parameters
----------
widgets: single widget or list of widgets.
This function will return the state of every widget mentioned
and of all their dependencies.
drop_defaults: boolean
Whether to drop default values from the widget states.
Returns
-------
A dictionary with the state of the widgets and any widget they
depend on.
"""
# collect the state of all relevant widgets
if widgets is None:
# Get state of all widgets, no smart resolution needed.
state = Widget.get_manager_state(drop_defaults=drop_defaults, widgets=None)['state']
else:
try:
widgets[0]
except (IndexError, TypeError):
widgets = [widgets]
state = {}
for widget in widgets:
_get_recursive_state(widget, state, drop_defaults)
# Add any links between included widgets:
add_resolved_links(state, drop_defaults)
return state | Get the state of all widgets specified, and their dependencies. This uses a simple dependency finder, including: - any widget directly referenced in the state of an included widget - any widget in a list/tuple attribute in the state of an included widget - any widget in a dict attribute in the state of an included widget - any jslink/jsdlink between two included widgets What this alogorithm does not do: - Find widget references in nested list/dict structures - Find widget references in other types of attributes Note that this searches the state of the widgets for references, so if a widget reference is not included in the serialized state, it won't be considered as a dependency. Parameters ---------- widgets: single widget or list of widgets. This function will return the state of every widget mentioned and of all their dependencies. drop_defaults: boolean Whether to drop default values from the widget states. Returns ------- A dictionary with the state of the widgets and any widget they depend on. |
170,402 | import json
import re
from .widgets import Widget, DOMWidget, widget as widget_module
from .widgets.widget_link import Link
from .widgets.docutils import doc_subst
from ._version import __html_manager_version__
html_template = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{title}</title>
</head>
<body>
{snippet}
</body>
</html>
"""
def embed_snippet(views,
drop_defaults=True,
state=None,
indent=2,
embed_url=None,
requirejs=True,
cors=True
):
"""Return a snippet that can be embedded in an HTML file.
Parameters
----------
{views_attribute}
{embed_kwargs}
Returns
-------
A unicode string with an HTML snippet containing several `<script>` tags.
"""
data = embed_data(views, drop_defaults=drop_defaults, state=state)
widget_views = '\n'.join(
widget_view_template.format(view_spec=escape_script(json.dumps(view_spec)))
for view_spec in data['view_specs']
)
if embed_url is None:
embed_url = DEFAULT_EMBED_REQUIREJS_URL if requirejs else DEFAULT_EMBED_SCRIPT_URL
load = load_requirejs_template if requirejs else load_template
use_cors = ' crossorigin="anonymous"' if cors else ''
values = {
'load': load.format(embed_url=embed_url, use_cors=use_cors),
'json_data': escape_script(json.dumps(data['manager_state'], indent=indent)),
'widget_views': widget_views,
}
return snippet_template.format(**values)
The provided code snippet includes necessary dependencies for implementing the `embed_minimal_html` function. Write a Python function `def embed_minimal_html(fp, views, title='IPyWidget export', template=None, **kwargs)` to solve the following problem:
Write a minimal HTML file with widget views embedded. Parameters ---------- fp: filename or file-like object The file to write the HTML output to. {views_attribute} title: title of the html page. template: Template in which to embed the widget state. This should be a Python string with placeholders `{{title}}` and `{{snippet}}`. The `{{snippet}}` placeholder will be replaced by all the widgets. {embed_kwargs}
Here is the function:
def embed_minimal_html(fp, views, title='IPyWidget export', template=None, **kwargs):
"""Write a minimal HTML file with widget views embedded.
Parameters
----------
fp: filename or file-like object
The file to write the HTML output to.
{views_attribute}
title: title of the html page.
template: Template in which to embed the widget state.
This should be a Python string with placeholders
`{{title}}` and `{{snippet}}`. The `{{snippet}}` placeholder
will be replaced by all the widgets.
{embed_kwargs}
"""
snippet = embed_snippet(views, **kwargs)
values = {
'title': title,
'snippet': snippet,
}
if template is None:
template = html_template
html_code = template.format(**values)
# Check if fp is writable:
if hasattr(fp, 'write'):
fp.write(html_code)
else:
# Assume fp is a filename:
with open(fp, "w") as f:
f.write(html_code) | Write a minimal HTML file with widget views embedded. Parameters ---------- fp: filename or file-like object The file to write the HTML output to. {views_attribute} title: title of the html page. template: Template in which to embed the widget state. This should be a Python string with placeholders `{{title}}` and `{{snippet}}`. The `{{snippet}}` placeholder will be replaced by all the widgets. {embed_kwargs} |
170,403 | from colorsys import rgb_to_hls
from pygments.styles import get_style_by_name
from pygments.token import Token
def dark_color(color):
"""Check whether a color is 'dark'.
Currently, this is simply whether the luminance is <50%"""
rgb = hex_to_rgb(color)
if rgb:
return rgb_to_hls(*rgb)[1] < 128
else: # default to False
return False
def get_style_by_name(name):
if name in STYLE_MAP:
mod, cls = STYLE_MAP[name].split('::')
builtin = "yes"
else:
for found_name, style in find_plugin_styles():
if name == found_name:
return style
# perhaps it got dropped into our styles package
builtin = ""
mod = name
cls = name.title() + "Style"
try:
mod = __import__('pygments.styles.' + mod, None, None, [cls])
except ImportError:
raise ClassNotFound("Could not find style module %r" % mod +
(builtin and ", though it should be builtin") + ".")
try:
return getattr(mod, cls)
except AttributeError:
raise ClassNotFound("Could not find style class %r in style module." % cls)
The provided code snippet includes necessary dependencies for implementing the `dark_style` function. Write a Python function `def dark_style(stylename)` to solve the following problem:
Guess whether the background of the style with name 'stylename' counts as 'dark'.
Here is the function:
def dark_style(stylename):
"""Guess whether the background of the style with name 'stylename'
counts as 'dark'."""
return dark_color(get_style_by_name(stylename).background_color) | Guess whether the background of the style with name 'stylename' counts as 'dark'. |
170,404 | from colorsys import rgb_to_hls
from pygments.styles import get_style_by_name
from pygments.token import Token
default_light_style_template = default_template + '''\
.in-prompt { color: navy; }
.out-prompt { color: darkred; }
'''
default_dark_style_template = default_template + '''\
.in-prompt,
.in-prompt-number { color: lime; }
.out-prompt,
.out-prompt-number { color: red; }
'''
default_bw_style_sheet = default_template%dict(
bgcolor='white', fgcolor='black', select="#ccc")
def get_colors(stylename):
"""Construct the keys to be used building the base stylesheet
from a templatee."""
style = get_style_by_name(stylename)
fgcolor = style.style_for_token(Token.Text)['color'] or ''
if len(fgcolor) in (3,6):
# could be 'abcdef' or 'ace' hex, which needs '#' prefix
try:
int(fgcolor, 16)
except TypeError:
pass
else:
fgcolor = "#"+fgcolor
return dict(
bgcolor = style.background_color,
select = style.highlight_color,
fgcolor = fgcolor
)
The provided code snippet includes necessary dependencies for implementing the `sheet_from_template` function. Write a Python function `def sheet_from_template(name, colors='lightbg')` to solve the following problem:
Use one of the base templates, and set bg/fg/select colors.
Here is the function:
def sheet_from_template(name, colors='lightbg'):
"""Use one of the base templates, and set bg/fg/select colors."""
colors = colors.lower()
if colors=='lightbg':
return default_light_style_template%get_colors(name)
elif colors=='linux':
return default_dark_style_template%get_colors(name)
elif colors=='nocolor':
return default_bw_style_sheet
else:
raise KeyError("No such color scheme: %s"%colors) | Use one of the base templates, and set bg/fg/select colors. |
170,405 | from functools import partial
import os
import os.path
import re
import sys
from textwrap import dedent
import time
from unicodedata import category
import webbrowser
from qtpy import QT6
from qtpy import QtCore, QtGui, QtPrintSupport, QtWidgets
from qtconsole.rich_text import HtmlExporter
from qtconsole.util import MetaQObjectHasTraits, get_font, superQ
from ipython_genutils.text import columnize
from traitlets.config.configurable import LoggingConfigurable
from traitlets import Bool, Enum, Integer, Unicode
from .ansi_code_processor import QtAnsiCodeProcessor
from .completion_widget import CompletionWidget
from .completion_html import CompletionHtml
from .completion_plain import CompletionPlain
from .kill_ring import QtKillRing
def category(__chr: Text) -> Text: ...
The provided code snippet includes necessary dependencies for implementing the `is_letter_or_number` function. Write a Python function `def is_letter_or_number(char)` to solve the following problem:
Returns whether the specified unicode character is a letter or a number.
Here is the function:
def is_letter_or_number(char):
""" Returns whether the specified unicode character is a letter or a number.
"""
cat = category(char)
return cat.startswith('L') or cat.startswith('N') | Returns whether the specified unicode character is a letter or a number. |
170,406 | from functools import partial
import os
import os.path
import re
import sys
from textwrap import dedent
import time
from unicodedata import category
import webbrowser
from qtpy import QT6
from qtpy import QtCore, QtGui, QtPrintSupport, QtWidgets
from qtconsole.rich_text import HtmlExporter
from qtconsole.util import MetaQObjectHasTraits, get_font, superQ
from ipython_genutils.text import columnize
from traitlets.config.configurable import LoggingConfigurable
from traitlets import Bool, Enum, Integer, Unicode
from .ansi_code_processor import QtAnsiCodeProcessor
from .completion_widget import CompletionWidget
from .completion_html import CompletionHtml
from .completion_plain import CompletionPlain
from .kill_ring import QtKillRing
def category(__chr: Text) -> Text: ...
The provided code snippet includes necessary dependencies for implementing the `is_whitespace` function. Write a Python function `def is_whitespace(char)` to solve the following problem:
Check whether a given char counts as white space.
Here is the function:
def is_whitespace(char):
"""Check whether a given char counts as white space."""
return category(char).startswith('Z') | Check whether a given char counts as white space. |
170,407 |
The provided code snippet includes necessary dependencies for implementing the `qstring_length` function. Write a Python function `def qstring_length(text)` to solve the following problem:
Tries to compute what the length of an utf16-encoded QString would be.
Here is the function:
def qstring_length(text):
"""
Tries to compute what the length of an utf16-encoded QString would be.
"""
utf16_text = text.encode('utf16')
length = len(utf16_text) // 2
# Remove Byte order mark.
# TODO: All unicode Non-characters should be removed
if utf16_text[:2] in [b'\xff\xfe', b'\xff\xff', b'\xfe\xff']:
length -= 1
return length | Tries to compute what the length of an utf16-encoded QString would be. |
170,408 | import inspect
from qtpy import QtCore, QtGui
from traitlets import HasTraits, TraitType
The provided code snippet includes necessary dependencies for implementing the `superQ` function. Write a Python function `def superQ(QClass)` to solve the following problem:
Permits the use of super() in class hierarchies that contain Qt classes. Unlike QObject, SuperQObject does not accept a QObject parent. If it did, super could not be emulated properly (all other classes in the heierarchy would have to accept the parent argument--they don't, of course, because they don't inherit QObject.) This class is primarily useful for attaching signals to existing non-Qt classes. See QtKernelManagerMixin for an example.
Here is the function:
def superQ(QClass):
""" Permits the use of super() in class hierarchies that contain Qt classes.
Unlike QObject, SuperQObject does not accept a QObject parent. If it did,
super could not be emulated properly (all other classes in the heierarchy
would have to accept the parent argument--they don't, of course, because
they don't inherit QObject.)
This class is primarily useful for attaching signals to existing non-Qt
classes. See QtKernelManagerMixin for an example.
"""
class SuperQClass(QClass):
def __new__(cls, *args, **kw):
# We initialize QClass as early as possible. Without this, Qt complains
# if SuperQClass is not the first class in the super class list.
inst = QClass.__new__(cls)
QClass.__init__(inst)
return inst
def __init__(self, *args, **kw):
# Emulate super by calling the next method in the MRO, if there is one.
mro = self.__class__.mro()
for qt_class in QClass.mro():
mro.remove(qt_class)
next_index = mro.index(SuperQClass) + 1
if next_index < len(mro):
mro[next_index].__init__(self, *args, **kw)
return SuperQClass | Permits the use of super() in class hierarchies that contain Qt classes. Unlike QObject, SuperQObject does not accept a QObject parent. If it did, super could not be emulated properly (all other classes in the heierarchy would have to accept the parent argument--they don't, of course, because they don't inherit QObject.) This class is primarily useful for attaching signals to existing non-Qt classes. See QtKernelManagerMixin for an example. |
170,409 | import inspect
from qtpy import QtCore, QtGui
from traitlets import HasTraits, TraitType
The provided code snippet includes necessary dependencies for implementing the `get_font` function. Write a Python function `def get_font(family, fallback=None)` to solve the following problem:
Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object
Here is the function:
def get_font(family, fallback=None):
"""Return a font of the requested family, using fallback as alternative.
If a fallback is provided, it is used in case the requested family isn't
found. If no fallback is given, no alternative is chosen and Qt's internal
algorithms may automatically choose a fallback font.
Parameters
----------
family : str
A font name.
fallback : str
A font name.
Returns
-------
font : QFont object
"""
font = QtGui.QFont(family)
# Check whether we got what we wanted using QFontInfo, since exactMatch()
# is overly strict and returns false in too many cases.
font_info = QtGui.QFontInfo(font)
if fallback is not None and font_info.family() != family:
font = QtGui.QFont(fallback)
return font | Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.