question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
61,968,521 | 2020-5-23 | https://stackoverflow.com/questions/61968521/python-web-scraping-request-errormod-security | I am new and I try to grap source code of an Web page for tutorial.I got beautifulsoup install,request install. At first I want to grap the source.I am doing this scraping job from "https://pythonhow.com/example.html".I am not doing anything illegal and I think this site also established for this purposes.Here's my cod... | You can easily fix this issue by providing a user agent to the request. By doing so, the website will think that someone is actually visiting the site using a web browser. Here is the code that you want to use: import requests from bs4 import BeautifulSoup headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac O... | 9 | 32 |
61,944,815 | 2020-5-21 | https://stackoverflow.com/questions/61944815/how-to-set-seed-for-jitter-in-seaborn-stripplot | I am trying to reproduce stripplots exactly so that I can draw lines and write on them reliably. However, when I produce a stripplot with jitter the jitter is random and prevents me from achieving my goal. I have blindly tried some rcParams I found in other Stack Overflow posts, such as mpl.rcParams['svg.hashsalt'] whi... | jitter is determined by scipy.stats.uniform uniform is class uniform_gen(scipy.stats._distn_infrastructure.rv_continuous) Which is a subclass of class rv_continuous(rv_generic) Which has a seed parameter, and uses np.random Therefore, use np.random.seed() It needs to be called before each plot. In the case of the exa... | 7 | 9 |
61,948,867 | 2020-5-22 | https://stackoverflow.com/questions/61948867/add-file-extension-in-timedrotatingfilehandler | I am trying to implement the python logging using TimedRotatingFileHandler i'm getting the problem in adding the file extension in log filename here is my code Path(".\\Log").mkdir(parents=True, exist_ok=True) LOGGING_MSG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' LOGGING_DATE_FORMAT = '%m-%d %H:%... | You should use a custom namer: handler.namer = lambda name: name + ".log" Unfortunately, the namer function gets the processed name. The name param would be like "info.log.2020-05-22", so you'll end up with "info.log.2020-05-22.log". If double .log is not acceptable just remove the initial one: handler.namer = lambda ... | 7 | 8 |
61,923,188 | 2020-5-20 | https://stackoverflow.com/questions/61923188/how-to-stop-autopep8-not-installed-messages-in-code | I'm a new Python programmer using the Mac version of VS Code 1.45.1 to create a Django project. I have the Python and Django extensions installed. Every time I save a Django file, Code pops up this window: Formatter autopep8 is not installed. Install? Source: Python (Extension) [Yes] [Use black] [Use yapf] I keep clic... | You will receive this prompt if You have "formatOnSave" turned on as a setting You selected autopep8 as your formatter The Python extension can't find autopep8 So the options are: Turn off formatting on save Make sure you successfully installed autopep8 into your environment or you specified the path to autopep8 in ... | 20 | 10 |
61,942,138 | 2020-5-21 | https://stackoverflow.com/questions/61942138/apply-function-row-wise-to-pandas-dataframe | I have to calculate the distance on a hilbert-curve from 2D-Coordinates. With the hilbertcurve-package i built my own "hilbert"-function, to do so. The coordinates are stored in a dataframe (col_1 and col_2). As you see, my function works when applied to two values (test). However it just does not work when applied row... | Since you have hilbert(df.col_1, df.col_2) in the apply, that's immediately trying to call your function with the full pd.Serieses for those two columns, triggering that error. What you should be doing is: df.apply(lambda x: hilbert(x['col_1'], x['col_2']), axis=1) so that the lambda function given will be applied to ... | 9 | 19 |
61,921,940 | 2020-5-20 | https://stackoverflow.com/questions/61921940/running-poetry-fails-with-usr-bin-env-python-no-such-file-or-directory | I just installed poetry with the following install script curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 However, when I execute poetry it fails with the following error $ poetry /usr/bin/env: ‘python’: No such file or directory I recently upgraded to ubuntu 20.04, is ... | poetry is dependent on whatever python is and doesn't attempt to use a specific version of python unless otherwise specified. The above issue will exist on ubuntu systems moving forward 20.04 onwards as python2.7 is deprecated and the python command does not map to python3.x You'll find specifying an alias for python t... | 19 | 42 |
61,930,060 | 2020-5-21 | https://stackoverflow.com/questions/61930060/how-to-use-shapely-for-subtracting-two-polygons | I am not really sure how to explain this but I have 2 polygons, Polygon1 and Polygon2. These polygons overlapped with each other. How to do I get Polygon2 using Shapely without the P from Polygon1. | You are looking for a difference. In Shapely you can calculate it either by using a difference method or by simply subtracting* one polygon from another: from shapely.geometry import Polygon polygon1 = Polygon([(0.5, -0.866025), (1, 0), (0.5, 0.866025), (-0.5, 0.866025), (-1, 0), (-0.5, -0.866025)]) polygon2 = Polygon(... | 12 | 26 |
61,933,021 | 2020-5-21 | https://stackoverflow.com/questions/61933021/how-to-overwrite-data-on-an-existing-excel-sheet-while-preserving-all-other-shee | I have a pandas dataframe df which I want to overwrite to a sheet Data of an excel file while preserving all the other sheets since other sheets have formulas linked to sheet Data I used the following code but it does not overwrite an existing sheet, it just creates a new sheet with the name Data 1 with pd.ExcelWriter(... | You can do it using openpyxl: import pandas as pd from openpyxl import load_workbook book = load_workbook(filename) writer = pd.ExcelWriter(filename, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df.to_excel(writer, "Data") writer.save() You need to initialize wri... | 10 | 14 |
61,923,379 | 2020-5-20 | https://stackoverflow.com/questions/61923379/simple-keras-network-in-gradienttape-lookuperror-no-gradient-defined-for-opera | I've built a very simple TensorFlow Keras model with a single dense layer. It works perfectly fine outside a GradientTape block, but inside a GradientTape block it raises LookupError: No gradient defined for operation 'IteratorGetNext' (op type: IteratorGetNext) Code to reproduce: from tensorflow.keras.models import Se... | try to redefine the predict operation in GradientTape in this way with tf.GradientTape() as tape: print(model(fake_data).shape) | 12 | 15 |
61,918,827 | 2020-5-20 | https://stackoverflow.com/questions/61918827/ansible-no-longer-works | I have been learning Ansible on Windows 10 through WSL (using Pengwin, a Debian-based Linux) and it's been working fine up until last night. This morning, it's as though it doesn't exist any more: ❯ ansible Traceback (most recent call last): File "/usr/bin/ansible", line 34, in <module> from ansible import context Modu... | Your issue is coming from the fact that you are using the instructions to install Ansible on an Ubuntu distribution, when, as you stated it, Pengwin is a Debian based one. So you should use the chapter on how to install Ansible on Debian and not how to install Ansible on Ubuntu. Better, still, because Pengwin is a very... | 9 | 5 |
61,917,521 | 2020-5-20 | https://stackoverflow.com/questions/61917521/computing-ab%e2%81%bb%c2%b9-with-np-linalg-solve | I need to compute AB⁻¹ in Python / Numpy for two matrices A and B (B being square, of course). I know that np.linalg.inv() would allow me to compute B⁻¹, which I can then multiply with A. I also know that B⁻¹A is actually better computed with np.linalg.solve(). Inspired by that, I decided to rewrite AB⁻¹ in terms of np... | In general, np.linalg.solve(B, A) is equivalent to B-1A. The rest is just math. In all cases, (AB)T = BTAT: https://math.stackexchange.com/q/1440305/295281. Not necessary for this case, but for invertible matrices, (AB)-1 = B-1A-1: https://math.stackexchange.com/q/688339/295281. For an invertible matrix, it is also the... | 7 | 8 |
61,916,096 | 2020-5-20 | https://stackoverflow.com/questions/61916096/word-cloud-built-out-of-tf-idf-vectorizer-function | I have a list called corpus that I am attempting TF-IDF on, using the sklearn in-built function. The list has 5 items. Each of these items comes from text files. I have generated a toy list called corpus for this example. corpus = ['Hi what are you accepting here do you accept me', 'What are you thinking about getting... | You're almost there. You need to transpose to get the frequencies per term rather than term frequencies per document, then sum hem, then pass that series directly to your wordcloud df.T.sum(axis=1) accept 0.577350 accepted 0.577350 accepting 0.577350 away 0.707107 far 0.353553 foreign 0.353553 getting 0.577350 hi 0.577... | 7 | 12 |
61,917,043 | 2020-5-20 | https://stackoverflow.com/questions/61917043/python-enum-meta-making-typing-module-crash | I've been breaking my head on this and I can't seem to find a solution to the problem. I use an enum to manage my access in a flask server. Short story I need the enum to return a default value if a non-existent enum value is queried. First I created a meta class for the enum: class AuthAccessMeta(enum.EnumMeta): def _... | Returning a default value can be done with the right version of enum. The problem you are having now, I suspect, is because in your except branch you do not return a value, nor raise an exception, if the if fails -- so None is returned instead. class AuthAccessMeta(enum.EnumMeta): def __getattr__(self, item): try: retu... | 8 | 8 |
61,913,010 | 2020-5-20 | https://stackoverflow.com/questions/61913010/can-not-import-pipeline-from-transformers | I have installed pytorch with conda and transformers with pip. I can import transformers without a problem but when I try to import pipeline from transformers I get an exception: from transformers import pipeline --------------------------------------------------------------------------- ImportError Traceback (most rec... | Check transformers version. Make sure you are on latest. Pipelines were introduced quite recently, you may have older version. | 10 | 8 |
61,909,732 | 2020-5-20 | https://stackoverflow.com/questions/61909732/how-to-catch-concurrent-futures-base-timeouterror-correctly-when-using-asyncio | First of all, i need to warn you: I'm new to asyncio, and i h I warn you right away, I'm new to asyncio, and I can hardly imagine what is in the library under the hood. Here is my code: import asyncio semaphore = asyncio.Semaphore(50) async def work(value): async with semaphore: print(value) await asyncio.sleep(10) asy... | You need to handle the exception. If you just pass it to gather, it will re-raise it. For example, you can create a new coroutine with the appropriate try/except: semaphore = asyncio.Semaphore(50) async def work(value): print(value) await asyncio.sleep(10) async def work_with_timeout(value): async with semaphore: try: ... | 8 | 6 |
61,908,021 | 2020-5-20 | https://stackoverflow.com/questions/61908021/how-to-get-n-easily-distinguishable-colors-with-matplotlib | I need to make different amounts of line plots with Matplotlib, but I have not been able to find a colormap that makes it easy to distinguish between the line plots. I have used the brg colormap like this: colors=brg(np.linspace(0,1,num_plots)) with for i in range(num_plots): ax.step(x,y,c=colors[i]) With four plots,... | I would use the tab10 or tab20 colormaps. See Colormap reference However, I believe you will always have trouble distinguishing hues when the number of lines becomes large (I would say >5 and certainly >10). In this case, you should combine hues with other distinguishing features like different markers or linestyles. ... | 8 | 7 |
61,908,745 | 2020-5-20 | https://stackoverflow.com/questions/61908745/error-astype-got-an-unexpected-keyword-argument-categories | df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'], index=['excellent', 'excellent', 'excellent', 'good', 'good', 'good', 'ok', 'ok', 'ok', 'poor', 'poor']) df.rename(columns={0: 'Grades'}, inplace=True) df I am trying to create an ordered category from the above dataframe using the foll... | From pandas 0.25+ are removed these arguments: Removed the previously deprecated ordered and categories keyword arguments in astype (GH17742) In newer pandas versions is necesary use CategoricalDtype and pass to astype: from pandas.api.types import CategoricalDtype cats = ['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+'... | 9 | 16 |
61,815,883 | 2020-5-15 | https://stackoverflow.com/questions/61815883/how-to-export-pptx-to-image-png-jpeg-in-python | I have developed a small code in Python to generate a PPTX file. But I would like also to generate a picture in PNG or JPEG of the slide. from pptx import Presentation from pptx.util import Inches img_path = 'monty-truth.png' prs = Presentation() blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(bl... | On Windows once you have installed pywin32 pip install pywin32 You can then use the following code : import win32com.client Application = win32com.client.Dispatch("PowerPoint.Application") Presentation = Application.Presentations.Open(r"your_path") Presentation.Slides[0].Export(r"the_new_path-file.jpg", "JPG") Applicat... | 7 | 6 |
61,865,481 | 2020-5-18 | https://stackoverflow.com/questions/61865481/is-there-an-idiomatic-way-to-install-systemd-units-with-setuptools | I'm distributing a module which can be imported and used as a library. It also comes with an executable—installed via console_scripts—for people to use. That executable can also be started as a systemd service (Type=simple) to provide a daemon to the system. systemd services need to refer to absolute paths in their Exe... | I would say don't use setuptools for this, it's not what it's made for. Instead use the package manager for the target distribution (apt, yum, dnf, pacman, etc.). I believe systemd and such things that are specific to the operating system (Linux distribution, Linux init system) are out of scope for Python packaging, pi... | 10 | 8 |
61,881,175 | 2020-5-19 | https://stackoverflow.com/questions/61881175/normed-histogram-y-axis-larger-than-1 | Sometimes when I create a histogram, using say seaborn's displot function, with norm_hist = True, the y-axis is less than 1 as expected for a PDF. Other times it takes on values greater than one. For example if I run sns.set(); x = np.random.randn(10000) ax = sns.distplot(x) Then the y-axis on the histogram goes from ... | The rule isn't that all the bars should sum to one. The rule is that all the areas of all the bars should sum to one. When the bars are very narrow, their sum can be quite large although their areas sum to one. The height of a bar times its width is the probability that a value would all in that range. To have the heig... | 7 | 21 |
61,852,402 | 2020-5-17 | https://stackoverflow.com/questions/61852402/how-can-i-plot-a-simple-plot-with-seaborn-from-a-python-dictionary | I have a dictionary like this: my_dict = {'Southampton': '33.7%', 'Cherbourg': '55.36%', 'Queenstown': '38.96%'} How can I have a simple plot with 3 bars showing the values of each key in a dictionary? I've tried: sns.barplot(x=my_dict.keys(), y = int(my_dict.values())) But I get : TypeError: int() argument must be ... | There are several issues in your code: You are trying to convert each value (eg "xx.xx%") into a number. my_dict.values() returns all values as a dict_values object. int(my_dict.values())) means converting the set of all values to a single integer, not converting each of the values to an integer. The former, naturally... | 10 | 16 |
61,787,127 | 2020-5-14 | https://stackoverflow.com/questions/61787127/how-to-not-print-the-index-url-in-generated-requirements-txt-when-using-piptools | I am using piptools to compile requirements.in to generate requirements.txt. I also have some index url written in my .pip/pip.conf file which I store my credentials to our python artifactory repo. So whenever I do pip-compile requirements.in the generated requirements.txt will contain a line reflecting that index url ... | add the --no-emit-index-url flag to the pip-compile command, or --no-index for pre-5.2.0 versions. EDIT: Official docs for this flag are here. | 9 | 10 |
61,883,438 | 2020-5-19 | https://stackoverflow.com/questions/61883438/is-there-a-way-to-programmatically-confirm-that-a-python-package-version-satisfi | I am trying to find whether there is a way to take an installed package and version and check whether it satisfies a requirements spec. For example, if I have the package pip==20.0.2, I want the program to do the following: CheckReqSpec("pip==20.0.2", "pip>=19.0.0") -> True CheckReqSpec("pip==20.0.2", "pip<=20.1") -> T... | Using pkg_resources (from setuptools) as an API is now deprecated, and will cause warnings at import time: $ python3 -W always -c 'from pkg_resources import Requirement' <string>:1: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html Instead, we can pa... | 11 | 10 |
61,859,356 | 2020-5-17 | https://stackoverflow.com/questions/61859356/how-to-click-the-ok-button-within-an-alert-using-python-selenium | I want to click the "OK" button in this pop up dialog I tried: driver.switchTo().alert().accept(); but it doesn't work | To click on the OK button within the alert you need to induce WebDriverWait for the desired alert_is_present() and you can use the following solution: WebDriverWait(driver, 10).until(EC.alert_is_present()) driver.switch_to.alert.accept() Note : You have to add the following imports : from selenium.webdriver.common.ale... | 7 | 16 |
61,814,614 | 2020-5-15 | https://stackoverflow.com/questions/61814614/unknown-layer-keraslayer-when-i-try-to-load-model | When i try to save my model as hdf5 path = 'path.h5' model.save(path) then load the model again my_reloaded_model = tf.keras.models.load_model(path) I get the following error ValueError: Unknown layer: KerasLayer Any help ? I'm using tensorflow version: 2.2.0 keras version: 2.3.0-tf | I just found a solution that worked for me my_reloaded_model = tf.keras.models.load_model( (path), custom_objects={'KerasLayer':hub.KerasLayer} ) | 18 | 42 |
61,859,098 | 2020-5-17 | https://stackoverflow.com/questions/61859098/maximum-volume-inscribed-ellipsoid-in-a-polytope-set-of-points | Later Edit: I uploaded here a sample of my original data. It's actually a segmentation image in the DICOM format. The volume of this structure as it is it's ~ 16 mL, so I assume the inner ellipsoid volume should be smaller than that. to extract the points from the DICOM image I used the following code: import os import... | Problem statement Given a number of points v₁, v₂, ..., vₙ, find a large ellipsoid satisfying two constraints: The ellipsoid is in the convex hull ℋ = ConvexHull(v₁, v₂, ..., vₙ). None of the points v₁, v₂, ..., vₙ is within the ellipsoid. I propose an iterative procedure to find a large ellipsoid satisfying these tw... | 12 | 9 |
61,827,165 | 2020-5-15 | https://stackoverflow.com/questions/61827165/plotly-how-to-handle-overlapping-colorbar-and-legends | I have a simple graph and I am using Plotly Express Library to draw it. The image is as follows which have two legends overlapping 'Rank' and 'Genre'. px.scatter_ternary(data_frame = data, a='Length.', b='Beats.Per.Minute', c='Popularity', color = 'Rank', symbol = 'Genre', labels = {'Length.': 'Len', 'Beats.Per.Minute... | Short answer: You can move the colorbar with: fig.update_layout(coloraxis_colorbar=dict(yanchor="top", y=1, x=0, ticks="outside")) The details: Since you haven't provided a fully executable code snippet with a sample of your data, I'm going to have to base a suggestion on a dataset and an example that's at least able... | 11 | 15 |
61,783,925 | 2020-5-13 | https://stackoverflow.com/questions/61783925/running-a-package-pytest-with-poetry | I am new to poetry and want to get it set-up with pytest. I have a package mylib in the following set-up ├── dist │ ├── mylib-0.0.1-py3-none-any.whl │ └── mylib-0.0.1.tar.gz ├── poetry.lock ├── mylib │ ├── functions.py │ ├── __init__.py │ └── utils.py ├── pyproject.toml ├── README.md └── tests └── test_functions.py in... | You need to run poetry install to set up your dev environment. It will install all package and development requirements, and once that is done it will do a dev-install of your source code. You only need to run it once, code changes will propagate directly and do not require running the install again. If you have set u... | 41 | 25 |
61,860,800 | 2020-5-18 | https://stackoverflow.com/questions/61860800/running-a-processpoolexecutor-in-ipython | I was running a simple multiprocessing example in my IPython interpreter (IPython 7.9.0, Python 3.8.0) on my MacBook and ran into a strange error. Here's what I typed: [In [1]: from concurrent.futures import ProcessPoolExecutor [In [2]: executor=ProcessPoolExecutor(max_workers=1) [In [3]: def func(): print('Hello') [In... | TLDR; import multiprocessing as mp from concurrent.futures import ProcessPoolExecutor # create child processes using 'fork' context executor = ProcessPoolExecutor(max_workers=1, mp_context=mp.get_context('fork')) This is in-fact caused by python 3.8 on MacOS switching to "spawn" method for creating a child process; a... | 10 | 18 |
61,891,181 | 2020-5-19 | https://stackoverflow.com/questions/61891181/how-to-use-multiple-inputs-in-tensorflow-2-x-keras-custom-layer | I'm trying to use multiple inputs in custom layers in Tensorflow-Keras. Usage can be anything, right now it is defined as multiplying the mask with the image. I've search SO and the only answer I could find was for TF 1.x so it didn't do any good. class mul(layers.Layer): def __init__(self, **kwargs): super().__init__(... | EDIT: Since TensorFlow v2.3/2.4, the contract is to use a list of inputs to the call method. For keras (not tf.keras) I think the answer below still applies. Implementing multiple inputs is done in the call method of your class, there are two alternatives: List input, here the inputs parameter is expected to be a list... | 12 | 15 |
61,888,521 | 2020-5-19 | https://stackoverflow.com/questions/61888521/python-sphinx-warning-definition-list-ends-without-a-blank-line-unexpected-uni | My doc is like this: def segments(self, start_time=1, end_time=9223372036854775806, offset=0, size=20): """Get segments of the model :parameter offset: - optional int size: - optional int start_time: - optional string,Segments end_time: - optional string,Segments :return: Segments Object """ When I make html, it turn... | The Question was already answered by jonrsharpe in a comment, but i want to complete it here. You are using the default Sphinx Style "reStructuredText" You have to add ":parameter" on every line: """Get segments of the model :parameter offset: optional int :parameter size: optional int :parameter start_time: optional ... | 17 | 8 |
61,852,225 | 2020-5-17 | https://stackoverflow.com/questions/61852225/align-button-to-the-center-of-the-window-using-pysimplegui | In my application am trying to place my button,text and input at the center of the window.I am using PySimpleGUI for designing buttons.For aligning to the center i used justification='center' attribute on my code.But still it is not fitting to the center of the window. The code am working with is import PySimpleGUI as ... | this code make the text, button and input to the center of the window. import PySimpleGUI as sg sg.theme('DarkAmber') layout = [ [sg.Text('Enter the value',justification='center',size=(100,1))], [sg.Input(justification='center',size=(100,1))], [sg.Button('Enter','center',size=(100,1))] ] window = sg.Window('My new wind... | 14 | 3 |
61,870,688 | 2020-5-18 | https://stackoverflow.com/questions/61870688/cant-run-idle-with-pyenv-installation-python-may-not-be-configured-for-tk-m | I recently spent couple hours making tkinter and IDLE work on my pyenv Python installation (macOS). Why you are here? You manage Python versions with pyenv on macOS and ( You want IDLE - the development environment for Python - work on your macOS or you want tkinter module work ) What's wrong? You get one of the foll... | Here is step by step guide to make IDLE and tkinter work: install tcl-tk with Homebrew. In shell run brew install tcl-tk in shell run echo 'export PATH="/usr/local/opt/tcl-tk/bin:$PATH"' >> ~/.zshrc reload shell by quitting Terminal app or run source ~/.zshrc after reloaded check that tck-tk is in $PATH. Run echo $PAT... | 13 | 19 |
61,791,651 | 2020-5-14 | https://stackoverflow.com/questions/61791651/how-to-run-python-3-function-even-after-user-has-closed-web-browser-tab | I am having an issue at work with a python project I am working on (I normally use PHP/Java so am lacking a bit of knowledge). Bascially I have a python program that I have built using Flask that connects an inventory management system to Shopify using the Shopify Python API. When the user triggers a function via an AJ... | You need to handle this task asynchronously because it's a long-running job that would dramatically reduce the performance of an HTTP response (if you wait untill it finishes). Also, you may notice that you need to run this task in a separate process of the current process that serves your HTTP request. Because, web se... | 8 | 7 |
61,890,687 | 2020-5-19 | https://stackoverflow.com/questions/61890687/dash-app-refusing-to-start-127-0-0-1-refused-to-connect | I am trying to run the example dash application but upon trying to run, the browser says it is refusing to connect. I have checked and Google Chrome has access through the firewall. The example code is: import dash import dash_core_components as dcc import dash_html_components as html external_stylesheets = ['https://... | First check if you are accessing the right port, the default one (usually) is 8050: http://localhost:8050/ Also, check if there is another Dash code running, it might be occupying the port. If it does not work, try determining the host as an argument in app.runserver(args), like this: app.run_server(host='0.0.0.0', deb... | 13 | 11 |
61,895,282 | 2020-5-19 | https://stackoverflow.com/questions/61895282/plotly-how-to-remove-empty-dates-from-x-axis | I have a Dataframe Date Category Sum 0 2019-06-03 "25M" 34 1 2019-06-03 "25M" 60 2 2019-06-03 "50M" 23 3 2019-06-04 "25M" 67 4 2019-06-05 "50M" -90 5 2019-06-05 "50M" 100 6 2019-06-06 "100M" 6 7 2019-06-07 "25M" -100 8 2019-06-08 "100M" 67 9 2019-06-09 "25M" 450 10 2019-06-10 "50M" 600 11 2019-06-11 "25M" -9 12 2019-0... | I had the same problem with my graph. Just add the following to layout code: xaxis=dict(type = "category") Note: I have used import plotly.graph_objs as go and NOT import plotly.express as px This worked for me. Hope it helps you too. | 12 | 19 |
61,802,080 | 2020-5-14 | https://stackoverflow.com/questions/61802080/excelwriter-valueerror-excel-does-not-support-datetime-with-timezone-when-savin | I'm running on this issue for quite a while now. I set the writer as follows: writer = pd.ExcelWriter(arquivo+'.xlsx', engine = 'xlsxwriter', options = {'remove_timezone': True}) df.to_excel(writer, header = True, index = True) This code is inside s function. The problem is every time I run the code, it gets informati... | What format is your timestamps in? I just had a similar problem. I was trying to save a data frame to Excel. However I was getting: I checked my date format which was in this format '2019-09-01T00:00:00.000Z' This is a timestamp pandas._libs.tslibs.timestamps.Timestamp from pandas.to_datetime which includes a method d... | 39 | 23 |
61,819,842 | 2020-5-15 | https://stackoverflow.com/questions/61819842/how-can-i-login-in-instagram-with-python-requests | Hello i am trying to login instagram with python requests library but when i try, instagram turns me "bad requests". İs anyone know how can i solve this problem? i searched to find a solve for this problem but i didnt find anything. Please help, thanks! it was working but after some time, it started to turn "bad reques... | link = 'https://www.instagram.com/accounts/login/' login_url = 'https://www.instagram.com/accounts/login/ajax/' time = int(datetime.now().timestamp()) response = requests.get(link) csrf = response.cookies['csrftoken'] payload = { 'username': username, 'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{time}:{password}', 'quer... | 8 | 12 |
61,867,945 | 2020-5-18 | https://stackoverflow.com/questions/61867945/python-import-error-cannot-import-name-six-from-sklearn-externals | I'm using numpy and mlrose, and all i have written so far is: import numpy as np import mlrose However, when i run it, it comes up with an error message: File "C:\Users\<my username>\AppData\Local\Programs\Python\Python38-32\lib\site-packages\mlrose\neural.py", line 12, in <module> from sklearn.externals import six I... | Solution: The real answer is that the dependency needs to be changed by the mlrose maintainers. A workaround is: import six import sys sys.modules['sklearn.externals.six'] = six import mlrose | 26 | 76 |
61,875,869 | 2020-5-18 | https://stackoverflow.com/questions/61875869/ubuntu-20-04-upgrade-python-missing-libffi-so-6 | I recently upgraded my OS to Ubuntu 20.04 LTS. Now when I try to import a library like Numpy in Python, I get the following error: ImportError: libffi.so.6: cannot open shared object file: No such file or directory I tried installing the libffi package, but apt can't locate it: sudo apt-get install libffi Reading pac... | It seems like I fixed it. I could be wrong, but here is what I think happened: Ubuntu 20.04 upgraded libffi6 to libffi7 Python is still looking for libffi6 What I did to fix it : Locate libffi.so.7 in your system $ find /usr/lib -name "libffi.so*" Create a simlink named libffi.so.6 that points to libffi.so.7: sudo l... | 119 | 113 |
61,863,806 | 2020-5-18 | https://stackoverflow.com/questions/61863806/stuck-in-watching-for-file-changes-with-statreloader | I made my project fine and when I run my server through a normal shell, it works. Now, I am trying to run my project through Git Bash. All the commands seem to work fine but when I do python manage.py runserver, it gets stuck on Watching for file changes with StatReloader Apparently after that I go to localhost:8000 b... | You may be missing the port binding, try to run python manage.py runserver 0.0.0.0:8000 to be sure that the app is running on localhost:8000 | 14 | 5 |
61,778,794 | 2020-5-13 | https://stackoverflow.com/questions/61778794/python-ctypes-how-to-check-memory-management | So I'm using Python as a front end GUI that interacts with some C files for storage and memory management as a backend. Whenever the GUI's window is closed or exited, I call all the destructor methods for my allocated variables. Is there anyway to check memory leaks or availability, like a C Valgrind check, right befor... | If you want to use Valgrind, then this readme might be helpful. Probably, this could be another good resource to make Valgrind friendly python and use it in your program. But if you consider something else like tracemalloc, then you can easily get some example usage of it here. The examples are pretty easy to interpret... | 9 | 4 |
61,850,321 | 2020-5-17 | https://stackoverflow.com/questions/61850321/django-channels-vs-django-3-0-3-1 | Can someone clarify the differences or complementarities between Django Channels Project and new Django native async support? From what I understood, Django-Channels is a project that have been started outside of Django, and then, started to be integrated in the core Django. But the current state of this work remains c... | today I'm using Django 2.2, and I'd like to add WebSocket support to my project. If you want to add websocket support to your app, at the moment you don't need to upgrade to django 3.0. Django 2.2 plus channels can do that - and for the time being is the best way forward. (Although there's absolutely no harm in upgra... | 18 | 30 |
61,822,379 | 2020-5-15 | https://stackoverflow.com/questions/61822379/with-django-csrf-exempt-request-session-is-always-empty | I am stuck in django and would really appreciate it if someone could help me. I need to have an entry point for a 3rd party API. So I created a view and decorated it with @csrf_exempt Now the problem is I am not able to access any session variables I set before. edit - I set multiple session variables like user email t... | I solved it using Django itself. No manipulation of session-id or interaction with the database. Step1: call 3rd party api @login_required def thirdPartyAPICall(request): #do some stuff and send a request to 3rd party Step2: receive a call-back from 3rd party in the view. Note how I put csrf_exempt and not login_requ... | 9 | 0 |
61,890,366 | 2020-5-19 | https://stackoverflow.com/questions/61890366/flask-session-log-out-and-redirect-to-login-page | I am using Flask,Python for my web application . The user will login and if the session time is more than 5 minutes then the app should come out and it should land on the login page. I tried some of the methods and I can see the session time out is happening but redirect to login page is not happening. @app.before_requ... | When I read the documents of the Flask-Login package, i saw a few things. When creating your Flask application, you also need to create a login manager. login_manager = LoginManager() A login_view variable in LoginManager class caught my attention. The details include the following explanation: The name of the view ... | 7 | 9 |
61,840,060 | 2020-5-16 | https://stackoverflow.com/questions/61840060/how-to-detect-subscript-numbers-in-an-image-using-ocr | I am using tesseract for OCR, via the pytesseract bindings. Unfortunately, I encounter difficulties when trying to extract text including subscript-style numbers - the subscript number is interpreted as a letter instead. For example, in the basic image: I want to extract the text as "CH3", i.e. I am not concerned abou... | You want to do apply pre-processing to your image before feeding it into tesseract to increase the accuracy of the OCR. I use a combination of PIL and cv2 to do this here because cv2 has good filters for blur/noise removal (dilation, erosion, threshold) and PIL makes it easy to enhance the contrast (distinguish the tex... | 11 | 4 |
61,863,309 | 2020-5-18 | https://stackoverflow.com/questions/61863309/package-requires-a-different-python-2-7-17-not-in-3-6-1-while-setting-up-pr | I cloned a repository, installed pre-commit and was committing for the first time. This is the time when pre-commit packages actually get installed and setup. I faced the following issue. [INFO] Installing environment for https://github.com/asottile/seed-isort-config. [INFO] Once installed this environment will be reu... | The issue was that I have both Python2.7 and 3 installed. And my pre-commit was installed was using Python 2.7 as the default. Solution 1: remove pre-commit from Python2.7 and add it to Python3. As per the creator of pre-commit - @anthony-sottile - it is better to use pre-commit with Python3. To do that we will have ... | 8 | 9 |
61,880,977 | 2020-5-19 | https://stackoverflow.com/questions/61880977/how-to-create-a-color-bar-in-an-osmnx-plot | Currently I have created a color map based on the distance of the nodes in the network to a specific target. The one thing I am not being able to do is a color bar. I would like the color bar to show me how much time the color indicates. The time data is in data['time']. Each color will indicate how long it will take t... | again. I had faced this same issue earlier without having enough motivation to solve it. But somehow I have managed to do it this time (and your trial has helped a lot as well, given that my coding knowledge is limited to say the least). See that I have changed the normalised values so that it means something on the f... | 11 | 10 |
61,842,649 | 2020-5-16 | https://stackoverflow.com/questions/61842649/renaming-months-from-number-to-name-in-pandas | i have the following dataframe: High Low Open Close Volume Adj Close year pct_day month day 1 1 NaN NaN NaN NaN NaN NaN 2010.0 0.000000 2 7869.853149 7718.482498 7779.655014 7818.089966 7.471689e+07 7818.089966 2010.0 0.007826 3 7839.965652 7719.758224 7775.396255 7777.940002 8.185879e+07 7777.940002 2010.0 0.002582 4 ... | I would do it using calendar and pd.CategoricalDtype to ensure sorting works correctly. import pandas as pd import numpy as np import calendar #Create dummy dataframe dateindx = pd.date_range('2019-01-01', '2019-12-31', freq='D') df = pd.DataFrame(np.random.randint(0,1000, (len(dateindx), 5)), index=pd.MultiIndex.from_... | 7 | 6 |
61,899,474 | 2020-5-19 | https://stackoverflow.com/questions/61899474/polynomial-regression-using-statsmodels-formula-api | Please forgive my ignorance. All I'm trying to do is add a squared term to my regression without going through the trouble of defining a new column in my dataframe. I'm using statsmodels.formula.api (as stats) because the format is similar to R, which I am more familiar with. hours_model = stats.ols(formula='act_hours... | You can try using I() like in R: import statsmodels.formula.api as smf np.random.seed(0) df = pd.DataFrame({'act_hours':np.random.uniform(1,4,100),'h_hours':np.random.uniform(1,4,100), 'month':np.random.randint(0,3,100),'trend':np.random.uniform(0,2,100)}) model = 'act_hours ~ h_hours + I(h_hours**2)' hours_model = smf... | 8 | 27 |
61,794,582 | 2020-5-14 | https://stackoverflow.com/questions/61794582/plotly-how-to-only-show-vertical-and-horizontal-line-crosshair-as-hoverinfo | I want to plot a chart with two subplots in plotly dash. My entire chart looks like this: import pandas as pd import numpy as np import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go from plotly.subplots import make_subplots df = pd.read_csv('https://raw.githu... | This should do it: fig.update_layout(hoverdistance=0) And setting spikesnap='cursor' for xaxes and yaxes. These little adjustments will keep the crosshair intact and remove the little icon that has been bothering you. From the docs: Plot: hoverdistance Sets the default distance (in pixels) to look for data to add ... | 19 | 21 |
61,902,426 | 2020-5-19 | https://stackoverflow.com/questions/61902426/cased-vs-uncased-bert-models-in-spacy-and-train-data | I want to use spacy's pretrained BERT model for text classification but I'm a little confused about cased/uncased models. I read somewhere that cased models should only be used when there is a chance that letter casing will be helpful for the task. In my specific case: I am working with German texts. And in German all ... | As a non-German-speaker, your comment about nouns being uppercase does make it seem like case is more relevant for German than it might be for English, but that doesn't obviously mean that a cased model will give better performance on all tasks. For something like part-of-speech detection, case would probably be enormo... | 25 | 21 |
61,900,138 | 2020-5-19 | https://stackoverflow.com/questions/61900138/pytorch-caught-indexerror-in-dataloader-worker-process-0-indexerror-too-man | I am trying to implement a detection model based on "finetuning object detection" official tutorial of PyTorch. It seemed to have worked with minimal data, (for 10 of images). However I uploaded my whole dataset to Drive and checked the index-data-label correspondences. There are not unmatching items in my setup, I hav... | When using np.loadtxt() method, make sure to add ndims = 2 as a parameter. Because the number of objects parameter num_obj becomes 10 even if it has only 1 object in it. It is because 1 object becomes a column vector which shows up as 10 objects. (representing 10 columns) ndims = 2, makes sure that the output of np.lo... | 7 | 1 |
61,890,674 | 2020-5-19 | https://stackoverflow.com/questions/61890674/run-python-script-in-jenkins | I want to run a python script from Jenkins using Jenkinsfile. Is there any way to run it directly from Jenkinsfile. I found python plugin(Click Here) in Jenkins to run a script, but there is no proper documentation for this plugin. It would be very helpful if anyone explains how to integrate this plugin with Jenkinsfi... | Adds the ability to execute python scripts as build steps. Other than that, this plugin works pretty much like the standard shell script support Per the docs of the plugin. Though I have not used this plugin through pipeline, from job perspective, you have to just provide .py script (filename and path), in a same way... | 12 | 16 |
61,888,674 | 2020-5-19 | https://stackoverflow.com/questions/61888674/can-you-plot-interquartile-range-as-the-error-band-on-a-seaborn-lineplot | I'm plotting time series data using seaborn lineplot (https://seaborn.pydata.org/generated/seaborn.lineplot.html), and plotting the median instead of mean. Example code: import seaborn as sns; sns.set() import matplotlib.pyplot as plt fmri = sns.load_dataset("fmri") ax = sns.lineplot(x="timepoint", y="signal", estimato... | I don't know if this can be done with seaborn alone, but here's one way to do it with matplotlib, keeping the seaborn style. The describe() method conveniently provides summary statistics for a DataFrame, among them the quartiles, which we can use to plot the medians with inter-quartile-ranges. import seaborn as sns; s... | 8 | 13 |
61,787,520 | 2020-5-14 | https://stackoverflow.com/questions/61787520/i-want-to-make-a-multi-page-help-command-using-discord-py | I am using discord.py to make a bot, and there are more commands than can fit on one page for my custom help command. I want the bot to add 2 reactions, back and forward, then the user that sent the help message can pick one, and go onto different pages of the help command. I want the bot to be able to edit the message... | This method would be using Client.wait_For(), and can be easily adapted if you have any other ideas for it. Example @bot.command() async def pages(ctx): contents = ["This is page 1!", "This is page 2!", "This is page 3!", "This is page 4!"] pages = 4 cur_page = 1 message = await ctx.send(f"Page {cur_page}/{pages}:\n{co... | 7 | 24 |
61,861,739 | 2020-5-18 | https://stackoverflow.com/questions/61861739/plotly-how-to-set-custom-xticks | From plotly doc: layout > xaxis > tickvals: Sets the values at which ticks on this axis appear. Only has an effect if tickmode is set to "array". Used with ticktext. layout > xaxis > ticktext: Sets the text displayed at the ticks position via tickvals. Only has an effect if tickmode is set to "array". Used with tickva... | I normally use the approach below. You should know that tickvals is to be regarded as a positional argument and works best (perhaps only) with numerical values and not dates. Use ticktext to display the dates in your preferred format. Snippet 1: fig.update_xaxes(tickangle=45, tickmode = 'array', tickvals = df_tips['dat... | 12 | 22 |
61,878,019 | 2020-5-18 | https://stackoverflow.com/questions/61878019/install-optional-dependencies-with-tox | I use tox to test a python project with the following basic config (tox.ini): [tox] envlist = py3 isolated_build = True [testenv] deps = pytest pytest-cov commands = pytest --cov {envsitepackagesdir}/foobar --cov-report xml --cov-report term Unfortunately, the package's optional dependencies (as specified in setup.cfg... | The supported way to do this is to use the extras key in your testenv for example: [testenv] deps = -rrequirements-dev.txt extras = typed this will install .[typed] or -e .[typed] if usedevelop = true disclaimer: I'm one of the tox maintainers | 9 | 14 |
61,872,923 | 2020-5-18 | https://stackoverflow.com/questions/61872923/supporting-both-form-and-json-encoded-bodys-with-fastapi | I've been using FastAPI to create an HTTP based API. It currently supports JSON encoded parameters, but I'd also like to support form-urlencoded (and ideally even form-data) parameters at the same URL. Following on Nikita's answer I can get separate urls working with: from typing import Optional from fastapi import Fas... | FastAPI can't route based on Content Type, you'd have to check that in the request and parse appropriately: @app.post('/') async def route(req: Request) -> Response: if req.headers['Content-Type'] == 'application/json': item = MyItem(** await req.json()) elif req.headers['Content-Type'] == 'multipart/form-data': item =... | 10 | 14 |
61,878,026 | 2020-5-18 | https://stackoverflow.com/questions/61878026/eigenvectors-are-complex-but-only-for-large-matrices | I'm trying to calculate the eigenvectors and eigenvalues of this matrix import numpy as np la = 0.02 mi = 0.08 n = 500 d1 = np.full(n, -(la+mi), np.double) d1[0] = -la d1[-1] = -mi d2 = np.full(n-1, la, np.double) d3 = np.full(n-1, mi, np.double) A = np.diagflat(d1) + np.diagflat(d2, -1) + np.diag(d3, 1) e_values, e_v... | What you are seeing appears to be fairly normal roundoff error. This is an unfortunate result of storing floating point numbers with a finite precision. It naturally gets relatively worse for large problems. Here is a plot of the real vs. imaginary components of the eigenvalues: You can see that the imaginary numbers ... | 7 | 7 |
61,879,166 | 2020-5-18 | https://stackoverflow.com/questions/61879166/pandas-groupby-month-and-year-date-as-datetime64ns-and-summarized-by-count | I have a data frame, which I created in pandas, grouping by date and summarizing by rides. date rides 0 2019-01-01 247279 1 2019-01-02 585996 2 2019-01-03 660631 3 2019-01-04 662011 4 2019-01-05 440848 .. ... ... 451 2020-03-27 218499 452 2020-03-28 143305 453 2020-03-29 110833 454 2020-03-30 207743 455 2020-03-31 19... | you can groupby and get the dt.year and the dt.month_name from the column date. print (df.groupby([df['date'].dt.year.rename('year'), df['date'].dt.month_name().rename('month')]) ['rides'].sum().reset_index()) year month rides 0 2019 January 2596765 1 2020 March 880003 | 7 | 11 |
61,875,963 | 2020-5-18 | https://stackoverflow.com/questions/61875963/pytorch-row-wise-dot-product | Suppose I have two tensors: a = torch.randn(10, 1000, 1, 4) b = torch.randn(10, 1000, 6, 4) Where the third index is the index of a vector. I want to take the dot product between each vector in b with respect to the vector in a. To illustrate, this is what I mean: dots = torch.Tensor(10, 1000, 6, 1) for b in range(10)... | a = torch.randn(10, 1000, 1, 4) b = torch.randn(10, 1000, 6, 4) c = torch.sum(a * b, dim=-1) print(c.shape) torch.Size([10, 1000, 6]) c = c.unsqueeze(-1) print(c.shape) torch.Size([10, 1000, 6, 1]) | 8 | 13 |
61,842,432 | 2020-5-16 | https://stackoverflow.com/questions/61842432/pyqt5-and-asyncio | Is it possible to keep a UDP server running as an asynchronous function receiving data and then passing it to an (PyQt5) widget which is also running as an asynchronous function?? The idea is that when the data coming into the server is updated, it also updates the widget. I have got a simple UDP server and a (PyQt5) w... | It should be clear that your UDP server does not run asynchronously. The logic of asyncio is that everything uses an eventloop as a base, and by default Qt does not support it, so you must use libraries such as qasync(python -m pip install qasync) and asyncqt(python -m pip install asyncqt) Considering the above, the so... | 9 | 7 |
61,855,161 | 2020-5-17 | https://stackoverflow.com/questions/61855161/any-workaround-to-add-token-authorization-decorator-to-endpoint-at-swagger-pytho | I know how to secure endpoint in flask, and I want to do the same thing to swagger generated python server stub. I am wondering how I can integrate flask token authentication works for the swagger python server, so the endpoint will be secured. I could easily add token authentication decorator to endpoint in flask. Thi... | Update Here is a example yaml to use JWT as bearer format: https://github.com/zalando/connexion/blob/master/examples/openapi3/jwt/openapi.yaml After you generate the flask server, on the swagger-ui you can find the 'Authorize' button. And if you execute /secret before 'Authorize' you will get a 401 error. So for your s... | 8 | 2 |
61,865,793 | 2020-5-18 | https://stackoverflow.com/questions/61865793/python-typeerror-invalid-comparison-between-dtype-datetime64ns-and-date | For a current project, I am planning to filter a JSON file by timeranges by running several loops, each time with a slightly shifted range. The code below however yields the error TypeError: Invalid comparison between dtype=datetime64[ns] and date for line after_start_date = df["Date"] >= start_date. I have already tri... | You can use pd.to_datetime('2017-01-31') instead of datetime.date.fromisoformat('2017-01-31'). I hope this helps! | 13 | 14 |
61,861,172 | 2020-5-18 | https://stackoverflow.com/questions/61861172/what-does-the-argument-newline-do-in-the-open-function | I was learning Python in Codecademy and they were talking about using the open() function for CSV files. I couldn't really understand what the argument newline='' meant for the code. import csv with open('addresses.csv', newline='') as addresses_csv: address_reader = csv.DictReader(addresses_csv, delimiter=';') for row... | In your csv.DictReader function, you are iterating over lines in addresses.csv and mapping each row to a dict. Check the quoted fields in the csv file, and see if there are any escape sequences for ending a line '\r\n' - notice what happens when you include the newline parameter as shown in your code versus when you do... | 20 | 14 |
61,854,891 | 2020-5-17 | https://stackoverflow.com/questions/61854891/tee-function-from-itertools-library | Here is an simple example that gets min, max, and avg values from a list. The two functions below have same result. I want to know the difference between these two functions. And why use itertools.tee()? What advantage does it provide? from statistics import median from itertools import tee purchases = [1, 2, 3, 4, 5] ... | Iterators can only be iterated once in python. After that they are "exhausted" and don't return more values. You can see this in functions like map(), zip(), filter() and many others: purchases = [1, 2, 3, 4, 5] double = map(lambda n: n*2, purchases) print(list(double)) # [2, 4, 6, 8, 10] print(list(double)) # [] <-- c... | 7 | 9 |
61,851,174 | 2020-5-17 | https://stackoverflow.com/questions/61851174/how-to-get-message-by-id-discord-py | I'm wondering how to get a message by its message id. I have tried discord.fetch_message(id) and discord.get_message(id), but both raise: Command raised an exception: AttributeError: module 'discord' has no attribute 'fetch_message'/'get_message' | When getting a message, you're going to need an abc.Messageable object - essentially an object where you can send a message in, for example a text channel, a DM etc. Example: @bot.command() async def getmsg(ctx, msgID: int): # yes, you can do msg: discord.Message # but for the purposes of this, i'm using an int msg = a... | 8 | 12 |
61,819,120 | 2020-5-15 | https://stackoverflow.com/questions/61819120/how-to-get-the-endpoint-of-a-linestring-in-shapely | Linestring1 = LINESTRING (51.2176008 4.4177154, 51.21758 4.4178548, **51.2175729 4.4179023**, *51.21745162000732 4.41871738126533*) Linestring2 = LINESTRING (*51.21745162000732 4.41871738126533*, **51.2174025 4.4190475**, 51.217338 4.4194807, 51.2172511 4.4200562, 51.2172411 4.4201077, 51.2172246 4.4201654, 51.2172067 ... | To get endpoints of a LineString, you just need to access its boundary property: from shapely.geometry import LineString line = LineString([(0, 0), (1, 1), (2, 2)]) endpoints = line.boundary print(endpoints) # MULTIPOINT (0 0, 2 2) first, last = line.boundary print(first, last) # POINT (0 0) POINT (2 2) Alternatively,... | 16 | 34 |
61,833,301 | 2020-5-16 | https://stackoverflow.com/questions/61833301/error-on-tensorflow-cannot-import-name-export-saved-model | I keep getting this error when importing tensorflow as tf with the below error text: ImportError: cannot import name 'export_saved_model' from 'tensorflow.python.keras.saving.saved_model' Code used is simply: import tensorflow as tf I have done: uninstalled and installed tensorflow through pip and condo via anacond... | Uninstalling and install again worked for me. conda activate tf pip uninstall -y tensorflow-gpu pip install tensorflow-gpu However, am still looking for the cause of this error. It was working just a few minutes ago but suddenly I have faced this error. | 10 | 2 |
61,841,672 | 2020-5-16 | https://stackoverflow.com/questions/61841672/no-matching-distribution-found-for-torch-1-5-0cpu-on-heroku | I am trying to deploy my Django app which uses a machine learning model. And the machine learning model requires pytorch to execute. When i am trying to deploy it is giving me this error ERROR: Could not find a version that satisfies the requirement torch==1.5.0+cpu (from -r /tmp/build_4518392d43f43bc52f067241a9661c92/... | PyTorch does not distribute the CPU only versions over PyPI. They are only available through their custom registry. If you select the CPU only version on PyTorch - Get Started Locally you get the following instructions: pip install torch==1.5.0+cpu torchvision==0.6.0+cpu -f https://download.pytorch.org/whl/torch_stable... | 11 | 23 |
61,799,363 | 2020-5-14 | https://stackoverflow.com/questions/61799363/read-tsv-file-in-pyspark | What is the best way to read .tsv file with header in pyspark and store it in a spark data frame. I am trying to use "spark.read.options" and "spark.read.csv" commands however no luck. Thanks. Regards, Jit | Well you can directly read the tsv file without providing external schema if there is header available as: df = spark.read.csv(path, sep=r'\t', header=True).select('col1','col2') Since spark is lazily evaluated it'll read only selected columns. Hope it helps. | 7 | 12 |
61,801,260 | 2020-5-14 | https://stackoverflow.com/questions/61801260/vscode-sort-imports-vs-organize-imports | When I enter option + shift + o on my Mac in a Python file in VSCode, I am given two options - "Sort imports" and "Organize Imports". They both organize the inputs nicely but in a different way, so I can keep flipping back and forth between the two of them. Why are there two different commands for this and is one prefe... | There are two because the Python extension created the Sort Imports command before VS Code introduced the Organize Imports command. So the Sort Imports command is the more "official" one for now. There is an open issue, though, to transition over to Organize Imports at some point. Feel free to 👍 the issue if you would... | 14 | 28 |
61,826,300 | 2020-5-15 | https://stackoverflow.com/questions/61826300/how-to-switch-from-hmset-to-hset-in-redis | I get the deprication warning, that Redis.hmset() is deprecated. Use Redis.hset() instead. However hset() takes a third parameter and I can't figure out what name is supposed to be. info = {'users': 10, "timestamp": datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} r.hmset("myKey", info) The above works, but this requi... | You may execute multiple hset for each field/value pair in hmset. r.hset('myKey', 'users', 10) r.hset('myKey', 'timestamp', datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')) r.hset('myKey', 'yet-another-field', 'yet-another-value') first parameter is the key name second parameter is the field name third parameter is t... | 14 | 1 |
61,816,236 | 2020-5-15 | https://stackoverflow.com/questions/61816236/does-pyspark-code-run-in-jvm-or-python-subprocess | I want to understand what is happening under the hood when I run the following script named t1.py with python3 t1.py. Specifically, I have the following questions: What kind of code is submitted to the spark worker node? Is it the python code or a translated equivalent Java code submitted to the spark worker node? Is ... | In PySpark, Python and JVM codes live in separate OS processes. PySpark uses Py4J, which is a framework that facilitates interoperation between the two languages, to exchange data between the Python and the JVM processes. When you launch a PySpark job, it starts as a Python process, which then spawns a JVM instance and... | 17 | 33 |
61,813,503 | 2020-5-15 | https://stackoverflow.com/questions/61813503/is-there-a-go-equivalent-to-pythons-virtualenv | The question is in the title: Is there a GO equivalent to python's virtualenv? What is the prefered work flow to start a new project? | Go modules, which are built into the tooling since Go 1.12 (or 1.11 with a special flag turned on). Create a directory outside of your GOPATH (i.e. basically anywhere), create a go.mod using go mod init (which gives your module a declared importpath), and start working. There's no need to "activate" an environment like... | 26 | 26 |
61,809,897 | 2020-5-15 | https://stackoverflow.com/questions/61809897/why-does-time-sleep-not-get-affected-by-the-gil | From what I understood when doing research on the Python GIL, is that only one thread can be executed at the once (Whoever holds the lock). However, if that is true, then why would this code only take 3 seconds to execute, rather than 15 seconds? import threading import time def worker(): """thread worker function""" t... | Mario's answer is a good high level answer. If you're interested in some details of how this is implemented: in CPython, the implementation of time.sleep wraps its select system call with Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS: https://github.com/python/cpython/blob/7ba1f75f3f02b4b50ac6d7e17d15e467afa36aac/Modul... | 13 | 14 |
61,767,723 | 2020-5-13 | https://stackoverflow.com/questions/61767723/get-config-missing-while-loading-previously-saved-model-without-custom-layers | I have a problem with loading the previously saved model. This is my save: def build_rnn_lstm_model(tokenizer, layers): model = tf.keras.Sequential([ tf.keras.layers.Embedding(len(tokenizer.word_index) + 1, layers,input_length=843), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(layers, kernel_regularizer=l2(0.01),... | Your example is missing the definition of f1, precision and recall functions. If the builtin metrics e.g. 'f1' (note it is a string) do not fit your usecase you can pass the custom_objects as follows: def f1(y_true, y_pred): return 1 model = tf.keras.models.load_model(path_to_model, custom_objects={'f1':f1}) | 19 | 27 |
61,788,158 | 2020-5-14 | https://stackoverflow.com/questions/61788158/elasticsearch-search-api-not-returning-all-the-results | I have three indexes, all three of them share a particular key-value pair. When I do a blanket search with the api "http://localhost:9200/_search" using the request body {"query":{ "query_string": { "query":"city*" } } } It is only returning results from two of the indexes. I tried using the same request body by alter... | The reason might be that you haven't provided the size parameter in the query. This limits the result count to 10 by default. Out of all the results the top 10 might be from the two index even thought the match is present in third index as well. This in turn giving the perception that result from third index are not be... | 7 | 10 |
61,784,255 | 2020-5-13 | https://stackoverflow.com/questions/61784255/split-a-pandas-dataframe-into-two-dataframes-efficiently-based-on-some-condition | So, I want to split a given dataframe into two dataframes based on an if condition for a particular column. I am currently achieving this by iterating over the whole dataframe two times. Please suggest some ways to improve this. player score dan 10 dmitri 45 darren 15 xae12 40 Like in the above dataframe, I want to s... | IICU Use boolean select m=df.score>15 Lessthan15=df[~m] Morethan15=df[m] Morethan15 LessThan15 | 7 | 3 |
61,776,830 | 2020-5-13 | https://stackoverflow.com/questions/61776830/python-asyncio-runtimeerror-await-wasnt-used-with-future | I want to use a semaphore with a gather() to limit api calls. I think I have to use create_task() but I obtain a runtime error: "RuntimeError: await wasn't used with future". How can I fix it? Here is the code: import asyncio # pip install git+https://github.com/sammchardy/python-binance.git@00dc9a978590e79d4aa02e6c75... | A sempahore limiting a resource usage is actually a very simple concept. It is similar to counting free parking lots. (-1 when a car enters, +1 when it leaves). When the counter drops to zero, a queue of waiting cars starts to build. That means: one semaphore per resource initial value = upper limit of concurrent reso... | 9 | 4 |
61,776,207 | 2020-5-13 | https://stackoverflow.com/questions/61776207/where-does-win32-come-from-when-im-using-windows-64bit | I'm using windows10 64-bit, I downloaded Python 3.8.1 for windows x86-64. But when I type "python" in cmd, the output says "win32". Where does that come from? Or is that normal? C:\>python Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" ... | tl;dr: "Win32" is still the common name of the Windows API, regardless of whether you're using it on a 32-bit or 64-bit machine. Background The Windows API was once called WinAPI, and the earliest versions ran on 16-bit computers. When they started to make versions for 32-bit computers, they had to modify a bunch of th... | 10 | 12 |
61,770,551 | 2020-5-13 | https://stackoverflow.com/questions/61770551/how-to-run-django-with-uvicorn-webserver | I have a Django project running on my local machine with dev server manage.py runserver and I'm trying to run it with Uvicorn before I deploy it in a virtual machine. So in my virtual environment I installed uvicorn and started the server, but as you can see below it fails to find Django static css files. (envdev) user... | When not running with the built-in development server, you'll need to either use whitenoise which does this as a Django/WSGI middleware (my recommendation) use the classic staticfile deployment procedure which collects all static files into some root and a static file server is expected to serve them. Uvicorn doesn't ... | 18 | 25 |
61,765,502 | 2020-5-13 | https://stackoverflow.com/questions/61765502/pip-freeze-doesnt-show-package-version | Over the weekends I have upgraded my Ubuntu to 20.04, and I tried creating virtualenvironment with python 3.8.2, and pip install requirements.txt. In requirement.txt, I am installing some code from private gitlab repositories. Previously, if I do pip freeze, I was able to see all packages name and version (formatted a... | You can use pip list --format=freeze instead. | 28 | 40 |
61,764,107 | 2020-5-13 | https://stackoverflow.com/questions/61764107/detect-sign-changes-in-pandas-dataframe | I have a pandas dataframe that is datetime indexed and it looks like this: Datetime 2020-05-11 14:00:00-03:00 0.097538 2020-05-11 14:30:00-03:00 -0.083788 2020-05-11 15:00:00-03:00 -0.074128 2020-05-11 15:30:00-03:00 0.059725 2020-05-11 16:00:00-03:00 0.041369 2020-05-11 16:30:00-03:00 0.034388 2020-05-12 10:00:00-03:... | Let us try import numpy as np np.sign(data).diff().ne(0) | 9 | 15 |
61,693,014 | 2020-5-9 | https://stackoverflow.com/questions/61693014/how-to-hide-plotly-yaxis-title-in-python | Editing: The following example from Plotly for reference: import plotly.express as px df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6") fig = px.bar(df, y='pop', x='country', text='pop') fig.update_traces(texttemplate='%{text:.2s}', textposition='outside') fig.update_layout(uniform... | Solution You need to use visible=False inside fig.update_yaxes() or fig.update_layout() as follows. For more details see the documentation for plotly.graph_objects.Figure. # Option-1: using fig.update_yaxes() fig.update_yaxes(visible=False, showticklabels=False) # Option-2: using fig.update_layout() fig.update_layout(y... | 43 | 73 |
61,644,396 | 2020-5-6 | https://stackoverflow.com/questions/61644396/flask-how-to-make-validation-on-request-json-and-json-schema | In flask-restplus API , I need to make validation on request JSON data where I already defined request body schema with api.model. Basically I want to pass input JSON data to API function where I have to validate input JSON data before using API function. To do so, I used RequestParser for doing this task, but the API ... | As I tried to convey in our conversation it appears you are after a serialization and deserialization tool. I have found Marshmallow to be an exceptional tool for this (it is not the only one). Here's a working example of using Marshmallow to validate a request body, converting the validated data back to a JSON string ... | 11 | 21 |
61,710,787 | 2020-5-10 | https://stackoverflow.com/questions/61710787/how-to-run-a-python-script-from-deno | I have a python script with the following code: print("Hello Deno") I want to run this python script (test.py) from test.ts using Deno. This is the code in test.ts so far: const cmd = Deno.run({cmd: ["python3", "test.py"]}); How can I get the output, of the python script in Deno? | To execute a python script from Deno you need to use Deno.Command const command = new Deno.Command('python3', { args: [ "test.py" ], }); const { code, stdout, stderr } = await command.output(); console.log(new TextDecoder().decode(stdout)); console.log(new TextDecoder().decode(stderr)); Old answer: Deno.run is now de... | 16 | 18 |
61,696,180 | 2020-5-9 | https://stackoverflow.com/questions/61696180/pytest-exec-code-in-self-locals-syntaxerror-missing-parentheses-in-call-to-exe | Trying to debug a pytest unit test gives me exec code in self.locals SyntaxError: Missing parentheses in call to 'exec' on very simple code. What could be causing it? | Don't have a package/directory/file/module named code in your code, because it conflicts with pytest. Changing to src solved this. I found the answer here: it turned out to be a conflict with my own python module called 'code' and one in use by the debugger. I changed my module name and the debugger began working. Thi... | 11 | 29 |
61,754,797 | 2020-5-12 | https://stackoverflow.com/questions/61754797/how-to-change-the-color-of-the-median-line-in-boxplot | More generally, how to change the color values for a subset of the boxes properties in a seaborn boxplot? Be that the median, the whiskers, or such. I'm particularly interested in how to change the median value, as I have to create plots which have a dark colour and the median line can't be seen against it. Here's some... | Update: the old version of this answer used the index in the generated lines to guess which line of the plot corresponds to a median line. The new version attaches a special label to each of the means, that can be retrieved later to filter out only those lines. You can use medianprops to change the color of the median ... | 9 | 4 |
61,678,226 | 2020-5-8 | https://stackoverflow.com/questions/61678226/executing-the-assembly-generated-by-numba | In a bizarre turn of events, I've ended up in the following predicament where I'm using the following Python code to write the assembly generated by Numba to a file: @jit(nopython=True, nogil=True) def six(): return 6 with open("six.asm", "w") as f: for k, v in six.inspect_asm().items(): f.write(v) The assembly code i... | After browsing [PyData.Numba]: Numba docs, and some debugging, trial and error, I reached to a conclusion: it seems you're off the path to your quest (as was also pointed out in comments). Numba converts Python code (functions) to machine code (for the obvious reason: speed). It does everything (convert, build, insert ... | 9 | 10 |
61,681,097 | 2020-5-8 | https://stackoverflow.com/questions/61681097/python-and-selenium-mobile-emulation | I'm trying to emulate Chrome for iPhone X with Selenium emulation and Python, as follow: from selenium import webdriver mobile_emulation = { "deviceName": "iphone X" } chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("mobileEmulation", mobile_emulation) driver = webdriver.Chrome(r'C:\Us... | You might have found an answer by now, but here's a general one: In your code example, your driver has no chance to know that you want it to emulate another device. Here's full working code: from selenium import webdriver mobile_emulation = { "deviceName": "your device" } chrome_options = webdriver.ChromeOptions() chro... | 14 | 14 |
61,668,501 | 2020-5-7 | https://stackoverflow.com/questions/61668501/duplicate-layers-when-reusing-pytorch-model | I am trying to reuse some of the resnet layers for a custom architecture and ran into a issue I can't figure out. Here is a simplified example; when I run: import torch from torchvision import models from torchsummary import summary def convrelu(in_channels, out_channels, kernel, padding): return nn.Sequential( nn.Conv... | Your layers aren't actually being invoked twice. This is an artifact of how summary is implemented. The simple reason is because summary recursively iterates over all the children of your module and registers forward hooks for each of them. Since you have repeated children (in base_model and layer0) then those repeated... | 10 | 7 |
61,741,997 | 2020-5-12 | https://stackoverflow.com/questions/61741997/how-to-format-requirements-txt-when-package-source-is-from-specific-websites | I am trying to convert the following installation commands using pip that downloads from another website, into a requirements.txt format, but just can't figure out how. Can anyone assist? pip install torch==1.5.0+cu101 torchvision==0.6.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html pip install detectron2... | The structure of the contents of a requirements.txt file is defined as follows: [[--option]...] <requirement specifier> [; markers] [[--option]...] <archive url/path> [-e] <local project path> [-e] <vcs project url> The <requirement specifier> defines the package and an optional version. SomeProject SomeProject == ... | 18 | 33 |
61,734,206 | 2020-5-11 | https://stackoverflow.com/questions/61734206/how-can-i-use-prefer-binary-with-pip-in-python-3 | In Python 2 I can install a set of packages via pip preferring binary packages over source packages (meaning: fallback to source if binary not found) with: (1) pip install --prefer-binary -r requirements.txt In Python 3 I can do this with: (2) pip3 install --only-binary=:all: -r requirements.txt But (1) is not exactly ... | Solution: upgrade pip to vs. 20.X and use --prefer-binary | 18 | 11 |
61,678,338 | 2020-5-8 | https://stackoverflow.com/questions/61678338/why-is-pycharm-not-highlighting-todos | In my settings, I have the TODO bound to highlight in yellow, yet in the actual code it does not highlight. Here is a screenshot of my settings: Editor -> TODO Does anyone know how to fix this? EDIT: I even tried re-installing Pycharm and I still have the issue. EDIT 2: In the TODO Window, it is saying "0 TODO items fo... | Go to Preferences (or Settings), Project Structure, and make sure the folder with your files is not in the "Excluded" tab's list. Click the folder you want to include and click on the "Sources" tab. Click Apply, then OK! It should work. | 9 | 9 |
61,667,967 | 2020-5-7 | https://stackoverflow.com/questions/61667967/how-can-i-swap-axis-in-a-torch-tensor | I have a torch tensor of size torch.Size([1, 128, 56, 128]) 1 is channel, 128 is the width, and height. 56 are the stacks of images. How can I resize it to torch.Size([1, 56, 128, 128]) ? | You could simply use permute or transpose. | 8 | 4 |
61,664,673 | 2020-5-7 | https://stackoverflow.com/questions/61664673/should-i-use-pip-or-pip3 | Eventually, every single time I install a new Linux distribution I do sudo apt-get install python3. However, once installed I always get confused. python is Python 2.7 and python3 is Python 3.x. But also it appears that pip is for Python 2 and pip3 for Python 3. That said most tutorials I see on Internet always use th... | Use python3 -m pip or python -m pip. That will use the correct pip for the python version you want. This method is mentioned in the pip documentation: python -m pip executes pip using the Python interpreter you specified as python. So /usr/bin/python3.7 -m pip means you are executing pip for your interpreter located a... | 9 | 18 |
61,689,391 | 2020-5-8 | https://stackoverflow.com/questions/61689391/error-with-simple-subclassing-of-pathlib-path-no-flavour-attribute | I'm trying to sublclass Path from pathlib, but I failed with following error at instantiation from pathlib import Path class Pl(Path): def __init__(self, *pathsegments: str): super().__init__(*pathsegments) Error at instantiation AttributeError: type object 'Pl' has no attribute '_flavour' Update: I'm inheriting from... | I solved it. Mokey patching is the way to go. define functions just like this def method1(self, other): blah Path.method1 = method1 The fastest, easiest, most convenient solution, zero downsides. Autosuggest in Pycharm works well. UPDATE: I got THE solution (works with linter and auto suggestor): class MyPath(type(Pat... | 11 | 3 |
61,717,006 | 2020-5-10 | https://stackoverflow.com/questions/61717006/pip-for-python-3-8 | How do I install Pip for Python 3.8 ? I made 3.8 my default Python version. sudo apt install python3.8-pip gives unable to locate package python3.8-pip and running python3.8 -m pip install [package] gives no module named pip I can't run sudo apt install python3-pip because it installs pip for Python 3.6 | Install pip the official way: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python3.8 get-pip.py made 3.8 my default Python version It depends on how you did that, but it might break something in your OS. For example some packages on Ubuntu 18.04 might depend on python being python2.7 or python3 being pyth... | 49 | 67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.