We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`numba -s` should show total cores and available cores
As title.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `numba/numba_entry.py`
Content:
```
1 from __future__ import print_function, division, absolute_import
2 
3 import sys
4 import argparse
5 import os
6 import subprocess
7 
8 
9 def get_sys_info():
10     # delay these imports until now as they are only needed in this
11     # function which then exits.
12     import platform
13     import json
14     from numba import config
15     from numba import cuda as cu
16     from numba.cuda import cudadrv
17     from numba.cuda.cudadrv.driver import driver as cudriver
18     from numba import roc
19     from numba.roc.hlc import hlc, libhlc
20     import textwrap as tw
21     import ctypes as ct
22     import llvmlite.binding as llvmbind
23     import locale
24     from datetime import datetime
25     from itertools import chain
26     from subprocess import check_output, CalledProcessError
27 
28     try:
29         fmt = "%-35s : %-s"
30         print("-" * 80)
31         print("__Time Stamp__")
32         print(datetime.utcnow())
33         print("")
34 
35         print("__Hardware Information__")
36         print(fmt % ("Machine", platform.machine()))
37         print(fmt % ("CPU Name", llvmbind.get_host_cpu_name()))
38         try:
39             featuremap = llvmbind.get_host_cpu_features()
40         except RuntimeError:
41             print(fmt % ("CPU Features", "NA"))
42         else:
43             features = sorted([key for key, value in featuremap.items()
44                                if value])
45             cpu_feat = tw.fill(' '.join(features), 80)
46             print(fmt % ("CPU Features", ""))
47             print(cpu_feat)
48         print("")
49 
50         print("__OS Information__")
51         print(fmt % ("Platform", platform.platform(aliased=True)))
52         print(fmt % ("Release", platform.release()))
53         system_name = platform.system()
54         print(fmt % ("System Name", system_name))
55         print(fmt % ("Version", platform.version()))
56         try:
57             if system_name == 'Linux':
58                 info = platform.linux_distribution()
59             elif system_name == 'Windows':
60                 info = platform.win32_ver()
61             elif system_name == 'Darwin':
62                 info = platform.mac_ver()
63             else:
64                 raise RuntimeError("Unknown system.")
65             buf = ''.join([x
66                            if x != '' else ' '
67                            for x in list(chain.from_iterable(info))])
68             print(fmt % ("OS specific info", buf))
69 
70             if system_name == 'Linux':
71                 print(fmt % ("glibc info", ' '.join(platform.libc_ver())))
72         except:
73             print("Error: System name incorrectly identified or unknown.")
74         print("")
75 
76         print("__Python Information__")
77         print(fmt % ("Python Compiler", platform.python_compiler()))
78         print(
79             fmt %
80             ("Python Implementation",
81              platform.python_implementation()))
82         print(fmt % ("Python Version", platform.python_version()))
83         print(
84             fmt %
85             ("Python Locale ", ' '.join(
86                 [x for x in locale.getdefaultlocale() if x is not None])))
87 
88         print("")
89         print("__LLVM information__")
90         print(
91             fmt %
92             ("LLVM version", '.'.join(
93                 [str(k) for k in llvmbind.llvm_version_info])))
94 
95         print("")
96         print("__CUDA Information__")
97         # Look for GPUs
98         try:
99             cu.list_devices()[0]  # will a device initialise?
100         except BaseException as e:
101             msg_not_found = "CUDA driver library cannot be found"
102             msg_disabled_by_user = "CUDA is disabled"
103             msg_end = " or no CUDA enabled devices are present."
104             msg_generic_problem = "Error: CUDA device intialisation problem."
105             msg = getattr(e, 'msg', None)
106             if msg is not None:
107                 if msg_not_found in msg:
108                     err_msg = msg_not_found + msg_end
109                 elif msg_disabled_by_user in msg:
110                     err_msg = msg_disabled_by_user + msg_end
111                 else:
112                     err_msg = msg_generic_problem + " Message:" + msg
113             else:
114                 err_msg = msg_generic_problem + " " + str(e)
115             # Best effort error report
116             print("%s\nError class: %s" % (err_msg, str(type(e))))
117         else:
118             try:
119                 cu.detect()
120                 dv = ct.c_int(0)
121                 cudriver.cuDriverGetVersion(ct.byref(dv))
122                 print(fmt % ("CUDA driver version", dv.value))
123                 print("CUDA libraries:")
124                 cudadrv.libs.test(sys.platform, print_paths=False)
125             except:
126                 print(
127                     "Error: Probing CUDA failed (device and driver present, runtime problem?)\n")
128 
129         print("")
130         print("__ROC Information__")
131         roc_is_available = roc.is_available()
132         print(fmt % ("ROC available", roc_is_available))
133 
134         toolchains = []
135         try:
136             libhlc.HLC()
137             toolchains.append('librocmlite library')
138         except:
139             pass
140         try:
141             cmd = hlc.CmdLine().check_tooling()
142             toolchains.append('ROC command line tools')
143         except:
144             pass
145 
146         # if no ROC try and report why
147         if not roc_is_available:
148             from numba.roc.hsadrv.driver import hsa
149             try:
150                 hsa.is_available
151             except BaseException as e:
152                 msg = str(e)
153             else:
154                msg = 'No ROC toolchains found.'
155             print(fmt % ("Error initialising ROC due to", msg))
156 
157         if toolchains:
158             print(fmt % ("Available Toolchains", ', '.join(toolchains)))
159 
160         try:
161             # ROC might not be available due to lack of tool chain, but HSA
162             # agents may be listed
163             from numba.roc.hsadrv.driver import hsa, dgpu_count
164             decode = lambda x: x.decode('utf-8') if isinstance(x, bytes) else x
165             print("\nFound %s HSA Agents:" % len(hsa.agents))
166             for i, agent in enumerate(hsa.agents):
167                 print('Agent id  : %s' % i)
168                 print('    vendor: %s' % decode(agent.vendor_name))
169                 print('      name: %s' % decode(agent.name))
170                 print('      type: %s' % agent.device)
171                 print("")
172 
173             _dgpus = []
174             for a in hsa.agents:
175                 if a.is_component and a.device == 'GPU':
176                    _dgpus.append(decode(a.name))
177             print(fmt % ("Found %s discrete GPU(s)" % dgpu_count(), \
178                   ', '.join(_dgpus)))
179         except Exception as e:
180             print("No HSA Agents found, encountered exception when searching:")
181             print(e)
182 
183 
184         print("")
185         print("__SVML Information__")
186         # replicate some SVML detection logic from numba.__init__ here.
187         # if SVML load fails in numba.__init__ the splitting of the logic
188         # here will help diagnosis of the underlying issue
189         have_svml_library = True
190         try:
191             if sys.platform.startswith('linux'):
192                 llvmbind.load_library_permanently("libsvml.so")
193             elif sys.platform.startswith('darwin'):
194                 llvmbind.load_library_permanently("libsvml.dylib")
195             elif sys.platform.startswith('win'):
196                 llvmbind.load_library_permanently("svml_dispmd")
197             else:
198                 have_svml_library = False
199         except:
200             have_svml_library = False
201         func = getattr(llvmbind.targets, "has_svml", None)
202         llvm_svml_patched = func() if func is not None else False
203         svml_operational = (config.USING_SVML and llvm_svml_patched \
204                             and have_svml_library)
205         print(fmt % ("SVML state, config.USING_SVML", config.USING_SVML))
206         print(fmt % ("SVML library found and loaded", have_svml_library))
207         print(fmt % ("llvmlite using SVML patched LLVM", llvm_svml_patched))
208         print(fmt % ("SVML operational:", svml_operational))
209 
210         # Look for conda and conda information
211         print("")
212         print("__Conda Information__")
213         cmd = ["conda", "info", "--json"]
214         try:
215             conda_out = check_output(cmd)
216         except Exception as e:
217             print(
218                 "Conda not present/not working.\nError was %s\n" % e)
219         else:
220             data = ''.join(conda_out.decode("utf-8").splitlines())
221             jsond = json.loads(data)
222             keys = ['conda_build_version',
223                     'conda_env_version',
224                     'platform',
225                     'python_version',
226                     'root_writable']
227             for k in keys:
228                 try:
229                     print(fmt % (k, jsond[k]))
230                 except KeyError:
231                     pass
232 
233             # get info about current environment
234             cmd = ["conda", "list"]
235             try:
236                 conda_out = check_output(cmd)
237             except CalledProcessError as e:
238                 print("Error: Conda command failed. Error was %s\n" % e.output)
239             else:
240                 print("")
241                 print("__Current Conda Env__")
242                 data = conda_out.decode("utf-8").splitlines()
243                 for k in data:
244                     if k[0] != '#':  # don't show where the env is, personal data
245                         print(k)
246 
247         print("-" * 80)
248 
249     except Exception as e:
250         print("Error: The system reporting tool has failed unexpectedly.")
251         print("Exception was:")
252         print(e)
253 
254     finally:
255         print(
256             "%s" %
257             "If requested, please copy and paste the information between\n"
258             "the dashed (----) lines, or from a given specific section as\n"
259             "appropriate.\n\n"
260             "=============================================================\n"
261             "IMPORTANT: Please ensure that you are happy with sharing the\n"
262             "contents of the information present, any information that you\n"
263             "wish to keep private you should remove before sharing.\n"
264             "=============================================================\n")
265 
266 
267 def make_parser():
268     parser = argparse.ArgumentParser()
269     parser.add_argument('--annotate', help='Annotate source',
270                         action='store_true')
271     parser.add_argument('--dump-llvm', action="store_true",
272                         help='Print generated llvm assembly')
273     parser.add_argument('--dump-optimized', action='store_true',
274                         help='Dump the optimized llvm assembly')
275     parser.add_argument('--dump-assembly', action='store_true',
276                         help='Dump the LLVM generated assembly')
277     parser.add_argument('--dump-cfg', action="store_true",
278                         help='[Deprecated] Dump the control flow graph')
279     parser.add_argument('--dump-ast', action="store_true",
280                         help='[Deprecated] Dump the AST')
281     parser.add_argument('--annotate-html', nargs=1,
282                         help='Output source annotation as html')
283     parser.add_argument('-s', '--sysinfo', action="store_true",
284                         help='Output system information for bug reporting')
285     parser.add_argument('filename', nargs='?', help='Python source filename')
286     return parser
287 
288 
289 def main():
290     parser = make_parser()
291     args = parser.parse_args()
292 
293     if args.dump_cfg:
294         print("CFG dump is removed.")
295         sys.exit(1)
296     if args.dump_ast:
297         print("AST dump is removed.  Numba no longer depends on AST.")
298         sys.exit(1)
299 
300     if args.sysinfo:
301         print("System info:")
302         get_sys_info()
303         sys.exit(0)
304 
305     os.environ['NUMBA_DUMP_ANNOTATION'] = str(int(args.annotate))
306     if args.annotate_html is not None:
307         try:
308             from jinja2 import Template
309         except ImportError:
310             raise ImportError("Please install the 'jinja2' package")
311         os.environ['NUMBA_DUMP_HTML'] = str(args.annotate_html[0])
312     os.environ['NUMBA_DUMP_LLVM'] = str(int(args.dump_llvm))
313     os.environ['NUMBA_DUMP_OPTIMIZED'] = str(int(args.dump_optimized))
314     os.environ['NUMBA_DUMP_ASSEMBLY'] = str(int(args.dump_assembly))
315 
316     if args.filename:
317         cmd = [sys.executable, args.filename]
318         subprocess.call(cmd)
319     else:
320         print("numba: error: the following arguments are required: filename")
321         sys.exit(1)
322
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/numba/numba_entry.py b/numba/numba_entry.py
--- a/numba/numba_entry.py
+++ b/numba/numba_entry.py
@@ -11,6 +11,7 @@
     # function which then exits.
     import platform
     import json
+    import multiprocessing
     from numba import config
     from numba import cuda as cu
     from numba.cuda import cudadrv
@@ -26,15 +27,57 @@
     from subprocess import check_output, CalledProcessError
 
     try:
-        fmt = "%-35s : %-s"
+        fmt = "%-45s : %-s"
         print("-" * 80)
         print("__Time Stamp__")
         print(datetime.utcnow())
         print("")
 
         print("__Hardware Information__")
+        system_name = platform.system()
         print(fmt % ("Machine", platform.machine()))
         print(fmt % ("CPU Name", llvmbind.get_host_cpu_name()))
+        if system_name == 'Linux':
+            strmatch = 'Cpus_allowed'
+            try:
+                loc = '/proc/self/status'
+                with open(loc, 'rt') as f:
+                    proc_stat = f.read().splitlines()
+                    for x in proc_stat:
+                        if x.startswith(strmatch):
+                            if x.startswith('%s:' % strmatch):
+                                hexnum = '0x%s' % x.split(':')[1].strip()
+                                acc_cpus = int(hexnum, 16)
+                                _n = str(bin(acc_cpus).count('1'))
+                                print(fmt % ("Number of accessible CPU cores",
+                                                _n))
+                            elif x.startswith('%s_list:' % strmatch):
+                                _a = x.split(':')[1].strip()
+                                print(fmt % ("Listed accessible CPUs cores",
+                                                _a))
+            except BaseException:
+                print(fmt % ("CPU count", multiprocessing.cpu_count()))
+            # See if CFS is in place
+            # https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
+            try:
+                def scrape_lines(loc):
+                    with open(loc, 'rt') as f:
+                        return f.read().splitlines()
+                loc = '/sys/fs/cgroup/cpuacct/cpu.cfs_period_us'
+                cfs_period = int(scrape_lines(loc)[0])
+                loc = '/sys/fs/cgroup/cpuacct/cpu.cfs_quota_us'
+                cfs_quota = int(scrape_lines(loc)[0])
+                if cfs_quota == -1:
+                    print(fmt % ("CFS restrictions", "None"))
+                else:
+                    runtime_amount = float(cfs_quota)/float(cfs_period)
+                    print(fmt % ("CFS restrictions (CPUs worth of runtime)",
+                                 runtime_amount))
+            except BaseException:
+                print(fmt % ("CFS restrictions", 'Information not available'))
+        else:
+            print(fmt % ("CPU count", multiprocessing.cpu_count()))
+
         try:
             featuremap = llvmbind.get_host_cpu_features()
         except RuntimeError:
@@ -50,7 +93,6 @@
         print("__OS Information__")
         print(fmt % ("Platform", platform.platform(aliased=True)))
         print(fmt % ("Release", platform.release()))
-        system_name = platform.system()
         print(fmt % ("System Name", system_name))
         print(fmt % ("Version", platform.version()))
         try:

{"golden_diff": "diff --git a/numba/numba_entry.py b/numba/numba_entry.py\n--- a/numba/numba_entry.py\n+++ b/numba/numba_entry.py\n@@ -11,6 +11,7 @@\n     # function which then exits.\n     import platform\n     import json\n+    import multiprocessing\n     from numba import config\n     from numba import cuda as cu\n     from numba.cuda import cudadrv\n@@ -26,15 +27,57 @@\n     from subprocess import check_output, CalledProcessError\n \n     try:\n-        fmt = \"%-35s : %-s\"\n+        fmt = \"%-45s : %-s\"\n         print(\"-\" * 80)\n         print(\"__Time Stamp__\")\n         print(datetime.utcnow())\n         print(\"\")\n \n         print(\"__Hardware Information__\")\n+        system_name = platform.system()\n         print(fmt % (\"Machine\", platform.machine()))\n         print(fmt % (\"CPU Name\", llvmbind.get_host_cpu_name()))\n+        if system_name == 'Linux':\n+            strmatch = 'Cpus_allowed'\n+            try:\n+                loc = '/proc/self/status'\n+                with open(loc, 'rt') as f:\n+                    proc_stat = f.read().splitlines()\n+                    for x in proc_stat:\n+                        if x.startswith(strmatch):\n+                            if x.startswith('%s:' % strmatch):\n+                                hexnum = '0x%s' % x.split(':')[1].strip()\n+                                acc_cpus = int(hexnum, 16)\n+                                _n = str(bin(acc_cpus).count('1'))\n+                                print(fmt % (\"Number of accessible CPU cores\",\n+                                                _n))\n+                            elif x.startswith('%s_list:' % strmatch):\n+                                _a = x.split(':')[1].strip()\n+                                print(fmt % (\"Listed accessible CPUs cores\",\n+                                                _a))\n+            except BaseException:\n+                print(fmt % (\"CPU count\", multiprocessing.cpu_count()))\n+            # See if CFS is in place\n+            # https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt\n+            try:\n+                def scrape_lines(loc):\n+                    with open(loc, 'rt') as f:\n+                        return f.read().splitlines()\n+                loc = '/sys/fs/cgroup/cpuacct/cpu.cfs_period_us'\n+                cfs_period = int(scrape_lines(loc)[0])\n+                loc = '/sys/fs/cgroup/cpuacct/cpu.cfs_quota_us'\n+                cfs_quota = int(scrape_lines(loc)[0])\n+                if cfs_quota == -1:\n+                    print(fmt % (\"CFS restrictions\", \"None\"))\n+                else:\n+                    runtime_amount = float(cfs_quota)/float(cfs_period)\n+                    print(fmt % (\"CFS restrictions (CPUs worth of runtime)\",\n+                                 runtime_amount))\n+            except BaseException:\n+                print(fmt % (\"CFS restrictions\", 'Information not available'))\n+        else:\n+            print(fmt % (\"CPU count\", multiprocessing.cpu_count()))\n+\n         try:\n             featuremap = llvmbind.get_host_cpu_features()\n         except RuntimeError:\n@@ -50,7 +93,6 @@\n         print(\"__OS Information__\")\n         print(fmt % (\"Platform\", platform.platform(aliased=True)))\n         print(fmt % (\"Release\", platform.release()))\n-        system_name = platform.system()\n         print(fmt % (\"System Name\", system_name))\n         print(fmt % (\"Version\", platform.version()))\n         try:\n", "issue": "`numba -s` should show total cores and available cores\nAs title.\n", "before_files": [{"content": "from __future__ import print_function, division, absolute_import\n\nimport sys\nimport argparse\nimport os\nimport subprocess\n\n\ndef get_sys_info():\n    # delay these imports until now as they are only needed in this\n    # function which then exits.\n    import platform\n    import json\n    from numba import config\n    from numba import cuda as cu\n    from numba.cuda import cudadrv\n    from numba.cuda.cudadrv.driver import driver as cudriver\n    from numba import roc\n    from numba.roc.hlc import hlc, libhlc\n    import textwrap as tw\n    import ctypes as ct\n    import llvmlite.binding as llvmbind\n    import locale\n    from datetime import datetime\n    from itertools import chain\n    from subprocess import check_output, CalledProcessError\n\n    try:\n        fmt = \"%-35s : %-s\"\n        print(\"-\" * 80)\n        print(\"__Time Stamp__\")\n        print(datetime.utcnow())\n        print(\"\")\n\n        print(\"__Hardware Information__\")\n        print(fmt % (\"Machine\", platform.machine()))\n        print(fmt % (\"CPU Name\", llvmbind.get_host_cpu_name()))\n        try:\n            featuremap = llvmbind.get_host_cpu_features()\n        except RuntimeError:\n            print(fmt % (\"CPU Features\", \"NA\"))\n        else:\n            features = sorted([key for key, value in featuremap.items()\n                               if value])\n            cpu_feat = tw.fill(' '.join(features), 80)\n            print(fmt % (\"CPU Features\", \"\"))\n            print(cpu_feat)\n        print(\"\")\n\n        print(\"__OS Information__\")\n        print(fmt % (\"Platform\", platform.platform(aliased=True)))\n        print(fmt % (\"Release\", platform.release()))\n        system_name = platform.system()\n        print(fmt % (\"System Name\", system_name))\n        print(fmt % (\"Version\", platform.version()))\n        try:\n            if system_name == 'Linux':\n                info = platform.linux_distribution()\n            elif system_name == 'Windows':\n                info = platform.win32_ver()\n            elif system_name == 'Darwin':\n                info = platform.mac_ver()\n            else:\n                raise RuntimeError(\"Unknown system.\")\n            buf = ''.join([x\n                           if x != '' else ' '\n                           for x in list(chain.from_iterable(info))])\n            print(fmt % (\"OS specific info\", buf))\n\n            if system_name == 'Linux':\n                print(fmt % (\"glibc info\", ' '.join(platform.libc_ver())))\n        except:\n            print(\"Error: System name incorrectly identified or unknown.\")\n        print(\"\")\n\n        print(\"__Python Information__\")\n        print(fmt % (\"Python Compiler\", platform.python_compiler()))\n        print(\n            fmt %\n            (\"Python Implementation\",\n             platform.python_implementation()))\n        print(fmt % (\"Python Version\", platform.python_version()))\n        print(\n            fmt %\n            (\"Python Locale \", ' '.join(\n                [x for x in locale.getdefaultlocale() if x is not None])))\n\n        print(\"\")\n        print(\"__LLVM information__\")\n        print(\n            fmt %\n            (\"LLVM version\", '.'.join(\n                [str(k) for k in llvmbind.llvm_version_info])))\n\n        print(\"\")\n        print(\"__CUDA Information__\")\n        # Look for GPUs\n        try:\n            cu.list_devices()[0]  # will a device initialise?\n        except BaseException as e:\n            msg_not_found = \"CUDA driver library cannot be found\"\n            msg_disabled_by_user = \"CUDA is disabled\"\n            msg_end = \" or no CUDA enabled devices are present.\"\n            msg_generic_problem = \"Error: CUDA device intialisation problem.\"\n            msg = getattr(e, 'msg', None)\n            if msg is not None:\n                if msg_not_found in msg:\n                    err_msg = msg_not_found + msg_end\n                elif msg_disabled_by_user in msg:\n                    err_msg = msg_disabled_by_user + msg_end\n                else:\n                    err_msg = msg_generic_problem + \" Message:\" + msg\n            else:\n                err_msg = msg_generic_problem + \" \" + str(e)\n            # Best effort error report\n            print(\"%s\\nError class: %s\" % (err_msg, str(type(e))))\n        else:\n            try:\n                cu.detect()\n                dv = ct.c_int(0)\n                cudriver.cuDriverGetVersion(ct.byref(dv))\n                print(fmt % (\"CUDA driver version\", dv.value))\n                print(\"CUDA libraries:\")\n                cudadrv.libs.test(sys.platform, print_paths=False)\n            except:\n                print(\n                    \"Error: Probing CUDA failed (device and driver present, runtime problem?)\\n\")\n\n        print(\"\")\n        print(\"__ROC Information__\")\n        roc_is_available = roc.is_available()\n        print(fmt % (\"ROC available\", roc_is_available))\n\n        toolchains = []\n        try:\n            libhlc.HLC()\n            toolchains.append('librocmlite library')\n        except:\n            pass\n        try:\n            cmd = hlc.CmdLine().check_tooling()\n            toolchains.append('ROC command line tools')\n        except:\n            pass\n\n        # if no ROC try and report why\n        if not roc_is_available:\n            from numba.roc.hsadrv.driver import hsa\n            try:\n                hsa.is_available\n            except BaseException as e:\n                msg = str(e)\n            else:\n               msg = 'No ROC toolchains found.'\n            print(fmt % (\"Error initialising ROC due to\", msg))\n\n        if toolchains:\n            print(fmt % (\"Available Toolchains\", ', '.join(toolchains)))\n\n        try:\n            # ROC might not be available due to lack of tool chain, but HSA\n            # agents may be listed\n            from numba.roc.hsadrv.driver import hsa, dgpu_count\n            decode = lambda x: x.decode('utf-8') if isinstance(x, bytes) else x\n            print(\"\\nFound %s HSA Agents:\" % len(hsa.agents))\n            for i, agent in enumerate(hsa.agents):\n                print('Agent id  : %s' % i)\n                print('    vendor: %s' % decode(agent.vendor_name))\n                print('      name: %s' % decode(agent.name))\n                print('      type: %s' % agent.device)\n                print(\"\")\n\n            _dgpus = []\n            for a in hsa.agents:\n                if a.is_component and a.device == 'GPU':\n                   _dgpus.append(decode(a.name))\n            print(fmt % (\"Found %s discrete GPU(s)\" % dgpu_count(), \\\n                  ', '.join(_dgpus)))\n        except Exception as e:\n            print(\"No HSA Agents found, encountered exception when searching:\")\n            print(e)\n\n\n        print(\"\")\n        print(\"__SVML Information__\")\n        # replicate some SVML detection logic from numba.__init__ here.\n        # if SVML load fails in numba.__init__ the splitting of the logic\n        # here will help diagnosis of the underlying issue\n        have_svml_library = True\n        try:\n            if sys.platform.startswith('linux'):\n                llvmbind.load_library_permanently(\"libsvml.so\")\n            elif sys.platform.startswith('darwin'):\n                llvmbind.load_library_permanently(\"libsvml.dylib\")\n            elif sys.platform.startswith('win'):\n                llvmbind.load_library_permanently(\"svml_dispmd\")\n            else:\n                have_svml_library = False\n        except:\n            have_svml_library = False\n        func = getattr(llvmbind.targets, \"has_svml\", None)\n        llvm_svml_patched = func() if func is not None else False\n        svml_operational = (config.USING_SVML and llvm_svml_patched \\\n                            and have_svml_library)\n        print(fmt % (\"SVML state, config.USING_SVML\", config.USING_SVML))\n        print(fmt % (\"SVML library found and loaded\", have_svml_library))\n        print(fmt % (\"llvmlite using SVML patched LLVM\", llvm_svml_patched))\n        print(fmt % (\"SVML operational:\", svml_operational))\n\n        # Look for conda and conda information\n        print(\"\")\n        print(\"__Conda Information__\")\n        cmd = [\"conda\", \"info\", \"--json\"]\n        try:\n            conda_out = check_output(cmd)\n        except Exception as e:\n            print(\n                \"Conda not present/not working.\\nError was %s\\n\" % e)\n        else:\n            data = ''.join(conda_out.decode(\"utf-8\").splitlines())\n            jsond = json.loads(data)\n            keys = ['conda_build_version',\n                    'conda_env_version',\n                    'platform',\n                    'python_version',\n                    'root_writable']\n            for k in keys:\n                try:\n                    print(fmt % (k, jsond[k]))\n                except KeyError:\n                    pass\n\n            # get info about current environment\n            cmd = [\"conda\", \"list\"]\n            try:\n                conda_out = check_output(cmd)\n            except CalledProcessError as e:\n                print(\"Error: Conda command failed. Error was %s\\n\" % e.output)\n            else:\n                print(\"\")\n                print(\"__Current Conda Env__\")\n                data = conda_out.decode(\"utf-8\").splitlines()\n                for k in data:\n                    if k[0] != '#':  # don't show where the env is, personal data\n                        print(k)\n\n        print(\"-\" * 80)\n\n    except Exception as e:\n        print(\"Error: The system reporting tool has failed unexpectedly.\")\n        print(\"Exception was:\")\n        print(e)\n\n    finally:\n        print(\n            \"%s\" %\n            \"If requested, please copy and paste the information between\\n\"\n            \"the dashed (----) lines, or from a given specific section as\\n\"\n            \"appropriate.\\n\\n\"\n            \"=============================================================\\n\"\n            \"IMPORTANT: Please ensure that you are happy with sharing the\\n\"\n            \"contents of the information present, any information that you\\n\"\n            \"wish to keep private you should remove before sharing.\\n\"\n            \"=============================================================\\n\")\n\n\ndef make_parser():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--annotate', help='Annotate source',\n                        action='store_true')\n    parser.add_argument('--dump-llvm', action=\"store_true\",\n                        help='Print generated llvm assembly')\n    parser.add_argument('--dump-optimized', action='store_true',\n                        help='Dump the optimized llvm assembly')\n    parser.add_argument('--dump-assembly', action='store_true',\n                        help='Dump the LLVM generated assembly')\n    parser.add_argument('--dump-cfg', action=\"store_true\",\n                        help='[Deprecated] Dump the control flow graph')\n    parser.add_argument('--dump-ast', action=\"store_true\",\n                        help='[Deprecated] Dump the AST')\n    parser.add_argument('--annotate-html', nargs=1,\n                        help='Output source annotation as html')\n    parser.add_argument('-s', '--sysinfo', action=\"store_true\",\n                        help='Output system information for bug reporting')\n    parser.add_argument('filename', nargs='?', help='Python source filename')\n    return parser\n\n\ndef main():\n    parser = make_parser()\n    args = parser.parse_args()\n\n    if args.dump_cfg:\n        print(\"CFG dump is removed.\")\n        sys.exit(1)\n    if args.dump_ast:\n        print(\"AST dump is removed.  Numba no longer depends on AST.\")\n        sys.exit(1)\n\n    if args.sysinfo:\n        print(\"System info:\")\n        get_sys_info()\n        sys.exit(0)\n\n    os.environ['NUMBA_DUMP_ANNOTATION'] = str(int(args.annotate))\n    if args.annotate_html is not None:\n        try:\n            from jinja2 import Template\n        except ImportError:\n            raise ImportError(\"Please install the 'jinja2' package\")\n        os.environ['NUMBA_DUMP_HTML'] = str(args.annotate_html[0])\n    os.environ['NUMBA_DUMP_LLVM'] = str(int(args.dump_llvm))\n    os.environ['NUMBA_DUMP_OPTIMIZED'] = str(int(args.dump_optimized))\n    os.environ['NUMBA_DUMP_ASSEMBLY'] = str(int(args.dump_assembly))\n\n    if args.filename:\n        cmd = [sys.executable, args.filename]\n        subprocess.call(cmd)\n    else:\n        print(\"numba: error: the following arguments are required: filename\")\n        sys.exit(1)\n", "path": "numba/numba_entry.py"}], "after_files": [{"content": "from __future__ import print_function, division, absolute_import\n\nimport sys\nimport argparse\nimport os\nimport subprocess\n\n\ndef get_sys_info():\n    # delay these imports until now as they are only needed in this\n    # function which then exits.\n    import platform\n    import json\n    import multiprocessing\n    from numba import config\n    from numba import cuda as cu\n    from numba.cuda import cudadrv\n    from numba.cuda.cudadrv.driver import driver as cudriver\n    from numba import roc\n    from numba.roc.hlc import hlc, libhlc\n    import textwrap as tw\n    import ctypes as ct\n    import llvmlite.binding as llvmbind\n    import locale\n    from datetime import datetime\n    from itertools import chain\n    from subprocess import check_output, CalledProcessError\n\n    try:\n        fmt = \"%-45s : %-s\"\n        print(\"-\" * 80)\n        print(\"__Time Stamp__\")\n        print(datetime.utcnow())\n        print(\"\")\n\n        print(\"__Hardware Information__\")\n        system_name = platform.system()\n        print(fmt % (\"Machine\", platform.machine()))\n        print(fmt % (\"CPU Name\", llvmbind.get_host_cpu_name()))\n        if system_name == 'Linux':\n            strmatch = 'Cpus_allowed'\n            try:\n                loc = '/proc/self/status'\n                with open(loc, 'rt') as f:\n                    proc_stat = f.read().splitlines()\n                    for x in proc_stat:\n                        if x.startswith(strmatch):\n                            if x.startswith('%s:' % strmatch):\n                                hexnum = '0x%s' % x.split(':')[1].strip()\n                                acc_cpus = int(hexnum, 16)\n                                _n = str(bin(acc_cpus).count('1'))\n                                print(fmt % (\"Number of accessible CPU cores\",\n                                                _n))\n                            elif x.startswith('%s_list:' % strmatch):\n                                _a = x.split(':')[1].strip()\n                                print(fmt % (\"Listed accessible CPUs cores\",\n                                                _a))\n            except BaseException:\n                print(fmt % (\"CPU count\", multiprocessing.cpu_count()))\n            # See if CFS is in place\n            # https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt\n            try:\n                def scrape_lines(loc):\n                    with open(loc, 'rt') as f:\n                        return f.read().splitlines()\n                loc = '/sys/fs/cgroup/cpuacct/cpu.cfs_period_us'\n                cfs_period = int(scrape_lines(loc)[0])\n                loc = '/sys/fs/cgroup/cpuacct/cpu.cfs_quota_us'\n                cfs_quota = int(scrape_lines(loc)[0])\n                if cfs_quota == -1:\n                    print(fmt % (\"CFS restrictions\", \"None\"))\n                else:\n                    runtime_amount = float(cfs_quota)/float(cfs_period)\n                    print(fmt % (\"CFS restrictions (CPUs worth of runtime)\",\n                                 runtime_amount))\n            except BaseException:\n                print(fmt % (\"CFS restrictions\", 'Information not available'))\n        else:\n            print(fmt % (\"CPU count\", multiprocessing.cpu_count()))\n\n        try:\n            featuremap = llvmbind.get_host_cpu_features()\n        except RuntimeError:\n            print(fmt % (\"CPU Features\", \"NA\"))\n        else:\n            features = sorted([key for key, value in featuremap.items()\n                               if value])\n            cpu_feat = tw.fill(' '.join(features), 80)\n            print(fmt % (\"CPU Features\", \"\"))\n            print(cpu_feat)\n        print(\"\")\n\n        print(\"__OS Information__\")\n        print(fmt % (\"Platform\", platform.platform(aliased=True)))\n        print(fmt % (\"Release\", platform.release()))\n        print(fmt % (\"System Name\", system_name))\n        print(fmt % (\"Version\", platform.version()))\n        try:\n            if system_name == 'Linux':\n                info = platform.linux_distribution()\n            elif system_name == 'Windows':\n                info = platform.win32_ver()\n            elif system_name == 'Darwin':\n                info = platform.mac_ver()\n            else:\n                raise RuntimeError(\"Unknown system.\")\n            buf = ''.join([x\n                           if x != '' else ' '\n                           for x in list(chain.from_iterable(info))])\n            print(fmt % (\"OS specific info\", buf))\n\n            if system_name == 'Linux':\n                print(fmt % (\"glibc info\", ' '.join(platform.libc_ver())))\n        except:\n            print(\"Error: System name incorrectly identified or unknown.\")\n        print(\"\")\n\n        print(\"__Python Information__\")\n        print(fmt % (\"Python Compiler\", platform.python_compiler()))\n        print(\n            fmt %\n            (\"Python Implementation\",\n             platform.python_implementation()))\n        print(fmt % (\"Python Version\", platform.python_version()))\n        print(\n            fmt %\n            (\"Python Locale \", ' '.join(\n                [x for x in locale.getdefaultlocale() if x is not None])))\n\n        print(\"\")\n        print(\"__LLVM information__\")\n        print(\n            fmt %\n            (\"LLVM version\", '.'.join(\n                [str(k) for k in llvmbind.llvm_version_info])))\n\n        print(\"\")\n        print(\"__CUDA Information__\")\n        # Look for GPUs\n        try:\n            cu.list_devices()[0]  # will a device initialise?\n        except BaseException as e:\n            msg_not_found = \"CUDA driver library cannot be found\"\n            msg_disabled_by_user = \"CUDA is disabled\"\n            msg_end = \" or no CUDA enabled devices are present.\"\n            msg_generic_problem = \"Error: CUDA device intialisation problem.\"\n            msg = getattr(e, 'msg', None)\n            if msg is not None:\n                if msg_not_found in msg:\n                    err_msg = msg_not_found + msg_end\n                elif msg_disabled_by_user in msg:\n                    err_msg = msg_disabled_by_user + msg_end\n                else:\n                    err_msg = msg_generic_problem + \" Message:\" + msg\n            else:\n                err_msg = msg_generic_problem + \" \" + str(e)\n            # Best effort error report\n            print(\"%s\\nError class: %s\" % (err_msg, str(type(e))))\n        else:\n            try:\n                cu.detect()\n                dv = ct.c_int(0)\n                cudriver.cuDriverGetVersion(ct.byref(dv))\n                print(fmt % (\"CUDA driver version\", dv.value))\n                print(\"CUDA libraries:\")\n                cudadrv.libs.test(sys.platform, print_paths=False)\n            except:\n                print(\n                    \"Error: Probing CUDA failed (device and driver present, runtime problem?)\\n\")\n\n        print(\"\")\n        print(\"__ROC Information__\")\n        roc_is_available = roc.is_available()\n        print(fmt % (\"ROC available\", roc_is_available))\n\n        toolchains = []\n        try:\n            libhlc.HLC()\n            toolchains.append('librocmlite library')\n        except:\n            pass\n        try:\n            cmd = hlc.CmdLine().check_tooling()\n            toolchains.append('ROC command line tools')\n        except:\n            pass\n\n        # if no ROC try and report why\n        if not roc_is_available:\n            from numba.roc.hsadrv.driver import hsa\n            try:\n                hsa.is_available\n            except BaseException as e:\n                msg = str(e)\n            else:\n               msg = 'No ROC toolchains found.'\n            print(fmt % (\"Error initialising ROC due to\", msg))\n\n        if toolchains:\n            print(fmt % (\"Available Toolchains\", ', '.join(toolchains)))\n\n        try:\n            # ROC might not be available due to lack of tool chain, but HSA\n            # agents may be listed\n            from numba.roc.hsadrv.driver import hsa, dgpu_count\n            decode = lambda x: x.decode('utf-8') if isinstance(x, bytes) else x\n            print(\"\\nFound %s HSA Agents:\" % len(hsa.agents))\n            for i, agent in enumerate(hsa.agents):\n                print('Agent id  : %s' % i)\n                print('    vendor: %s' % decode(agent.vendor_name))\n                print('      name: %s' % decode(agent.name))\n                print('      type: %s' % agent.device)\n                print(\"\")\n\n            _dgpus = []\n            for a in hsa.agents:\n                if a.is_component and a.device == 'GPU':\n                   _dgpus.append(decode(a.name))\n            print(fmt % (\"Found %s discrete GPU(s)\" % dgpu_count(), \\\n                  ', '.join(_dgpus)))\n        except Exception as e:\n            print(\"No HSA Agents found, encountered exception when searching:\")\n            print(e)\n\n\n        print(\"\")\n        print(\"__SVML Information__\")\n        # replicate some SVML detection logic from numba.__init__ here.\n        # if SVML load fails in numba.__init__ the splitting of the logic\n        # here will help diagnosis of the underlying issue\n        have_svml_library = True\n        try:\n            if sys.platform.startswith('linux'):\n                llvmbind.load_library_permanently(\"libsvml.so\")\n            elif sys.platform.startswith('darwin'):\n                llvmbind.load_library_permanently(\"libsvml.dylib\")\n            elif sys.platform.startswith('win'):\n                llvmbind.load_library_permanently(\"svml_dispmd\")\n            else:\n                have_svml_library = False\n        except:\n            have_svml_library = False\n        func = getattr(llvmbind.targets, \"has_svml\", None)\n        llvm_svml_patched = func() if func is not None else False\n        svml_operational = (config.USING_SVML and llvm_svml_patched \\\n                            and have_svml_library)\n        print(fmt % (\"SVML state, config.USING_SVML\", config.USING_SVML))\n        print(fmt % (\"SVML library found and loaded\", have_svml_library))\n        print(fmt % (\"llvmlite using SVML patched LLVM\", llvm_svml_patched))\n        print(fmt % (\"SVML operational:\", svml_operational))\n\n        # Look for conda and conda information\n        print(\"\")\n        print(\"__Conda Information__\")\n        cmd = [\"conda\", \"info\", \"--json\"]\n        try:\n            conda_out = check_output(cmd)\n        except Exception as e:\n            print(\n                \"Conda not present/not working.\\nError was %s\\n\" % e)\n        else:\n            data = ''.join(conda_out.decode(\"utf-8\").splitlines())\n            jsond = json.loads(data)\n            keys = ['conda_build_version',\n                    'conda_env_version',\n                    'platform',\n                    'python_version',\n                    'root_writable']\n            for k in keys:\n                try:\n                    print(fmt % (k, jsond[k]))\n                except KeyError:\n                    pass\n\n            # get info about current environment\n            cmd = [\"conda\", \"list\"]\n            try:\n                conda_out = check_output(cmd)\n            except CalledProcessError as e:\n                print(\"Error: Conda command failed. Error was %s\\n\" % e.output)\n            else:\n                print(\"\")\n                print(\"__Current Conda Env__\")\n                data = conda_out.decode(\"utf-8\").splitlines()\n                for k in data:\n                    if k[0] != '#':  # don't show where the env is, personal data\n                        print(k)\n\n        print(\"-\" * 80)\n\n    except Exception as e:\n        print(\"Error: The system reporting tool has failed unexpectedly.\")\n        print(\"Exception was:\")\n        print(e)\n\n    finally:\n        print(\n            \"%s\" %\n            \"If requested, please copy and paste the information between\\n\"\n            \"the dashed (----) lines, or from a given specific section as\\n\"\n            \"appropriate.\\n\\n\"\n            \"=============================================================\\n\"\n            \"IMPORTANT: Please ensure that you are happy with sharing the\\n\"\n            \"contents of the information present, any information that you\\n\"\n            \"wish to keep private you should remove before sharing.\\n\"\n            \"=============================================================\\n\")\n\n\ndef make_parser():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--annotate', help='Annotate source',\n                        action='store_true')\n    parser.add_argument('--dump-llvm', action=\"store_true\",\n                        help='Print generated llvm assembly')\n    parser.add_argument('--dump-optimized', action='store_true',\n                        help='Dump the optimized llvm assembly')\n    parser.add_argument('--dump-assembly', action='store_true',\n                        help='Dump the LLVM generated assembly')\n    parser.add_argument('--dump-cfg', action=\"store_true\",\n                        help='[Deprecated] Dump the control flow graph')\n    parser.add_argument('--dump-ast', action=\"store_true\",\n                        help='[Deprecated] Dump the AST')\n    parser.add_argument('--annotate-html', nargs=1,\n                        help='Output source annotation as html')\n    parser.add_argument('-s', '--sysinfo', action=\"store_true\",\n                        help='Output system information for bug reporting')\n    parser.add_argument('filename', nargs='?', help='Python source filename')\n    return parser\n\n\ndef main():\n    parser = make_parser()\n    args = parser.parse_args()\n\n    if args.dump_cfg:\n        print(\"CFG dump is removed.\")\n        sys.exit(1)\n    if args.dump_ast:\n        print(\"AST dump is removed.  Numba no longer depends on AST.\")\n        sys.exit(1)\n\n    if args.sysinfo:\n        print(\"System info:\")\n        get_sys_info()\n        sys.exit(0)\n\n    os.environ['NUMBA_DUMP_ANNOTATION'] = str(int(args.annotate))\n    if args.annotate_html is not None:\n        try:\n            from jinja2 import Template\n        except ImportError:\n            raise ImportError(\"Please install the 'jinja2' package\")\n        os.environ['NUMBA_DUMP_HTML'] = str(args.annotate_html[0])\n    os.environ['NUMBA_DUMP_LLVM'] = str(int(args.dump_llvm))\n    os.environ['NUMBA_DUMP_OPTIMIZED'] = str(int(args.dump_optimized))\n    os.environ['NUMBA_DUMP_ASSEMBLY'] = str(int(args.dump_assembly))\n\n    if args.filename:\n        cmd = [sys.executable, args.filename]\n        subprocess.call(cmd)\n    else:\n        print(\"numba: error: the following arguments are required: filename\")\n        sys.exit(1)\n", "path": "numba/numba_entry.py"}]}