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 |
|---|---|---|---|---|---|---|
65,229,864 | 2020-12-10 | https://stackoverflow.com/questions/65229864/geopandas-polygon-to-line | I am new to geopandas and would like to plot only the outline of a polygon, similar to the function ST_Boundary() in PostGIS I have a geodataframe states containing polygons for each state states = counties.dissolve(by='STATEFP') When I subset by one state, I am able to plot that state: states.loc[states.index.isin(['... | You can get boundary as states.boundary Alternatively, if you want only exterior boundary you get it as states.exterior Those give you new GeoSeries with line geometry. | 8 | 9 |
65,231,632 | 2020-12-10 | https://stackoverflow.com/questions/65231632/importerror-cannot-import-name-bigquery-from-google-cloud-unknown-location | I'm trying to deploy a Cloud Function and it is returning me all the time the following error after importing bigquery from google.cloud ImportError: cannot import name 'bigquery' from 'google.cloud' (unknown location) I've tried to install all the newest versions and remove and reinstall and persists Any idea? | Try adding something like google-cloud-bigquery==2.3.1 into requirements.txt of your Google Cloud Function | 9 | 11 |
65,230,997 | 2020-12-10 | https://stackoverflow.com/questions/65230997/when-i-use-fastapi-and-pydantic-to-build-post-api-appear-a-typeerror-object-of | I use FastAPi and Pydantic to model the requests and responses to an POST API. I defined three class: from pydantic import BaseModel, Field from typing import List, Optional, Dict class RolesSchema(BaseModel): roles_id: List[str] class HRSchema(BaseModel): pk: int user_id: str worker_id: str worker_name: str worker_ema... | Try to use roles=create.roles.dict() for creating query instead of roles=create.roles | 8 | 1 |
65,226,693 | 2020-12-10 | https://stackoverflow.com/questions/65226693/the-conflict-is-caused-by-the-user-requested-tensorboard-2-1-0-tensorflow-1-15 | I am trying to install a package VIBE from a git repo and inistally I was installing its dependencies. The code is located here: https://github.com/mkocabas/VIBE how should I fix this? Here's the error I got: (vibe-env) mona@mona:~/research/VIBE$ pip install -r requirements.txt Requirement already satisfied: numpy==1.1... | The key here is this: The conflict is caused by: The user requested tensorboard==2.1.0 tensorflow 1.15.4 depends on tensorboard<1.16.0 and >=1.15.0 This is due to the fact that there is a conflict in requirements.txt of https://github.com/mkocabas/VIBE since it requires tensorboard==2.1.0 and tensorflow==1.15.4. Howev... | 6 | 3 |
65,224,767 | 2020-12-9 | https://stackoverflow.com/questions/65224767/python-abstract-property-cant-instantiate-abstract-class-with-abstract-me | I'm trying to create a base class with a number of abstract python properties, in python 3.7. I tried it one way (see 'start' below) using the @property, @abstractmethod, @property.setter annotations. This worked but it doesn't raise an exception if the subclass doesn't implement a setter. That's the point of using @ab... | I suspect this is a bug in the interaction of abstract methods and properties. In your base class, the following things happen, in order: You define an abstract method named start. You create a new property that uses the abstract method from 1) as its getter. The name start now refers to this property, with the only r... | 6 | 4 |
65,222,324 | 2020-12-9 | https://stackoverflow.com/questions/65222324/how-to-sample-from-dataframe-based-on-percentile-of-a-column | Given a dataset like this: import pandas as pd rows = [{'key': 'ABC', 'freq': 100}, {'key': 'DEF', 'freq': 60}, {'key': 'GHI', 'freq': 50}, {'key': 'JKL', 'freq': 40}, {'key': 'MNO', 'freq': 13}, {'key': 'PQR', 'freq': 11}, {'key': 'STU', 'freq': 10}, {'key': 'VWX', 'freq': 10}, {'key': 'YZZ', 'freq': 3}, {'key': 'WHYQ... | Let's try: bins = [0, 0.1, 0.5, 1] samples = [3,3,1] df['sample'] = pd.cut(df.percent[::-1].cumsum(), # accumulate percentage bins=[0, 0.1, 0.5, 1], # bins labels=False # num samples ).astype(int) df.groupby('sample').apply(lambda x: x.sample(n=samples[x['sample'].iloc[0])] ) Output: key freq percent sample sample 1 ... | 8 | 10 |
65,219,970 | 2020-12-9 | https://stackoverflow.com/questions/65219970/how-to-design-a-neural-network-to-predict-arrays-from-arrays | I am trying to design a neural network to predict an array of the smooth underlying function from a dataset array with gaussian noise included. I have created a training and data set of 10000 arrays combined. Now I am trying to predict the array values for the actual function but it seems to fail and the accuracy isn't... | Looking at your y data: y_train[0] array([0. , 0.69314718, 1.09861229, 1.38629436, 1.60943791, 1.79175947, 1.94591015, 2.07944154, 2.19722458, 2.30258509, 2.39789527, 2.48490665, 2.56494936, 2.63905733, 2.7080502 , 2.77258872, 2.83321334, 2.89037176, 2.94443898, 2.99573227, 3.04452244, 3.09104245, 3.13549422, 3.1780538... | 7 | 3 |
65,219,786 | 2020-12-9 | https://stackoverflow.com/questions/65219786/how-to-run-a-server-in-python | How to run a server in python? I already have tried: python -m SimpleHTTPServer python -m HTTPServer but its says to me: invalid syntax Can someone help me? Thanks! | You can use this command in cmd or terminal python -m SimpleHTTPServer <port_number> # Python 2.x Python 3.x python3 -m http.server # Python 3x By default, this will run the contents of the directory on a local web server, on port 8000. You can go to this server by going to the URL localhost:8000 in your web browser. | 22 | 36 |
65,216,850 | 2020-12-9 | https://stackoverflow.com/questions/65216850/list-of-lists-into-a-python-rich-table | Given the below, how can i get the animal, age and gender into each of the table cells please? Currently all the data ends up in one cell. Thanks from rich.console import Console from rich.table import Table list = [['Cat', '7', 'Female'], ['Dog', '0.5', 'Male'], ['Guinea Pig', '5', 'Male']] table1 = Table(show_header=... | Just use * to unpack the tuple and it should work fine. for row in zip(*list): table1.add_row(*row) Note that table1.add_row(*('Cat', 'Dog', 'Guinea Pig')) is equivalent to table1.add_row('Cat', 'Dog', 'Guinea Pig') While previously your approach was equivalent to table1.add_row('Cat Dog Guinea Pig') | 6 | 9 |
65,216,794 | 2020-12-9 | https://stackoverflow.com/questions/65216794/importerror-when-importing-metric-from-sklearn | When I am trying to import a metric from sklearn, I get the following error: from sklearn.metrics import mean_absolute_percentage_error ImportError: cannot import name 'mean_absolute_percentage_error' from 'sklearn.metrics' /Users/carter/opt/anaconda3/lib/python3.8/site-packages/sklearn/metrics/__init__.py) I have use... | The function mean_absolute_percentage_error is new in scikit-learn version 0.24 as noted in the documentation. As of December 2020, the latest version of scikit-learn available from Anaconda is v0.23.2, so that's why you're not able to import mean_absolute_percentage_error. You could try installing the latest version f... | 18 | 15 |
65,213,809 | 2020-12-9 | https://stackoverflow.com/questions/65213809/pydantic-does-not-validate-when-assigning-a-number-to-a-string | When assigning an incorrect attribute to a Pydantic model field, no validation error occurs. from pydantic import BaseModel class pyUser(BaseModel): username: str class Config: validate_all = True validate_assignment = True person = pyUser(username=1234) person.username >>>1234 try_again = pyUser() pydantic.error_wrapp... | It is expected behaviour according to the documentation: str strings are accepted as-is, int, float and Decimal are coerced using str(v) You can use the StrictStr, StrictInt, StrictFloat, and StrictBool types to prevent coercion from compatible types. from pydantic import BaseModel, StrictStr class pyUser(BaseModel):... | 7 | 11 |
65,209,934 | 2020-12-9 | https://stackoverflow.com/questions/65209934/pydantic-enum-field-does-not-get-converted-to-string | I am trying to restrict one field in a class to an enum. However, when I try to get a dictionary out of class, it doesn't get converted to string. Instead it retains the enum. I checked pydantic documentation, but couldn't find anything relevant to my problem. This code is representative of what I actually need. from e... | You need to use use_enum_values option of model config: use_enum_values whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialise model.dict() later (default: False) from enum import Enum from pydantic import BaseModel class S(str, Enum): am='am... | 101 | 181 |
65,138,643 | 2020-12-4 | https://stackoverflow.com/questions/65138643/examples-or-explanations-of-pytorch-dataloaders | I am fairly new to Pytorch (and have never done advanced coding). I am trying to learn the basics of deep learning using the d2l.ai textbook but am having trouble with understanding the logic behind the code for dataloaders. I read the torch.utils.data docs and am not sure what the DataLoader class is meant for, and wh... | I'll give you an example of how to use dataloaders and will explain the steps: Dataloaders are iterables over the dataset. So when you iterate over it, it will return B randomly from the dataset collected samples (including the data-sample and the target/label), where B is the batch-size. To create such a dataloader yo... | 6 | 14 |
65,120,501 | 2020-12-3 | https://stackoverflow.com/questions/65120501/typing-any-in-python-3-9-and-pep-585-type-hinting-generics-in-standard-collect | I am trying to understand if the typing package is still needed? If in Python 3.8 I do: from typing import Any, Dict my_dict = Dict[str, Any] Now in Python 3.9 via PEP 585 it's now preferred to use the built in types for collections hence: from typing import Any my_dict = dict[str, Any] Do I still need to use the typ... | The use of the Any remains the same. PEP 585 applies only to standard collections. This PEP proposes to enable support for the generics syntax in all standard collections currently available in the typing module. Starting with Python 3.9, the following collections become generic and importing those from typing is dep... | 14 | 17 |
65,172,029 | 2020-12-6 | https://stackoverflow.com/questions/65172029/why-do-i-get-str-object-is-not-callable | I did this plot and it worked. The day after I ran it and I got this error: TypeError: 'str' object is not callable. plt.plot(A2, A15, color="black", label="TRC - P1", marker="o") plt.xlabel("Amostras") plt.ylabel("TRC (%)") plt.title("TRC da P1") plt.yticks([0, 10, 20, 30, 40, 50, 60, 70]) plt.xticks(rotation=60) Fol... | I would guess that you defined somewhere in your notebook something like plt.xlabel = "something". This could also happened before you run this code shown. Try to close the Notebook and restart your Kernel. After restarting run your code shown and everything should be fine. If using jupyter notebook then click on Run t... | 14 | 52 |
65,101,442 | 2020-12-2 | https://stackoverflow.com/questions/65101442/formatter-black-is-not-working-on-my-vscode-but-why | I have started using Python and Django and I am very new in this field. And, this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue... When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up... | Update 2023-09-15: Now VSCode has a Microsoft oficial Black Formatter extension. It will probably solve your problems. Original answer: I use Black from inside VSCode and it rocks. It frees mental cycles that you would spend deciding how to format your code. It's best to use it from your favorite editor. Just run from ... | 80 | 121 |
65,140,310 | 2020-12-4 | https://stackoverflow.com/questions/65140310/is-there-a-way-to-release-the-gil-for-pure-functions-using-pure-python | I think I must be missing something; this seems so right, but I can't see a way to do this. Say you have a pure function in Python: from math import sin, cos def f(t): x = 16 * sin(t) ** 3 y = 13 * cos(t) - 5 * cos(2*t) - 2 * cos(3*t) - cos(4*t) return (x, y) is there some built-in functionality or library that provid... | Is there a way to release the GIL for pure functions using pure python? In short, the answer is no, because those functions aren't pure on the level on which the GIL operates. GIL serves not just to protect objects from being updated concurrently by Python code, its primary purpose is to prevent the CPython interpret... | 14 | 17 |
65,141,291 | 2020-12-4 | https://stackoverflow.com/questions/65141291/get-a-list-of-all-available-fonts-in-pil | I'm trying to find out what fonts are available to be used in PIL with the font = ImageFont.load() and/or ImageFont.truetype() function. I want to create a list from which I can sample a random font to be used. I haven't found anything in the documentation so far, unfortunately. | I have so far not found a solution with PIL but matplotlib has a function to get all the available fonts from the system: system_fonts = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf') The font can then be loaded using fnt = ImageFont.truetype(font, 60) | 9 | 12 |
65,184,937 | 2020-12-7 | https://stackoverflow.com/questions/65184937/fatal-python-error-init-fs-encoding-failed-to-get-the-python-codec-of-the-file | I am trying to start my uwsgi server in my virtual environment, but after I added plugin python3 option I get this error every time: !!! Python Home is not a directory: /home/env3/educ !!! Set PythonHome to /home/env3/educ Python path configuration: PYTHONHOME = '/home/env3/educ' PYTHONPATH = (not set) program name = '... | I see your PYTHONHOME is set to PYTHONHOME = '/home/env3/educ'. Try to check if it is really there. The solution for me was to remove the PYTHONHOME environment variable. For you, it can be just that, or setting that variable to another value. This worked on Windows, and would work on Linux for sure. If someone tries t... | 57 | 44 |
65,142,024 | 2020-12-4 | https://stackoverflow.com/questions/65142024/when-set-name-is-useful-in-python | I saw a tweet from Raymond Hettinger yesterday. He used __set_name__. When I define __set_name__ method for my Class, the name becomes the instance's name. The owner became Foo, which is also expected but I couldn't figure out when and how this is useful. class Bar: def __set_name__(self, owner, name): print(f'{self} w... | As @juanpa provided a brief explanation, it is used to know the variable's name and class. One of its use cases is for logging. When you want to log the variable's name. This example was in descriptor's HowTo. import logging logging.basicConfig(level=logging.INFO) class LoggedAccess: def __set_name__(self, owner, name)... | 14 | 12 |
65,167,879 | 2020-12-6 | https://stackoverflow.com/questions/65167879/python-y-should-be-a-1d-array-got-an-array-of-shape-instead | Let's consider data : import numpy as np from sklearn.linear_model import LogisticRegression x=np.linspace(0,2*np.pi,80) x = x.reshape(-1,1) y = np.sin(x)+np.random.normal(0,0.4,80) y[y<1/2] = 0 y[y>1/2] = 1 clf=LogisticRegression(solver="saga", max_iter = 1000) I want to fit logistic regression where y is dependent v... | Change the order of your operations: First geneate x and y as 1-D arrays: x = np.linspace(0, 2*np.pi, 8) y = np.sin(x) + np.random.normal(0, 0.4, 8) Then (after y was generated) reshape x: x = x.reshape(-1, 1) Edit following a comment as of 2022-02-20 The source of the problem in the original code is that; x = np.li... | 7 | 8 |
65,122,957 | 2020-12-3 | https://stackoverflow.com/questions/65122957/resolving-new-pip-backtracking-runtime-issue | The new pip dependency resolver that was released with version 20.3 takes an inappropriately long time to install a package. On our CI pipeline yesterday, a docker build that used to take ~10 minutes timed out after 1h of pip installation messages like this (almost for every library that is installed by any dependency ... | Latest update (2022-02) There seems to be major update in pip just few days old (version 22.0, release notes + relevant issue on github). I haven't tested it in more detail but it really seems to me that they optimized installation order calculation in complex case in such way that it resolves many issues we all encoun... | 185 | 130 |
65,152,998 | 2020-12-5 | https://stackoverflow.com/questions/65152998/pause-a-ffmpeg-encoding-in-a-python-popen-subprocess-on-windows | I am trying to pause an encode of FFmpeg while it is in a non-shell subprocess (This is important to how it plays into a larger program). This can be done by presssing the "Pause / Break" key on the keyboard by itself, and I am trying to send that to Popen. The command itself must be cross platform compatible, so I can... | Linux/Unix solution: import subprocess, os, signal # ... # Start the task: proc = subprocess.Popen(..., start_new_session=True) # ... def send_signal_to_task(pid, signal): #gpid = os.getpgid(pid) # WARNING This does not work gpid = pid # But this does! print(f"Sending {signal} to process group {gpid}...") os.killpg(gpi... | 6 | 2 |
65,182,608 | 2020-12-7 | https://stackoverflow.com/questions/65182608/how-to-define-a-type-for-a-function-arguments-and-return-type-with-a-predefine | I want to define a function signature (arguments and return type) based on a predefined type. Let's say I have this type: safeSyntaxReadType = Callable[[tk.Tk, Notebook, str], Optional[dict]] which means safeSyntaxReadType is a function that receives 3 arguments (from types as listed above), and it can return a dict o... | Simply assign the function to a new name representing the specific callable type. Greetable = Callable[[str, int], str] def any_greet_person(name, age): ... typed_greet_person: Greetable = any_greet_person reveal_type(any_greet_person) reveal_type(typed_greet_person) Keep in mind that the object defined as any_greet_p... | 10 | 8 |
65,107,269 | 2020-12-2 | https://stackoverflow.com/questions/65107269/python-dictionary-with-generic-keys-and-callablet-values | I have some named tuples: JOIN = NamedTuple("JOIN", []) EXIT = NamedTuple("EXIT", []) I also have functions to handle each type of tuple with: def handleJoin(t: JOIN) -> bool: pass def handleExit(t: EXIT) -> bool: pass What I want to do is create a dictionary handleTuple so I can call it like so: t: Union[JOIN, EXIT]... | TypeVars are only meaningful in aliases, classes and functions. One can define a Protocol for the lookup: T = TypeVar("T", JOIN, EXIT, contravariant=True) class Handler(Protocol): def __getitem__(self, item: Type[T]) -> Callable[[T], bool]: ... handleTuple = cast(Handler, {JOIN: handleJoin, EXIT: handleExit}) The spec... | 6 | 4 |
65,113,967 | 2020-12-2 | https://stackoverflow.com/questions/65113967/why-is-nothing-drawn-in-pygame-at-all | i have started a new project in python using pygame and for the background i want the bottom half filled with gray and the top black. i have used rect drawing in projects before but for some reason it seems to be broken? i don't know what i am doing wrong. the weirdest thing is that the result is different every time i... | You need to update the display. You are actually drawing on a Surface object. If you draw on the Surface associated to the PyGame display, this is not immediately visible in the display. The changes become visibel, when the display is updated with either pygame.display.update() or pygame.display.flip(). See pygame.disp... | 6 | 4 |
65,110,798 | 2020-12-2 | https://stackoverflow.com/questions/65110798/feature-importance-in-a-binary-classification-and-extracting-shap-values-for-one | Suppose we have a binary classification problem, we have two classes of 1s and 0s as our target. I aim to use a tree classifier to predict 1s and 0s given the features. Further, I can use SHAP values to rank the feature importance that are predictive of 1s and 0s. Until now everything is good! Now suppose that I want t... | Let's prepare some binary classification data: from seaborn import load_dataset from sklearn.model_selection import train_test_split from lightgbm import LGBMClassifier import shap titanic = load_dataset("titanic") X = titanic.drop(["survived","alive","adult_male","who",'deck'],1) y = titanic["survived"] features = X.c... | 9 | 12 |
65,124,833 | 2020-12-3 | https://stackoverflow.com/questions/65124833/how-to-combine-scatter-and-line-plots-using-plotly-express | Plotly Express has an intuitive way to provide pre-formatted plotly plots with minimal lines of code; sort of how Seaborn does it for matplotlib. It is possible to add traces of plots on Plotly to get a scatter plot on an existing line plot. However, I couldn't find such a functionality in Plotly Express. Is it possibl... | You can use: fig3 = go.Figure(data=fig1.data + fig2.data) Where fig1 and fig2 are built using px.line() and px.scatter(), respectively. And fig3 is, as you can see, built using plotly.graph_objects. Some details: One approach that I use alot is building two figures fig1 and fig2 using plotly.express and then combine t... | 35 | 76 |
65,184,355 | 2020-12-7 | https://stackoverflow.com/questions/65184355/error-403-access-denied-from-google-authentication-web-api-despite-google-acc | I'm using the default code provided from Google, and I don't quite understand why it's not working. The code outputs the prompt "Please visit this URL to authorize this application: [Google login URL]." When attempting to log in with the account designated as owner of the script under the google developers console I ge... | The error message you are getting is related to the fact that your application has not been verified yet. As mentioned in that link all applications that access google APIs using sensitive scopes need to go though googles verification process. Normal you are given a grace period of 100 users accessing your application ... | 60 | 26 |
65,130,080 | 2020-12-3 | https://stackoverflow.com/questions/65130080/attributeerror-running-django-site-on-mac-11-0-1 | I'm getting an error running a django site locally that was working fine before I updated my Mac OS to 11.0.1. I'm thinking this update is the cause of the problem since nothing else was really changed between when it was working and now. 10:15:05 worker.1 | Traceback (most recent call last): 10:15:05 worker.1 | File "... | Ok this is a dirty workaround for Big Sur compatibility: https://developer.apple.com/documentation/macos-release-notes/macos-big-sur-11_0_1-release-notes New in macOS Big Sur 11.0.1, the system ships with a built-in dynamic linker cache of all system-provided libraries. As part of this change, copies of dynamic librar... | 7 | 26 |
65,205,506 | 2020-12-8 | https://stackoverflow.com/questions/65205506/lstm-autoencoder-problems | TLDR: Autoencoder underfits timeseries reconstruction and just predicts average value. Question Set-up: Here is a summary of my attempt at a sequence-to-sequence autoencoder. This image was taken from this paper: https://arxiv.org/pdf/1607.00148.pdf Encoder: Standard LSTM layer. Input sequence is encoded in the final ... | Okay, after some debugging I think I know the reasons. TLDR You try to predict next timestep value instead of difference between current timestep and the previous one Your hidden_features number is too small making the model unable to fit even a single sample Analysis Code used Let's start with the code (model is the... | 13 | 8 |
65,184,035 | 2020-12-7 | https://stackoverflow.com/questions/65184035/alembic-ignore-specific-tables | I'm using alembic to manage database migrations as per user defined sqlalchemy models. My challenge is that I'd like for alembic to ignore any creation, deletion, or changes to a specific set of tables. Note: My Q is similar to this question Ignoring a model when using alembic autogenerate but is different in that I wa... | I found a solution to my problem! My error was in the instantiation of my context object in env.py def run_migrations_offline(): ... context.configure( url=url, target_metadata=target_metadata, include_object=include_object, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): c... | 24 | 23 |
65,133,937 | 2020-12-3 | https://stackoverflow.com/questions/65133937/mock-streaming-api-in-python-for-unit-test | I have an async function that calls a streaming api. What is the best way to write unit test for this function? The api response has to be mocked. I tried with aiounittest and used mock from unittest. But this calls the actual api instead of getting the mocked response. Also tried with pytest.mark.asyncio annotation, b... | Use asynctest instead of aiounittest. Replace unittest.TestCase with asynctest.TestCase. Replace from unittest.mock import patch with from asynctest.mock import patch. async for data in method1: should be async for data in method1():. import asynctest from asynctest.mock import patch class TestClass(asynctest.TestCas... | 6 | 4 |
65,108,407 | 2020-12-2 | https://stackoverflow.com/questions/65108407/understanding-featurehasher-collisions-and-vector-size-trade-off | I'm preprocessing my data before implementing a machine learning model. Some of the features are with high cardinality, like country and language. Since encoding those features as one-hot-vector can produce sparse data, I've decided to look into the hashing trick and used python's category_encoders like so: from catego... | Is that the way to use the library in order to encode high categorical values? Yes. There is nothing wrong with your implementation. You can think about the hashing trick as a "reduced size one-hot encoding with a small risk of collision, that you won't need to use if you can tolerate the original feature dimension".... | 11 | 5 |
65,208,376 | 2020-12-8 | https://stackoverflow.com/questions/65208376/find-path-of-python-installed-by-homebrew | I have installed python 3.8.6 with homebrew on macOS. But when I check with which -a python3 I only get paths of 3.9 and 3.8.2. Is there a way to find the paths of all versions installed by homebrew? Or maybe more general question, how can I find the path of 3.8.6? | Use brew info <packagename> it's probably in one of (and referenced in both) /usr/local/Cellar/python@3.8/3.8.6_2 /usr/local/opt/python@3.8/libexec/bin See also Apple SE Where can I find the installed package path via brew If it's not there, it's plausible the version detection is wrong and only searches for the first... | 7 | 8 |
65,179,646 | 2020-12-7 | https://stackoverflow.com/questions/65179646/how-do-i-parse-a-chemical-formula-using-a-regular-expression | I have a list patterns: patterns=['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn... | Use import pandas as pd patterns=['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn... | 7 | 0 |
65,193,998 | 2020-12-8 | https://stackoverflow.com/questions/65193998/syntaxerror-invalid-syntax-to-repo-init-in-the-aosp-code | I have tried to repo init the source code Ubuntu build machine and it is successfully able to clone the code. repo init -u git@github.com:xxx/xx_manifest.git -b xxx Now I am trying repo init the source code in VM Ubuntu machine. In between getting the error like below: Traceback (most recent call last): File "/xxx/.rep... | try these commands curl https://storage.googleapis.com/git-repo-downloads/repo-1 > ~/bin/repo chmod a+x ~/bin/repo python3 ~/bin/repo init -u git@.... | 30 | 49 |
65,198,998 | 2020-12-8 | https://stackoverflow.com/questions/65198998/sphinx-warning-autosummary-stub-file-not-found-for-the-methods-of-the-class-c | I have an open source package with lots of classes over different submodules. All classes have methods fit and transform, and inherit fit_transform from sklearn. All classes have docstrings that follow numpydoc with subheadings Parameters, Attributes, Notes, See Also, and Methods, where I list fit, transform and fit_tr... | Ok, after 3 days, I nailed it. The secret is add a short description to the methods in the docstrings after the heading "Methods" instead of leaving them empty as I did. So: class DropFeatures(BaseEstimator, TransformerMixin): Some description. Parameters ---------- features_to_drop : str or list, default=None Variable... | 13 | 13 |
65,199,011 | 2020-12-8 | https://stackoverflow.com/questions/65199011/is-there-a-way-to-check-similarity-between-two-full-sentences-in-python | I am making a project like this one here: https://www.youtube.com/watch?v=dovB8uSUUXE&feature=youtu.be but i am facing trouble because i need to check the similarity between the sentences for example: if the user said: 'the person wear red T-shirt' instead of 'the boy wear red T-shirt' I want a method to check the simi... | Most of there libraries below should be good choice for semantic similarity comparison. You can skip direct word comparison by generating word, or sentence vectors using pretrained models from these libraries. Sentence similarity with Spacy Required models must be loaded first. For using en_core_web_md use python -m sp... | 28 | 76 |
65,100,974 | 2020-12-2 | https://stackoverflow.com/questions/65100974/how-do-i-properly-import-python-modules-in-a-multi-directory-project | I have a python project with a basic setup that looks like this: imptest.py utils/something.py utils/other.py Here's what's in the scripts: imptest.py #!./venv/bin/python import utils.something as something import utils.other as other def main(): """ Main function. """ something.do_something() other.do_other() if __na... | The problem here is the path, Consider this directory structure main - utils/something.py - utils/other.py imptest.py When you try to import other using relative path in to something.py, then you would do something like from . import other. This would work when you execute $ python something.py but would fail when you... | 7 | 6 |
65,196,818 | 2020-12-8 | https://stackoverflow.com/questions/65196818/unable-to-access-docker-container-socket-hang-up-error | I have successfully built and started the docker container, it is running perfectly, but when I try to access it [End point url 0.0.0.0:6001] I am getting a "socket hang up" error GET http://0.0.0.0:6001/ Error: socket hang up Request Headers User-Agent: PostmanRuntime/7.26.8 Accept: */* Postman-Token: <token> Host: 0.... | Try localhost:6001 not internet address You can also try any of your system local ipaddress , you find ipaddress by typing ifconfig or ipconfig if you are in linux or windows respectively | 14 | 0 |
65,194,694 | 2020-12-8 | https://stackoverflow.com/questions/65194694/session-not-created-this-version-of-chromedriver-only-supports-chrome-version-8 | I installed the version chromedriver 88 as requested but my version chrome is 87.0.4280.88 that is the last version (outside beta) while I am also asked to download version 88 of chrome Here is the error : selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver ... | Your ChromeDriver version and your installed version of Chrome need to match up. You are using ChromeDriver for Chrome version 87. Keep both version same. Check your Chrome version (Help -> About) and then find the correct ChromeDriver release. You could instead use webdriver-manager which can handle this for you. Chro... | 18 | 24 |
65,186,969 | 2020-12-7 | https://stackoverflow.com/questions/65186969/simplifying-straight-line-movements-in-a-list-of-step-by-step-x-y-coordinates | In my game, I have a list of tuples (x,y) : solution = [(36, 37), (36, 36), (36, 35), (37, 35), (38, 35), (38, 34), (38, 33), (38, 32)] This list describes the movements the player should do to move from point (36, 37) to point (38, 32). I want to simplify this list to the following : opti = [(36, 37), (36, 35), (38, ... | You can try this: compare the previous and next location with the current location when iterating over the list(solution) to check if all the points are in the same line, pass if they are in the same line else append to the final (opti) list. solution = [(36, 37), (36, 36), (36, 35), (37, 35), (38, 35), (38, 34), (38, ... | 6 | 1 |
65,106,184 | 2020-12-2 | https://stackoverflow.com/questions/65106184/adding-a-dynamic-email-backend-in-django | I would like to let my users decide their email backend on their own. That is why I have created the email relevant keys (host, port, username...) on the users and now I try to work this (see below) backend into my Django project. Working with the docs and the source code, my first attempt was to extend the default Ema... | send_email has a parameter called connection (link to docs) which seems to fit perfectly. You can get a connection by calling get_connection (link to docs) with the user's parameters. connection = get_connection(host=user.email_host, port=user.email_port, ...) send_email(connection=connection, ...) If you'd like to su... | 7 | 4 |
65,174,575 | 2020-12-7 | https://stackoverflow.com/questions/65174575/typeerror-not-supported-between-instances-of-nonetype-and-float | I am following a YouTube tutorial and I wrote this code from the tutorial import numpy as np import pandas as pd from scipy.stats import percentileofscore as score my_columns = [ 'Ticker', 'Price', 'Number of Shares to Buy', 'One-Year Price Return', 'One-Year Percentile Return', 'Six-Month Price Return', 'Six-Month Per... | I'm working through this tutorial as well. I looked deeper into the data in the four '___ Price Return' columns. Looking at my batch API call, there's four rows that have the value 'None' instead of a float which is why the 'NoneError' appears, as the percentileofscore function is trying to calculate the percentiles us... | 11 | 12 |
65,182,169 | 2020-12-7 | https://stackoverflow.com/questions/65182169/create-new-column-with-data-that-has-same-column | I have DataFrame similat to this. How to add new column with names of rows that have same value in one of the column? For example: Have this: name building a blue b white c blue d red e blue f red How to get this? name building in_building_with a blue [c, e] b white [] c blue [a, e] d red [f] e blue [a, c] f red [d]... | This is approach(worst) I can only think of : r = df.groupby('building')['name'].agg(dict) df['in_building_with'] = df.apply(lambda x: [r[x['building']][i] for i in (r[x['building']].keys()-[x.name])], axis=1) df: name building in_building_with 0 a blue [c, e] 1 b white [] 2 c blue [a, e] 3 d red [f] 4 e blue [a, c] ... | 7 | 4 |
65,181,817 | 2020-12-7 | https://stackoverflow.com/questions/65181817/how-to-iterate-over-multiple-lists-of-different-lengths-but-repeat-the-last-val | In my Python 3 script, I am trying to make a combination of three numbers from three different lists based on inputs. If the lists are the same size, there is no issue with zip. However, I want to be able to input a single number for a specific list and the script to repeat that number until the longest list is finishe... | You could make use of logical or operator to use the last element of the shorter lists: from itertools import zip_longest list1 = [1] list2 = ["a", "b", "c", "d", "e", "f"] list3 = [2] for l1, l2, l3 in zip_longest(list1, list2, list3): print(l1 or list1[-1], l2, l3 or list3[-1]) Out: 1 a 2 1 b 2 1 c 2 1 d 2 1 e 2 1 f... | 10 | 10 |
65,180,527 | 2020-12-7 | https://stackoverflow.com/questions/65180527/how-to-update-a-value-in-the-nested-column-of-struct-using-pyspark | I try to do very simple - update a value of a nested column;however, I cannot figure out how Environment: Apache Spark 2.4.5 Databricks 6.4 Python 3.7 dataDF = [ (('Jon','','Smith'),'1580-01-06','M',3000) ] schema = StructType([ StructField('name', StructType([ StructField('firstname', StringType(), True), StructFiel... | Need to wrangle with the column a bit as below: import pyspark.sql.functions as F df2 = df.select('*', 'name.*') \ .withColumn('firstname', F.lit('newname')) \ .withColumn('name', F.struct(*[F.col(col) for col in df.select('name.*').columns])) \ .drop(*df.select('name.*').columns) df2.show() +------------------+-------... | 9 | 7 |
65,175,454 | 2020-12-7 | https://stackoverflow.com/questions/65175454/how-to-delete-multiple-files-and-specific-pattern-in-s3-boto3 | Can Python delete specific multiple files in S3? I want to delete multiple files with specific extensions. This script removes all files. These are the various specific files that I want to delete: XXX.tar.gz XXX.txt ** Current code: ** (all files deleted) import boto3 accesskey = "123" secretkey = "123" region = "ap-... | Presuming that you want to delete *.tar.gz and *.txt files from the given bucket and prefix, this would work: import boto3 s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket('my-bucket') objects = bucket.objects.filter(Prefix = 'myfolder/') objects_to_delete = [{'Key': o.key} for o in objects if o.key.endsw... | 6 | 12 |
65,103,114 | 2020-12-2 | https://stackoverflow.com/questions/65103114/most-efficient-way-of-adding-elements-given-the-index-list-in-numpy | Assume we have a numpy array A with shape (N, ) and a matrix D with shape (M, 3) which has data and another matrix I with shape (M, 3) which has corresponding index of each data element in D. How can we construct A given D and I such that the repeated element indexes are added? Example: ############# A[I] := D ########... | I doubt you can get much faster than np.bincount - and notice how the official documentation provides this exact usecase # Your example A = [0.5, 0.6] D = [[0.1, 0.1, 0.2], [0.2, 0.4, 0.1]] I = [[0, 1, 0], [0, 1, 1]] # Solution import numpy as np D, I = np.array(D).flatten(), np.array(I).flatten() print(np.bincount(I, ... | 7 | 6 |
65,171,183 | 2020-12-6 | https://stackoverflow.com/questions/65171183/how-to-run-headless-microsoft-edge-with-selenium-in-python | With Chrome you can add options when creating the driver. You just do options = Options() options.headless = True driver = webdriver.Chrome(PATH\TO\DRIVER, options=options) But for some reason when trying to do the same with Microsoft Edge options = Options() options.headless = True driver = webdriver.Edge(PATH\TO\DRI... | options = EdgeOptions() options.use_chromium = True options.add_argument("headless") options.add_argument("disable-gpu") Try above code , you have to enable chromium to enable headless https://learn.microsoft.com/en-us/microsoft-edge/webdriver-chromium/?tabs=python This works only for new edge chromium not for edge l... | 9 | 9 |
65,167,576 | 2020-12-6 | https://stackoverflow.com/questions/65167576/python-decimal-addition-and-subtraction-not-giving-exact-result | Python (3.8) code: #!/usr/bin/env python3 from decimal import Decimal from decimal import getcontext x = Decimal('0.6666666666666666666666666667') y = x; print(getcontext().prec) print(y) print(y == x) y += x; y += x; y += x; y -= x; y -= x; y -= x; print(y) print(y == x) Python output: 28 0.66666666666666666666666666... | From Python documentation: The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. Moreover, the following also need to be considered: The context precision does not affect how many digits are stored. That is determined exclusively by the number of digits in value. For example, De... | 6 | 3 |
65,160,277 | 2020-12-5 | https://stackoverflow.com/questions/65160277/spacy-tokenizer-with-only-whitespace-rule | I would like to know if the spacy tokenizer could tokenize words only using the "space" rule. For example: sentence= "(c/o Oxford University )" Normally, using the following configuration of spacy: nlp = spacy.load("en_core_news_sm") doc = nlp(sentence) for token in doc: print(token) the result would be: ( c / o Oxf... | Let's change nlp.tokenizer with a custom Tokenizer with token_match regex: import re import spacy from spacy.tokenizer import Tokenizer nlp = spacy.load('en_core_web_sm') text = "This is it's" print("Before:", [tok for tok in nlp(text)]) nlp.tokenizer = Tokenizer(nlp.vocab, token_match=re.compile(r'\S+').match) print("... | 5 | 11 |
65,163,947 | 2020-12-6 | https://stackoverflow.com/questions/65163947/iterate-over-a-list-based-on-list-with-set-of-iteration-steps | I want to iterate a given list based on a variable number of iterations stored in another list and a constant number of skips stored in as an integer. Let's say I have 3 things - l - a list that I need to iterate on (or filter) w - a list that tells me how many items to iterate before taking a break k - an integer tha... | This works: l = [6,2,2,5,2,5,1,7,9,4] w = [2,2,1,1] k = 1 def take(xs, runs, skip_size): ixs = iter(xs) for run_size in runs: for _ in range(run_size ): yield next(ixs) for _ in range(skip_size): next(ixs) result = list(take(l, w, k)) print(result) Result: [6, 2, 5, 2, 1, 9] The function is what's called a generator,... | 9 | 6 |
65,157,725 | 2020-12-5 | https://stackoverflow.com/questions/65157725/using-selenium-inside-gitlab-ci-cd | I've desperetaly tried to set a pytest pipeline CI/CD for my personal projet hosted by gitlab. I tried to set up a simple project with two basic files: file test_core.py, witout any other dependencies for the sake of simplicity: # coding: utf-8 # !/usr/bin/python3 import pytest from selenium import webdriver from selen... | I've finally managed to ping gitlab CI on green with the below .gitlab-ci.yml file. Note that I'm not a fan of yaml language. To make the file shorter, I've used a shared block of code, named install_firefox_geckodriver. Then, I've configured 2 jobs with python 3.7 and 3.8, that call this block. The keys to make this k... | 7 | 5 |
65,159,773 | 2020-12-5 | https://stackoverflow.com/questions/65159773/set-column-width-in-pandas-dataframe | Searching for this topic and found a solution but doesn't work for me The code I am working on (part of it like that) pd.set_option('max_colwidth', 1000) df = pd.DataFrame(list) The line of setting the max colwidth: I tried to put this line before the df line and another try after the df line but the output still the ... | You can try setting the others parameters also like: pd.set_option('display.max_columns', 1000, 'display.width', 1000, 'display.max_rows',1000) | 6 | 4 |
65,158,620 | 2020-12-5 | https://stackoverflow.com/questions/65158620/official-repository-of-unicode-character-names | There are a few ways to get the list of all Unicode characters' names: for example using Python module unicodedata, as explained in List of unicode character names, or using the website: https://unicode.org/charts/charindex.html but here it's incomplete, and you have to open and parse PDF to find the names. But what is... | The official source for the actual character data (which includes the character names and many, many other details) is the Unicode Character Database. The latest version of the data files can be accessed via http://www.unicode.org/Public/UCD/latest/. Names specifically can be found in the files NamesList.txt. The forma... | 6 | 10 |
65,156,028 | 2020-12-5 | https://stackoverflow.com/questions/65156028/set-print-flush-true-to-default | I am aware that you can flush after a print statement by setting flush=True like so: print("Hello World!", flush=True) However, for cases where you are doing many prints, it is cumbersome to manually set each print to flush=True. Is there a way to set the default to flush=True for Python 3.x? I am thinking of somethin... | You can use partial: from functools import partial print_flushed = partial(print, flush=True) print_flushed("Hello world!") From the documentation: The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified ... | 7 | 8 |
65,147,823 | 2020-12-4 | https://stackoverflow.com/questions/65147823/python-asyncio-task-exception-was-never-retrieved | Description: (simplified) I have 2 tasks. Within each task I have 3 coroutines. 2 coroutines from the first task fail. (simulated) While processing task results, I am getting one "Task exception was never retrieved" message. I believe this is because exception of only one of the two failed coroutines in that task was ... | If you want to collect exceptions instead of raising them, you can use asyncio.gather(return_exceptions=True) in coro as well. For example: import asyncio async def download(data): if data in ['b', 'c']: 1/0 # simulate error return 42 # success async def coro(data_list): coroutines = [download(data) for data in data_li... | 14 | 10 |
65,115,092 | 2020-12-2 | https://stackoverflow.com/questions/65115092/occasional-deadlock-in-multiprocessing-pool | I have N independent tasks that are executed in a multiprocessing.Pool of size os.cpu_count() (8 in my case), with maxtasksperchild=1 (i.e. a fresh worker process is created for each new task). The main script can be simplified to: import subprocess as sp import multiprocessing as mp def do_work(task: dict) -> dict: re... | The deadlock occurred due to high memory usage in workers, thus triggering the OOM killer which abruptly terminated the worker subprocesses, leaving the pool in a messy state. This script reproduces my original problem. For the time being I am considering switching to a ProcessPoolExecutor which will throw a BrokenProc... | 9 | 10 |
65,150,961 | 2020-12-4 | https://stackoverflow.com/questions/65150961/in-defined-for-generator | Why is in operator defined for generators? >>> def foo(): ... yield 42 ... >>> >>> f = foo() >>> 10 in f False What are the possible use cases? I know that range(...) objects have a __contains__ function defined so that we can do stuff like this: >>> r = range(10) >>> 4 in r True >>> r.__contains__ <method-wrapper '__... | "What are the possible use cases?" To check if the generator will produce some value. Dunder methods serve as hooks for the particular syntax they are associated with. __contains__ isn't some kind of one-to-one mapping to x in y. The language ultimately defines the semantics of these operators. From the documentation o... | 6 | 4 |
65,146,320 | 2020-12-4 | https://stackoverflow.com/questions/65146320/pandas-how-to-get-rows-with-consecutive-dates-and-sales-more-than-1000 | I have a data frame called df: Date Sales 01/01/2020 812 02/01/2020 981 03/01/2020 923 04/01/2020 1033 05/01/2020 988 ... ... How can I get the first occurrence of 7 consecutive days with sales above 1000? This is what I am doing to find the rows where sales is above 1000: In [221]: df.loc[df["sales"] >= 1000] Out [22... | You can assign a unique identifier per consecutive days, group by them, and return the first value per group (with a previous filter of values > 1000): df = df.query('Sales > 1000').copy() df['grp_date'] = df.Date.diff().dt.days.fillna(1).ne(1).cumsum() df.groupby('grp_date').head(7).reset_index(drop=True) where you c... | 6 | 5 |
65,147,132 | 2020-12-4 | https://stackoverflow.com/questions/65147132/how-to-set-the-hue-order-in-seaborn-plots | I have a Pandas dataset named titanic I am plotting a bar chart as described in the Seaborn official documentation, using the following code: import seaborn as sns titanic = sns.load_dataset("titanic") sns.catplot(x="sex", y="survived", hue="class", kind="bar", data=titanic) This produces the following plot: As you c... | In order to manually select the hue order of a Seaborn plot, you have to define the desired order as a list and then pass it to the plot function as the argument hue_order . The following code would work: import seaborn as sns titanic = sns.load_dataset("titanic") hue_order = ['Third', 'Second', 'First'] sns.catplot(x=... | 29 | 60 |
65,114,261 | 2020-12-2 | https://stackoverflow.com/questions/65114261/is-there-a-way-to-deploy-a-fastapi-app-on-cpanel | I'm having trouble deploying a FastAPI app on cpanel with Passenger | You might be able to run your FastAPI app using a2wsgi: In your passenger_wsgi.py: from a2wsgi import ASGIMiddleware from main import app # Import your FastAPI app. application = ASGIMiddleware(app) | 9 | 10 |
65,139,977 | 2020-12-4 | https://stackoverflow.com/questions/65139977/how-is-x-42-x-lambda-x-parsed | I was surprised that this assertion fails: x = 42 x = lambda: x assert x() == 42 It seems that x ends up recursively referring to itself, so that x(), x()(), etc. are all functions. What is the rule used to parse this, and where is this documented? By the way (not unexpectedly given the above), the original value of x... | The variable x is created by the first assignment, and rebound with the second assignment. Since the x in the lambda isn't evaluated until the lambda is called, calling it will evaluate to the most recently assigned value. Note that this is not dynamic scoping - if it were dynamic, the following would print "99", but i... | 49 | 45 |
65,135,205 | 2020-12-3 | https://stackoverflow.com/questions/65135205/how-to-set-a-protobuf-timestamp-field-in-python | I am exploring the use of protocol buffers and would like to use the new Timestamp data type which is in protobuf3. Here is my .proto file: syntax = "proto3"; package shoppingbasket; import "google/protobuf/timestamp.proto"; message TransactionItem { optional string product = 1; optional int32 quantity = 2; optional do... | See Timestamp. I think you want: basket1.tstamp.GetCurrentTime() | 6 | 7 |
65,120,743 | 2020-12-3 | https://stackoverflow.com/questions/65120743/many-rg-commands-started-by-vscode-that-consume-99-of-cpus | I'm working inside a very big github repo, say its structure is like project-root ├── project-1 │ ├── subproject-a │ └── subproject-others └── project-2 ├── subproject-b └── subproject-others There are many projects, each contains many subprojects. I'm just working on one of the subprojects (e.g. subproject-a). When I... | It turns out that there are four symlink folders with over 700k files in them. These folders are usually ignored in /project-root/.gitginore. So rg by default would ignore searching in them. But here because of --no-ignore-parent --follow flags, they are being searched nonetheless. I added these folders to /project-roo... | 11 | 5 |
65,108,382 | 2020-12-2 | https://stackoverflow.com/questions/65108382/visual-studio-code-color-not-working-when-using-python-types | I am using the new python syntax to describe what types my methods return e.g.,: def method(unpacked_message: dict) -> dict: This seems to break the vscode color scheme Expected colors: Environment and vs code extensions: Python 3.6.9 on ubuntu ms-python.python v2020.11.371526539 tht13.python: Python for VS code v0... | Based on the information you provided, I reproduced the problem you described. Reason: The Syntax Highlighting style provided by the extension "Python for VSCode" is different from the extension "Python". Solution: Please disable the extension "Python for VSCode". before: after: | 18 | 33 |
65,127,212 | 2020-12-3 | https://stackoverflow.com/questions/65127212/python3-nat-hole-punching | I know this topic is not new. There is various information out there although, the robust solution is not presented (at least I did not found). I have a P2P daemon written in python3 and the last element on the pie is to connect two clients behind the NAT via TCP. My references for this topic: https://bford.info/pub/ne... | Finally found the expected behavior! Don't want to give too much code here but I hope after this you will understand the basics of how to implement it. Best to have a separate file in each of the client's folder - nearby ./tcphole_client1.py and ./tcphole_client2.py. We need to connect fast after we initiated sessions ... | 7 | 5 |
65,131,391 | 2020-12-3 | https://stackoverflow.com/questions/65131391/what-exactly-is-kerass-categoricalcrossentropy-doing | I am porting a keras model over to torch and I'm having trouble replicating the exact behavior of keras/tensorflow's 'categorical_crossentropy' after a softmax layer. I have some workarounds for this problem, so I'm only interested in understanding what exactly tensorflow calculates when calculating categorical cross e... | The problem is that you are using hard 0s and 1s in your predictions. This leads to nan in your calculation since log(0) is undefined (or infinite). What is not really documented is that the Keras cross-entropy automatically "safeguards" against this by clipping the values to be inside the range [eps, 1-eps]. This mean... | 8 | 7 |
65,119,003 | 2020-12-3 | https://stackoverflow.com/questions/65119003/binning-pandas-value-counts | I have a Pandas Series produced by df.column.value_counts().sort_index(). | N Months | Count | |------|------| | 0 | 15 | | 1 | 9 | | 2 | 78 | | 3 | 151 | | 4 | 412 | | 5 | 181 | | 6 | 543 | | 7 | 175 | | 8 | 409 | | 9 | 594 | | 10 | 137 | | 11 | 202 | | 12 | 170 | | 13 | 446 | | 14 | 29 | | 15 | 39 | | 16 | 44 | | 17 ... | You can use pd.cut: pd.cut(df['N Months'], [0,13, 26, 50], include_lowest=True).value_counts() Update you should be able to pass custom bin to value_counts: df['N Months'].value_counts(bins = [0,13, 26, 50]) Output: N Months (-0.001, 13.0] 3522 (13.0, 26.0] 793 (26.0, 50.0] 9278 Name: Count, dtype: int64 | 6 | 21 |
65,113,251 | 2020-12-2 | https://stackoverflow.com/questions/65113251/why-are-sqlite3-shortcut-functions-called-nonstandard | I've used sqlite3 in Python in which execute() creates ambiguity. When I use: import sqlite3 A = sqlite3.connect('a') A.execute('command to be executed') help(A.execute) I got the output of help() as: ..... ..... Executes a SQL statement. Non-standard. But when I execute like this: import sqlite3 A = sqlite.connect('... | The "nonstandard" function is the execute method of the sqlite3.Connection class: This is a nonstandard shortcut that creates a cursor object by calling the cursor() method, calls the cursor’s execute() method with the parameters given, and returns the cursor. "Standard" refers to PEP 249 -- Python Database API Speci... | 6 | 6 |
65,112,585 | 2020-12-2 | https://stackoverflow.com/questions/65112585/pip-installation-stuck-in-infinite-loop-if-unresolvable-conflicts-in-dependencie | Pip installation is stuck in an infinite loop if there are unresolvable conflicts in dependencies. To reproduce, pip==20.3.0 and: pip install pyarrow==2.0.0 azureml-defaults==1.18.0 | Workarounds: Local environment: Downgrade pip to < 20.3 Conda environment created from yaml: This will be seen only if conda-forge is highest priority channel, anaconda channel doesn't have pip 20.3 (as of now). To mitigate the issue please explicitly specify pip<20.3 (!=20.3 or =20.2.4 pin to other version) as a conda... | 15 | 13 |
65,111,601 | 2020-12-2 | https://stackoverflow.com/questions/65111601/what-is-the-difference-between-async-with-lock-and-with-await-lock | I have seen two ways of acquiring the asyncio Lock: async def main(lock): async with lock: async.sleep(100) and async def main(lock): with await lock: async.sleep(100) What is the difference between them? | The second form with await lock is deprecated since Python 3.7 and is removed in Python 3.9. Running it with Python 3.7 gives this warning: DeprecationWarning: 'with await lock' is deprecated use 'async with lock' instead Sources (scroll to the bottom): https://docs.python.org/3.7/library/asyncio-sync.html https://d... | 9 | 7 |
65,107,933 | 2020-12-2 | https://stackoverflow.com/questions/65107933/pytorch-model-training-cpu-memory-leak-issue | When I trained my pytorch model on GPU device,my python script was killed out of blue.Dives into OS log files , and I find script was killed by OOM killer because my CPU ran out of memory.It’s very strange that I trained my model on GPU device but I ran out of my CPU memory. Snapshot of OOM killer log file In order to... | Previously when you did not use the .detach() on your tensor, you were also accumulating the computation graph as well and as you went on, you kept acumulating more and more until you ended up exuasting your memory to the point it crashed. When you do a detach(), you are effectively getting the data without the previou... | 6 | 4 |
65,102,969 | 2020-12-2 | https://stackoverflow.com/questions/65102969/invalid-syntax-jose-py | I was trying to use jose library for authentication for one of my flask apps. using the import statement as follows from jose import jwt But it throws following An error, Traceback (most recent call last): File "F:/XXX_XXX/xxxx-services-web/src/auth.py", line 6, in <module> from jose import jwt File "F:\Users\XXXX_XXX... | installing python-jose instead of jose fixed my problem. https://pypi.org/project/python-jose/ | 22 | 44 |
65,102,579 | 2020-12-2 | https://stackoverflow.com/questions/65102579/send-and-receive-file-using-python-fastapi-and-requests | I'm trying to upload a file to a FastAPI server using requests. I've boiled the problem down to its simplest components. The client using requests: import requests files = {'file': ('foo.txt', open('./foo.txt', 'rb'))} response = requests.post('http://127.0.0.1:8000/file', files=files) print(response) print(response.js... | FastAPI expecting the file in the my_file field and you are sending it to the file field. it should be as import requests url = "http://127.0.0.1:8000/file" files = {'my_file': open('README.md', 'rb')} res = requests.post(url, files=files) Also, you don't need a tuple to manage the upload file (we're dealing with a sim... | 17 | 27 |
65,102,013 | 2020-12-2 | https://stackoverflow.com/questions/65102013/add-line-break-after-every-20-characters-and-save-result-as-a-new-string | I have a string variable input = "A very very long string from user input", how can I loop through the string and add a line break \n after 20 characters then save the formatted string in a variable new_input? So far am only able to get the first 20 characters as such input[0:20] but how do you do this through the enti... | You probably want to do something like this inp = "A very very long string from user input" new_input = "" for i, letter in enumerate(inp): if i % 20 == 0: new_input += '\n' new_input += letter # this is just because at the beginning too a `\n` character gets added new_input = new_input[1:] | 5 | 6 |
65,093,883 | 2020-12-1 | https://stackoverflow.com/questions/65093883/how-do-i-turn-off-the-evaluating-plt-show-did-not-finish-after-3-00s-seconds | I often debug my python code by plotting NumPy arrays in the vscode debugger. Often I spend more than 3s looking at a plot. When I do vscode prints the extremely long warning below. It's very annoying because I then have to scroll up a lot all the time to see previous debugging outputs. Where is this PYDEVD_WARN_EVALUA... | If found a way to adapt the launch.json which takes care of this problem. { "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "debugpy", "request": "launch", "program": "${file}", "env": {"PYTHONPATH": "${workspaceRoot}", "PYDEVD_WARN_EVALUATION_TIMEOUT": "500"}, "cwd": "${workspaceFolde... | 21 | 32 |
65,034,898 | 2020-11-27 | https://stackoverflow.com/questions/65034898/pip-install-does-not-find-package-but-pip-search-does | I want to install the hdbcli package (SAP HANA connector). When I search with pip the package is being found, but when I want to install it, pip can't find the package. Specifiying the current package also yields no results. pip install hdbcli==2.6.61 How do I solve this? > pip search hbdcli hdbcli (2.6.61) - SAP HANA... | This usually means pip could not find any distribution of that project that would be compatible with your python environment: Python implementation (CPython, or PyPy, etc.) Python interpreter major and minor version (3.10, or 3.11, etc.) operating system (Windows, or Linux, etc.) CPU bitness (64 bits or 32 bits) versi... | 12 | 12 |
65,082,448 | 2020-11-30 | https://stackoverflow.com/questions/65082448/specify-pandas-index-name-in-the-constructor | Can I specify a pandas DataFrame index name in the constructor? Said otherwise, I would like to do the following: df = pd.DataFrame({"a":[1,2],"b":[3,4]}) df.rename_axis(index='myindex', inplace=True) with a single line of code (by calling only the constructor) | You can pass an index to the DataFrame constructor with the given name that you want. import pandas as pd df = pd.DataFrame({"a":[1,2],"b":[3,4]}, index=pd.Index([], name='myIndex')) df a b myIndex 0 1 3 1 2 4 | 13 | 13 |
65,031,764 | 2020-11-27 | https://stackoverflow.com/questions/65031764/posewarping-how-to-vectorize-this-for-loop-z-buffer | I'm trying to warp a frame from view1 to view2 using ground truth depth map, pose information, and camera matrix. I've been able to remove most of the for-loops and vectorize it, except one for-loop. When warping, multiple pixels in view1 may get mapped to a single location in view2, due to occlusions. In this case, I ... | I implemented this as follows. Instead of picking the nearest point (min), I used soft-min, i.e. I took the weighted average of all the colliding points where I made sure that a small difference in depth leads to a large difference in weights and that the nearest depth has the highest weight. I implemented the sum (in ... | 8 | 1 |
65,037,641 | 2020-11-27 | https://stackoverflow.com/questions/65037641/plotly-how-to-add-multiple-y-axes | I have data with 5 different columns and their value varies from each other. Actual gen Storage Solar Gen Total Gen Frequency 1464 1838 1804 18266 51 2330 2262 518 4900 51 2195 923 919 8732 49 2036 1249 1316 3438 48 2910 534 1212 4271 47 857 2452 1272 6466 50 2331 990 2729 14083 51 2604 767 2730 19037 47 993 2606 705 1... | Here is an example of how multi-level y-axes can be created. Essentially, the keys to this are: Create a key in the layout dict, for each axis, then assign a trace to the that axis. Set the xaxis domain to be narrower than [0, 1] (for example [0.2, 1]), thus pushing the left edge of the graph to the right, making room... | 9 | 8 |
65,044,870 | 2020-11-27 | https://stackoverflow.com/questions/65044870/how-to-extract-info-within-a-shadow-root-open-using-selenium-python | I got the next url related to an online store https://www.tiendasjumbo.co/buscar?q=mani and I can't extract the product label an another fields: from selenium import webdriver import time from random import randint driver = webdriver.Firefox(executable_path= "C:\Program Files (x86)\geckodriver.exe") driver.implicitly_w... | The products within the website https://www.tiendasjumbo.co/buscar?q=mani are located within a #shadow-root (open). Solution To extract the product label you have to use shadowRoot.querySelector() and you can use the following Locator Strategy: Code Block: driver.get('https://www.tiendasjumbo.co/buscar?q=mani') item... | 8 | 13 |
65,010,639 | 2020-11-25 | https://stackoverflow.com/questions/65010639/in-a-coockiecutter-template-add-folder-only-if-choice-variable-has-a-given-valu | I am creating a cookiecutter template and would like to add a folder (and the files it contains) only if a variable has a given value. For example cookiecutter.json: { "project_slug":"project_folder" "i_want_this_folder":['y','n'] } and my template structure looks like: template └── {{ cookiecutter.project_slug }} ├──... | I was facing the same issue having the option to add or no folders with different contents (all folders can exist at the same time). The structure of the project is the following: ├── {{cookiecutter.project_slug}} │ │ │ ├── folder_1_to_add_or_no │ │ ├── file1.py │ │ ├── file2.py │ │ └── file3.txt │ │ │ ├── folder_2_to_... | 6 | 3 |
65,026,852 | 2020-11-26 | https://stackoverflow.com/questions/65026852/set-default-value-for-selectbox | I am new to streamlit. I tried to set a default value for sidebar.selectbox. The code is below. I appreciate the help! Thank you in advance. st.sidebar.header('Settings') fichier = st.sidebar.selectbox('Dataset', ('djia', 'msci', 'nyse_n', 'nyse_o', 'sp500', 'tse')) window_ANTICOR = st.sidebar.selectbox('Window ANTICOR... | Use the index keyword of the selectbox widget. Pass the index of the value in the options list that you want to be the default choice. E.g. if you wanted to set the default choice of the selectbox labeled 'Window ANTICOR' to 30 (which you appear to be trying to do), you could simply do this: values = ['<select>',3, 5, ... | 17 | 25 |
64,997,553 | 2020-11-25 | https://stackoverflow.com/questions/64997553/python-requires-ipykernel-to-be-installed | I encounter an issue when I use the Jupyter Notebook in VS code. The screen shows "Python 3.7.8 requires ipykernel to be installed". I followed the pop-up to install ipykernel. It still does not work. The screenshot is attached. It bothers me a lot. Could anyone help me with it? Tons of thanks. | I had the same issue and spent the whole day trying to resolve it. What worked for me was installing the Jupyter dependencies for anaconda: > conda install jupyter I installed this in my base environment. After this VSCode worked without any errors. | 64 | 28 |
65,074,811 | 2020-11-30 | https://stackoverflow.com/questions/65074811/how-to-open-ipynb-file-in-spyder | without using iSpyder DOS shell commands, how can an .ipynb (Jupyter Notebook) be opened directly into Spyder on Windows? Even the online Jupyter Notebook site prompts for a relative directory path where the file is stored. Why isn't there something that just loads the Notebook how it's supposed to look without typing... | You may check out https://github.com/spyder-ide/spyder-notebook Once you install this, you can open native .ipynb files in spyder From the website: Spyder plugin to use Jupyter notebooks inside Spyder. Currently it supports basic functionality such as creating new notebooks, opening any notebook in your filesystem and... | 15 | 11 |
65,095,614 | 2020-12-1 | https://stackoverflow.com/questions/65095614/macbook-m1-and-python-libraries | Is new macbook m1 suitable for Data Science? Do Data Science python libraries such as pandas, numpy, sklearn etc work on the macbook m1 (Apple Silicon) chip and how fast compared to the previous generation intel based macbooks? | This GitHub repository has lots of useful information about the Apple M1 chip and data science in Python https://github.com/neurolabusc/AppleSiliconForNeuroimaging. I have included representative quotes below. This repository focuses on software for brain imaging analysis, but the takeaways are broad. Updated on 27 Sep... | 24 | 45 |
65,031,238 | 2020-11-27 | https://stackoverflow.com/questions/65031238/why-doesnt-os-systemcls-clear-the-recent-output | I am always using system('cls') in C language before using Dev-C++. Now I am studying Python and using Pycharm 2020.2.3. I tried to use os.system('cls'). Here is my program: import os print("clear screen") n = int(input("")) if n == 1: os.system('cls') There is no error in my program but it is not clearing the recent ... | PhCharm displays the output of your running module using the output console. In order for your terminal commands under os.system() to work, you need to emulate your terminal inside the output console. Select 'Edit Configurations' from the 'Run' menu. Under the 'Execution' section, select 'Emulate terminal in output co... | 8 | 8 |
65,002,585 | 2020-11-25 | https://stackoverflow.com/questions/65002585/connection-object-has-no-attribute-sftp-live-when-pysftp-connection-fails | I'd like to catch nicely the error when "No hostkey for host *** is found" and give an appropriate message to the end user. I tried this: import pysftp, paramiko try: with pysftp.Connection('1.2.3.4', username='root', password='') as sftp: sftp.listdir() except paramiko.ssh_exception.SSHException as e: print('SSH error... | The analysis by @reverse_engineer is correct. However: It seems that an additional attribute, self._transport, also is defined too late. The problem can be temporarily corrected until a permanent fix comes by subclassing the pysftp.Connection class as follows: import pysftp import paramiko class My_Connection(pysftp.... | 18 | 12 |
65,064,740 | 2020-11-29 | https://stackoverflow.com/questions/65064740/error-when-trying-to-use-conda-on-visual-studio-code-conda-the-term-conda | I am trying to build a basic machine learning algorithm, and to do so I am using the Anaconda interpreter for Python. However, even though Visual Studio Code appears to have recognized Conda as the interpreter, and I have the Anaconda 3 shell working as a separate application, I cannot get Conda to work in Visual Studi... | Try the following: Run Anaconda/Miniconda Activate the environment there: conda activate your-env Start Visual Studio Code from the Anaconda/Miniconda terminal: code Then Visual Studio Code should recognize conda: | 9 | 21 |
65,012,601 | 2020-11-25 | https://stackoverflow.com/questions/65012601/attributeerror-simpleimputer-object-has-no-attribute-validate-data-in-pyca | I am using PyCaret and get an error. AttributeError: 'SimpleImputer' object has no attribute '_validate_data' Trying to create a basic instance. # Create a basic PyCaret instance import pycaret from pycaret.regression import * mlb_pycaret = setup(data = pycaret_df, target = 'pts', train_size = 0.8, numeric_features = ... | The problem here is with the imputation. The default per pycaret documentation is 'simple' but in this case, you need to make that imputation_type='iterative' for it to work. | 8 | 13 |
65,011,660 | 2020-11-25 | https://stackoverflow.com/questions/65011660/how-can-i-get-the-title-of-the-currently-playing-media-in-windows-10-with-python | Whenever audio is playing in windows 10, whether it is from Spotify, Firefox, or a game. When you turn the volume, windows has a thing in the corner that says the song artist, title, and what app is playing like the photo below (sometimes it only says what app is playing sound if a game is playing the sound) I want to... | I am getting the titles of the windows to get the song information. Usually, the application name is displayed in the title, but when it is playing a song, the song name is shown. Here is a function that returns a list of all the window titles. from __future__ import print_function import ctypes def get_titles(): EnumW... | 15 | 2 |
65,064,137 | 2020-11-29 | https://stackoverflow.com/questions/65064137/geopandas-how-to-plot-countries-cities | I would need to plot some data on a geographic plot. Specifically, I would like to highlight countries and states where data comes from. My dataset is Year Country State/City 0 2009 BGR Sofia 1 2018 BHS New Providence 2 2002 BLZ NaN 3 2000 CAN California 4 2002 CAN Ontario ... ... ... ... 250 2001 USA Ohio 251 1998 US... | From the code you've posted I can't see anything wrong with the plotting, so I assume that the issue might be somewhere in your data aggregation or merging. Here is a solution that starts by generating data which should be similar to yours, then counts the number of times a country appears in the data as a proportion o... | 11 | 6 |
65,080,685 | 2020-11-30 | https://stackoverflow.com/questions/65080685/usb-usb-device-handle-win-cc1020-failed-to-read-descriptor-from-node-connectio | We recently upgraded our Windows 10 test environment with ChromeDriver v87.0.4280.20 and Chrome v87.0.4280.66 (Official Build) (64-bit) and after the up-gradation even the minimal program is producing this ERROR log: [9848:10684:1201/013233.169:ERROR:device_event_log_impl.cc(211)] [01:32:33.170] USB: usb_device_handle_... | After going through quite a few discussions, documentations and Chromium issues here are the details related to the surfacing of the log message: [9848:10684:1201/013233.169:ERROR:device_event_log_impl.cc(211)] [01:32:33.170] USB: usb_device_handle_win.cc:1020 Failed to read descriptor from node connection: A device at... | 16 | 20 |
65,083,808 | 2020-12-1 | https://stackoverflow.com/questions/65083808/bump2version-to-increment-pre-release-while-removing-post-release-segment | How would I use bump2version (with regards to its invocation and/or its configuration) to increment: 1.0.0.a2.post0 # post-release of a pre-release a2 to 1.0.0.a3 # pre-release a3 Reproducible example: $ python3 -m pip install 'bump2version==1.0.*' __init__.py: __version__ = "1.0.0.a2.post0" setup.cfg: [bumpversion... | We had to wrestle with that (and, back in the days, with the original bumpversion, not the nicer bump2version). With the config below, you can use bumpversion pre to go from 1.0.0.a2.post0 to 1.0.0.a3. Explanation: Since pre and post each have both a string prefix and a number, I believe it is necessary to split them a... | 7 | 5 |
65,062,014 | 2020-11-29 | https://stackoverflow.com/questions/65062014/how-to-make-a-module-reload-in-python-after-the-script-is-compiled | The basic idea involved: I am trying to make an application where students can write code related to a specific problem(say to check if the number is even) The code given by the student is then checked by the application by comparing the output given by the user's code with the correct output given by the correct code ... | Even for the bundled application imports work the standard way. That means whenever an import is encountered, the interpreter will try to find the corresponding module. You can make your test_it.py module discoverable by appending the containing directory to sys.path. The import test_it should be dynamic, e.g. inside a... | 6 | 1 |
65,028,943 | 2020-11-26 | https://stackoverflow.com/questions/65028943/google-or-tools-tsp-spanning-multiple-days-with-start-stop-times | I am using Google OR-Tools to optimize the routing of a single vehicle over the span of a several day. I am trying to: Be able to specify the number of days over which to optimize routing. Be able to specify the start location and end location for each day. Be able to specify the start time and end time for each day. ... | You may have something like that: python plop.py Objective: 93780 droped: [] Route for vehicle 0: 0 [21600;21600] -> 38 [21902;57722] -> 33 [23897;59717] -> 34 [25935;61755] -> 28 [28562;64382] -> 41 [31374;67194] -> 39 [33520;69340] -> 40 [35840;71660] -> 36 [38315;74135] -> 37 [40745;76565] -> 5 [44115;79935] -> 25 [... | 9 | 2 |
65,084,044 | 2020-12-1 | https://stackoverflow.com/questions/65084044/pytest-fixture-not-found-pytest-bdd | I have the following step definitions, which result in an error because the @given fixture is not found, even though it is defined in target_fixture: import pytest from pytest_bdd import scenario, given, when, then, parsers from admin import Admin @scenario('../features/Admin.feature', 'register a new user') def test_a... | Either downgrade to pytest-bdd<4 where this behaviour is still accepted, or rename the steps by removing the test_ prefix to prevent pytest from recognizing them as separate tests. @when(...) def register(admin_login, ...): ... @then(...) def login(admin_login): ... should work. | 6 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.