eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: When I start the server.exe and it is trying to perform uvicorn.run(), the exception is being thrown: Traceback (most recent call last): File "logging\config.py", line 390, in resolve ModuleNotFoundError: No module named 'uvicorn.logging' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "logging\config.py", line 542, in configure File "logging\config.py", line 654, in configure_formatter File "logging\config.py", line 469, in configure_custom File "logging\config.py", line 397, in resolve File "logging\config.py", line 390, in resolve ValueError: Cannot resolve 'uvicorn.logging.DefaultFormatter': No module named 'uvicorn.logging' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "server.py", line 82, in <module> File "server.py", line 21, in run File "uvicorn\main.py", line 343, in run File "uvicorn\config.py", line 180, in __init__ File "uvicorn\config.py", line 223, in configure_logging File "logging\config.py", line 808, in dictConfig File "logging\config.py", line 545, in configure ValueError: Unable to configure formatter 'default' [7932] Failed to execute script server  Note that the uvicorn.logging module does exist and when I perform the server`s code in Python, it operates correctly.

Answer: I encountered the same problem. And I found it's a job of hiddenimports,It's useful to modify the following lines in xxx.spec: a = Analysis(['xxx.py'], hiddenimports=['uvicorn.logging'], <everything else>)  however, there will still be other similar problems. So, I try to add all files of uvicorn,and it works with: hiddenimports=['uvicorn.lifespan.off','uvicorn.lifespan.on','uvicorn.lifespan', 'uvicorn.protocols.websockets.auto','uvicorn.protocols.websockets.wsproto_impl', 'uvicorn.protocols.websockets_impl','uvicorn.protocols.http.auto', 'uvicorn.protocols.http.h11_impl','uvicorn.protocols.http.httptools_impl', 'uvicorn.protocols.websockets','uvicorn.protocols.http','uvicorn.protocols', 'uvicorn.loops.auto','uvicorn.loops.asyncio','uvicorn.loops.uvloop','uvicorn.loops', 'uvicorn.logging'],  then, run: pyinstaller xxx.spec
Question: I am trying to install transformers using pip pip install transformers  after import transformers this error show Neither PyTorch nor TensorFlow >= 2.0 have been found.Models won't be available and only tokenizers, configuration, and file/data utilities can be used.  although I install TensorFlow-GPU= 2.3.1 and using conda system info Windows 10 python 3.6 cuda 10.1 tensorflow-gpu= 2.3.1 

Answer: I found the problem after investigate for 10 hours I installed tensorflow by using conda install tensorflow-gpu  and transformers by using pip after remove tensorflow-gpu and install it by using pip it works fine
Question: Is there a way to convert SMILES to either chemical name or IUPAC name using RDKit or other python modules? I couldn't find something very helpful in other posts. Thank you very much!

Answer: As far as I am aware this is not possible using rdkit, and I do not know of any python modules with this ability. If you are ok with using a web service you could use the NCI resolver. Here is a naive implementation of a function to retrieve an IUPAC identifier from a SMILES string: import requests CACTUS = "https://cactus.nci.nih.gov/chemical/structure/{0}/{1}" def smiles_to_iupac(smiles): rep = "iupac_name" url = CACTUS.format(smiles, rep) response = requests.get(url) response.raise_for_status() return response.text print(smiles_to_iupac('c1ccccc1')) print(smiles_to_iupac('CC(=O)OC1=CC=CC=C1C(=O)O')) [Out]: BENZENE 2-acetyloxybenzoic acid  You could easily extend it to convert multiple different formats, although the function isn't exactly fast... Another solution is to use PubChem. You can use the API with the python package pubchempy. Bear in mind this may return multiple compounds. import pubchempy # Use the SMILES you provided smiles = 'O=C(NCc1ccc(C(F)(F)F)cc1)[C@@H]1Cc2[nH]cnc2CN1Cc1ccc([N+](=O)[O-])cc1' compounds = pubchempy.get_compounds(smiles, namespace='smiles') match = compounds[0] print(match.iupac_name) [Out]: (6S)-5-[(4-nitrophenyl)methyl]-N-[[4-(trifluoromethyl)phenyl]methyl]-3,4,6,7-tetrahydroimidazo[4,5-c]pyridine-6-carboxamide
Question: My scrip ist currently using QtWidgets.QFileDialog.getOpenFileNames() to let the user select files within Windows explorer. Now I´m wondering if there is a way to let them select also folders, not just files. There are some similar posts, but none of them provides a working solution. I really dont want to use the QFileDialog file explorer to get around this.

Answer: QFileDialog doesn't allow that natively. The only solution is to create your own instance, do some small "patching". Note that in order to achieve this, you cannot use the native dialogs of your OS, as Qt has almost no control over them; that's the reason of the dialog.DontUseNativeDialog flag, which is mandatory. The following code works as much as static methods do, and returns the selected items (or none, if the dialog is cancelled). def getOpenFilesAndDirs(parent=None, caption='', directory='', filter='', initialFilter='', options=None): def updateText(): # update the contents of the line edit widget with the selected files selected = [] for index in view.selectionModel().selectedRows(): selected.append('"{}"'.format(index.data())) lineEdit.setText(' '.join(selected)) dialog = QtWidgets.QFileDialog(parent, windowTitle=caption) dialog.setFileMode(dialog.ExistingFiles) if options: dialog.setOptions(options) dialog.setOption(dialog.DontUseNativeDialog, True) if directory: dialog.setDirectory(directory) if filter: dialog.setNameFilter(filter) if initialFilter: dialog.selectNameFilter(initialFilter) # by default, if a directory is opened in file listing mode, # QFileDialog.accept() shows the contents of that directory, but we # need to be able to "open" directories as we can do with files, so we # just override accept() with the default QDialog implementation which # will just return exec_() dialog.accept = lambda: QtWidgets.QDialog.accept(dialog) # there are many item views in a non-native dialog, but the ones displaying # the actual contents are created inside a QStackedWidget; they are a # QTreeView and a QListView, and the tree is only used when the # viewMode is set to QFileDialog.Details, which is not this case stackedWidget = dialog.findChild(QtWidgets.QStackedWidget) view = stackedWidget.findChild(QtWidgets.QListView) view.selectionModel().selectionChanged.connect(updateText) lineEdit = dialog.findChild(QtWidgets.QLineEdit) # clear the line edit contents whenever the current directory changes dialog.directoryEntered.connect(lambda: lineEdit.setText('')) dialog.exec_() return dialog.selectedFiles()
Question: I have just started using hvPlot today, as part of Panel. I am having a difficult time figuring out how to disable scientific notation in my plots. For example here is a simple bar plot. The axis and the tootltip are in scientific notation. How can I change the format to a simple int?  I am showing this to non numerical and non techy management. They would rather see just basic integers and I don’t want to have to explain to them what scientific notation is. I could not find anything in the docs to help me: https://hvplot.holoviz.org/user_guide/Customization.html I’ve also tried to cobble together suggestions from Bokeh docs. I can’t figure it out. Please help! Thanks My simple df:  local_date amount 0 Jan 19 506124.98 1 Feb 19 536687.28 2 Mar 19 652279.31 3 Apr 19 629440.06 4 May 19 703527.00 5 Jun 19 724234.08 6 Jul 19 733413.32 7 Aug 19 758647.44 8 Sep 19 782676.16 9 Oct 19 833674.28 10 Nov 19 864649.74 11 Dec 19 849920.47 12 Jan 20 857732.52 13 Feb 20 927399.50 14 Mar 20 1152440.49 15 Apr 20 1285779.35 16 May 20 1431744.76 17 Jun 20 1351893.95 18 Jul 20 1325507.38 19 Aug 20 1299528.81  And code: df.hvplot.bar(height=500,width=1000) 

Answer: You can specify the formatter you would like to use in either x- or y-axis ticks, as such: df.hvplot.bar(height=500,width=1000, yformatter='%.0f')  According to the Customization page you also referenced, the xformatter and yformatter arguments can accept "printf formatter, e.g. '%.3f', and bokeh TickFormatter". So, another way to do it is by passing a custom formatter from boken.models.formatters and customize it as such (Note: there's many other formatters you can also explore). For example: from bokeh.models.formatters import BasicTickFormatter df.hvplot.bar(height=500,width=1000, yformatter=BasicTickFormatter(use_scientific=False))  Both should give you a result like this:  Now, editing the hover tooltip format is a bit tricker. One way to do it is to assign the figure object as custom HoverTool, in the following fashion: from bokeh.models import HoverTool hover = HoverTool(tooltips=[("amount", "@amount{0,0}"), ("local_date", "@local_date")]) df.hvplot.bar(height=500, width=1000, yformatter='%.0f', use_index=False).opts(tools=[hover])  You can find more details on how to configure a custom HoverTool here.
Question: Imagine you have published two pre-releases:  package 0.0.1.dev0 package 0.0.2.dev0  My install_requires section in setup.py states: [ 'package>=0.0.2,<1.0.0' ]  Now, when i run pip install . --upgrade --pre I get an error:  ERROR: Could not find a version that satisfies the requirement package<1.0.0,>=0.0.2 (from versions: 0.0.1.dev0, 0.0.2.dev0) ERROR: No matching distribution found for package<1.0.0,>=0.0.2  What am I doing wrong? Isn't the --pre flag supposed to tell pip to match pre-release versions?

Answer: Summary The pip --pre option directs pip to include potential matching pre-release and development versions, but it does not change the semantics of version matching. Since pre-release 0.0.2.dev0 is older than stable release 0.0.2, pip correctly reports an error when searching for a package that is at least as new as stable release 0.0.2. Explanation The key point of confusion is around the pip --pre option, which is documented as:  --pre Include pre-release and development versions. By default, pip only finds stable versions.  The premise of the question is that the --pre option should change the package-version-matching semantics such that pre-release version suffixes would be ignored when matching against stable versions. To further clarify, consider the compatible release operator ~=. PEP 440 section Compatible release, states in part:  For a given release identifier V.N, the compatible release clause is approximately equivalent to the pair of comparison clauses: >= V.N, == V.* ... If a pre-release, post-release or developmental release is named in a compatible release clause as V.N.suffix, then the suffix is ignored when determining the required prefix match: ~= 2.2.post3 = 2.2.post3, == 2.* ~= 1.4.5a4 = 1.4.5a4, == 1.4.*  This example makes it clear that the suffix is ignored. The following requirement does not match 0.0.2.dev0: install_requires=['package~=0.0.2'] # ERROR: ResolutionImpossible  Whereas this example does match stable release 0.0.2: install_requires=['package~=0.0.2.dev0'] # OK - suffix ignored
Question: I wish to return the version of Jupyter Notebook from within a cell of a notebook. For example, to get the python version, I run: from platform import python_version python_version()  or to get the pandas version: pd.__version__  I have tried: notebook.version() ipython.version() jupyter.version()  and several other, related forms (including capitalizing the first letters), but get errors that (for example):  NameError: name 'jupyter' is not defined  I am aware of other ways (e.g. clicking on Help>About in the GUI menu; using the conda command line) but I want to automate documentation of all package versions. If it matters, I am running v6.1.1 of Notebook in a Python 3.7.3 environment.

Answer: Paste the following command into your jupyter cell(exclamation symbol means that you need to run shell command, not python) !jupyter --version  example output: jupyter core : 4.6.0 jupyter-notebook : 6.0.1 qtconsole : 4.7.5 ipython : 7.8.0 ipykernel : 5.1.3 jupyter client : 5.3.4 jupyter lab : not installed nbconvert : 5.6.0 ipywidgets : 7.5.1 nbformat : 4.4.0 traitlets : 4.3.3  To get the python version use the python --version command: !python --version  example output: Python 3.6.8  UPDATE: to get values as dict you can use the following script(not perfect, written in 3 minutes) import subprocess versions = subprocess.check_output(["jupyter", "--version"]).decode().split('\n') parsed_versions = {} for component in versions: if component == "": continue comps = list(map(str.strip, component.split(': '))) parsed_versions[comps[0]] = comps[1]  Value of parsed_versions variable { "jupyter core": "4.6.0", "jupyter-notebook": "6.0.1", "qtconsole": "4.7.5", "ipython": "7.8.0", "ipykernel": "5.1.3", "jupyter client": "5.3.4", "jupyter lab": "not installed", "nbconvert": "5.6.0", "ipywidgets": "7.5.1", "nbformat": "4.4.0", "traitlets": "4.3.3" }  UPDATE 2: Thanks to @TrentonMcKinney for suggestions on how to make this script better
Question: I've seen all over problems using Memcached in Django projects which is considered to be  The fastest, most efficient type of cache supported natively by Django  For instances,  Why doesn't memcache work in my Django? How to configure Memcache for Django on Google cloud AppEngine? Django doesn't use memcached framework memcache on django is not working How to use memcached in django project? How do you confirm django is using memcached? Configuring memcached with django What steps are needed to implement memcached in a Django application? How to use memcached in django project?  So, how can we then use it?

Answer: This answer explains how to install Memcached on Windows 10 and how to integrate it with Django through a specific client. It was validated using Memcached 1.4.4, Python 2.7 and Django 1.11.  In your Django project, under settings.py, add the following code in the bottom of the file SESSIONS_ENGINE='django.contrib.sessions.backends.cache' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } }   Install memcached client for Python with your virtual environment active (python-memcached) pip install python-memcached   Download Memcached using one of the following download links and extract it to a particular folder    http://downloads.northscale.com/memcached-win32-1.4.4-14.zip http://downloads.northscale.com/memcached-win64-1.4.4-14.zip    Open that folder location in the Terminal or PowerShell and run .\memcached.exe -h    you should get something like this   Run the following command (-m is for the amount of memory you want to dedicate and -vvv is for extreme verbose) .\memcached.exe -m 512 -vvv      In the view you want to use cache, specify it in urls.py like from django.conf.urls import include, url from django.views.decorators.cache import cache_page from .views import IndexView urlpatterns = [ url(r'^$', cache_page(60*60)(IndexView.as_view()), name="index"), ]   Go to the Django project, start the server and you should get much better results in your Time load.
Question: I'm a beginner in programming and I'm looking for a nice idea how to generate three integers that satisfy a condition. Example: We are given n = 30, and we've been asked to generate three integers a, b and c, so that 7*a + 5*b + 3*c = n. I tried to use for loops, but it takes too much time and I have a maximum testing time of 1000 ms. I'm using Python 3. My attempt: x = int(input()) c = [] k = [] w = [] for i in range(x): for j in range(x): for h in range(x): if 7*i + 5*j + 3*h = x: c.append(i) k.append(j) w.append(h) if len(c) == len(k) == len(w) print(-1) else: print(str(k[0]) + ' ' + str(c[0]) + ' ' + str(w[0])) 

Answer: import numpy as np def generate_answer(n: int, low_limit:int, high_limit: int): while True: a = np.random.randint(low_limit, high_limit + 1, 1)[0] b = np.random.randint(low_limit, high_limit + 1, 1)[0] c = (n - 7 * a - 5 * b) / 3.0 if int(c) == c and low_limit <= c <= high_limit: break return a, b, int(c) if __name__ == "__main__": n = 30 ans = generate_answer(low_limit=-5, high_limit=50, n=n) assert ans[0] * 7 + ans[1] * 5 + ans[2] * 3 == n print(ans)  If you select two of the numbers a, b, c, you know the third. In this case, I randomize ints for a, b, and I find c by c = (n - 7 * a - 5 * b) / 3.0. Make sure c is an integer, and in the allowed limits, and we are done. If it is not, randomize again.  If you want to generate all possibilities, def generate_all_answers(n: int, low_limit:int, high_limit: int): results = [] for a in range(low_limit, high_limit + 1): for b in range(low_limit, high_limit + 1): c = (n - 7 * a - 5 * b) / 3.0 if int(c) == c and low_limit <= c <= high_limit: results.append((a, b, int(c))) return results
Question: I am trying to figure out the difference between the __lte and __gte in Django. The reason being that I am trying to create a function with dates that can work only with a time frame, so I've been researching between Field Lookups Comparison. I've looked up several documentations https://docs.djangoproject.com/en/3.0/ref/models/querysets/#exclude but didn't reach a conclusive answer. Edited: I learned that lte is less than or equal and gte greater than or equal Here is some documentation link

Answer: The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value. So for example: MyModel.objects.filter(field__gte=5) # field ≥ 5 MyModel.objects.filter(field__lte=5) # field ≤ 5
Question: I saw this on a jupyter notebook: !pip install -Uqq fastbook  ! runs commands on shell. U stands for upgrade. What do the options qq mean? q stands for quiet. Why are there two q's? Looked up pip install --help. Looked up User guide to no avail.

Answer: The option -q of pip give less output. The Option is additive. In other words, you can use it up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels). So:  -q  means display only the messages with WARNING,ERROR,CRITICAL log levels -qq  means display only the messages with ERROR,CRITICAL log levels -qqq means display only the messages with CRITICAL log level
Question: I'm trying to calculate the NDCG score for binary relevances: from sklearn.metrics import ndcg_score y_true = [0, 1, 0] y_pred = [0, 1, 0] ndcg_score(y_true, y_pred)  And getting: ValueError: Only ('multilabel-indicator', 'continuous-multioutput', 'multiclass-multioutput') formats are supported. Got binary instead  Is there a way to make this work?

Answer: Please try: from sklearn.metrics import ndcg_score y_true = [[0, 1, 0]] y_pred = [[0, 1, 0]] ndcg_score(y_true, y_pred) 1.0  Note the expected shapes in the docs:  y_true: ndarray, shape (n_samples, n_labels) y_score: ndarray, shape (n_samples, n_labels)
Question: I'm trying to learn the Python version of Playwright. See here I would like to learn how to locate an element, so that I can do things with it. Like printing the inner HTML, clicking on it and such. The example below loads a page and prints the HTML from playwright import sync_playwright with sync_playwright() as p: browser = p.chromium.launch(headless=False) page = browser.newPage() page.goto('http://whatsmyuseragent.org/') print(page.innerHTML("*")) browser.close()  This page contains an element <div class="user-agent"> <p class="intro-text">Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4238.0 Safari/537.36</p> </div>  Using Selenium, I could locate the element and print it's content like this elem = driver.find_element_by_class_name("user-agent") print(elem) print(elem.get_attribute("innerHTML"))  How can I do the same in Playwright? #UPDATE# - Note if you want to run this in 2021+ that current versions of playwright have changed the syntax from CamelCase to snake_case.

Answer: You can use the querySelector function, and then call the innerHTML function: handle = page.querySelector(".user-agent") print(handle.innerHTML())
Question: I have a waterfall chart and I want to set each bar's color separately (blue for the first one, red for the 2nd, 3rd, and 4th one, green for 5th one, and blue for 6th one). All the relative bars in the chart are increasing, and the plotly only allows you to set three colors for increasing, decreasing, and total ones. Is there any way to do what I want? import plotly.graph_objects as go fig = go.Figure(go.Waterfall( name = "20", orientation = "v", measure = ["relative", "relative", "relative", "relative", "relative", "total"], x = ["Buy", "Transaction Cost", "Remodeling Cost", "Ownership Cost", "Gain", "Sell"], textposition = "outside", text = ["$200", "$14", "$45", "$5", "$86", "$350"], y = [200, 14, 45, 5, 86, 350], connector = {"visible": False} )) fig.show()  Result:  As I said, I want the color of the bar to be: blue for the first one, red for the 2nd, 3rd, and 4th one, green for 5th one, and blue for 6th one

Answer: Problem Ploty waterfall chart bar color customization. As OP mentioned, currently plotly supports customizing bar colors for decreasing, increasing, and totals. Solution In OP's example, to make color of bars (blue, red, red, red, green, blue):  set marker color red in increasing attribute set marker color blue in totals attribute add shapes of blue and green to the 1st and 4th bar via .add_shape()  import plotly.graph_objects as go fig = go.Figure(go.Waterfall( name = "20", orientation = "v", measure = ["relative", "relative", "relative", "relative", "relative", "total"], x = ["Buy", "Transaction Cost", "Remodeling Cost", "Ownership Cost", "Gain", "Sell"], textposition = "outside", text = ["$200", "$14", "$45", "$5", "$86", "$350"], y = [200, 14, 45, 5, 86, 350], increasing = {"marker":{"color":"red"}}, totals = {"marker":{"color":"blue"}}, connector = {"visible": False} )) fig.add_shape( type="rect", fillcolor="blue", line=dict(color="blue"), opacity=1, x0=-0.4, x1=0.4, xref="x", y0=0.0, y1=fig.data[0].y[0], yref="y" ) fig.add_shape( type="rect", fillcolor="green", line=dict(color="green"), opacity=1, x0=3.6, x1=4.4, xref="x", y0=fig.data[0].y[-1] - fig.data[0].y[-2], y1=fig.data[0].y[-1], yref="y" ) fig.show()  Which would yield the result OP wanted  Reference  https://plotly.com/python/waterfall-charts/ R Plotly: How to set the color of Individual Bars of a Waterfall Chart in R Plot.ly? https://plotly.com/python/styling-plotly-express/#updating-or-modifying-figures-made-with-plotly-express
Question: I deployed a large 3D model to aws sagemaker. Inference will take 2 minutes or more. I get the following error while calling the predictor from Python: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (0) from model with message "Your invocation timed out while waiting for a response from container model. Review the latency metrics for each container in Amazon CloudWatch, resolve the issue, and try again."'  In Cloud Watch I also see some PING time outs while the container is processing: 2020-10-07T16:02:39.718+02:00 2020/10/07 14:02:39 https://forums.aws.amazon.com/ 106#106: *251 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 10.32.0.2, server: , request: "GET /ping HTTP/1.1", upstream: "http://unix:/tmp/gunicorn.sock/ping", host: "model.aws.local:8080"  How do I increase the invocation time out? Or is there a way to make async invocations to an sagemaker endpoint?

Answer: It’s currently not possible to increase timeout—this is an open issue in GitHub. Looking through the issue and similar questions on SO, it seems like you may be able to use batch transforms in conjunction with inference. References https://stackoverflow.com/a/55642675/806876 Sagemaker Python SDK timeout issue: https://github.com/aws/sagemaker-python-sdk/issues/1119