content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How can I change the result of torch.cuda.is_available() to True GTX 1050ti
hello i have recently started using pytorch but now i need to use my GPU which is a Nvidia GTX 1050ti to process some data but unfortunately torch.cuda.is_available() is returning False i have tried uninstaling cudatoolkit 11.3 and downgra... | How can I change the result of torch.cuda.is_available() to True GTX 1050ti | hello i have recently started using pytorch but now i need to use my GPU which is a Nvidia GTX 1050ti to process some data but unfortunately torch.cuda.is_available() is returning False i have tried uninstaling cudatoolkit 11.3 and downgrade it to 11.1 and also deleating and reinstaling pytorch using conda install pyto... | [
"You have probably downloaded the only-cpu version.\nHave you tried to install it using pip and the stable pytorch version?\npip install torch torchvision -f https://download.pytorch.org/whl/torch_stable.html\n\nMake sure to purge your pip cache before so you won't install the same chached wheels:\npip uninstall to... | [
0
] | [] | [] | [
"gpu",
"python",
"pytorch"
] | stackoverflow_0067527807_gpu_python_pytorch.txt |
Q:
Pandas - How to count multiple columns and generate a percentage
I have a dataframe that has 100+ columns. The columns have either a 1 (for yes) and 0 (for no) as seen below.
I'm trying to find out the percentage of each - such as "what percentage of the episodes have a barn?" or "what percentage of the episodes ... | Pandas - How to count multiple columns and generate a percentage | I have a dataframe that has 100+ columns. The columns have either a 1 (for yes) and 0 (for no) as seen below.
I'm trying to find out the percentage of each - such as "what percentage of the episodes have a barn?" or "what percentage of the episodes have a beach?" I think I'll need to iterate through the rows and put t... | [
"is this what you mean?\ndf = pd.DataFrame([[1,1,0],[0,0,1],[1,0,1],[0,0,1]],\n columns=['barn','beach','boat'])\n\n>>> df\n'''\n barn beach boat\n0 1 1 0\n1 0 0 1\n2 1 0 1\n3 0 0 1\n'''\n\n>>> df.mean().reset_index(name='value')\n'''\n inde... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074563730_dataframe_pandas_python_python_3.x.txt |
Q:
ImportError: cannot import name 'COMMON_SAFE_ASCII_CHARACTERS' from 'charset_normalizer.constant'
Traceback (most recent call last):
File "g:\mydrive\ \pdftotext_pdfminer.py", line 3, in <module>
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
File "C:\Users\ \anaconda3\envs\ \lib\sit... | ImportError: cannot import name 'COMMON_SAFE_ASCII_CHARACTERS' from 'charset_normalizer.constant' | Traceback (most recent call last):
File "g:\mydrive\ \pdftotext_pdfminer.py", line 3, in <module>
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
File "C:\Users\ \anaconda3\envs\ \lib\site-packages\pdfminer\pdfinterp.py", line 7, in <module>
from .cmapdb import CMap
File "C:\Users\ ... | [
"there. I faced the same problem when trying to use the pdfplumber package today (2022-11-24) from a script I have long used with no problem. I don't know why this error is happening but found one of the solutions in this link helpful:\nHow to fix AttributeError: partially initialized module?\nBriefly, I removed my... | [
0
] | [] | [] | [
"importerror",
"pdfminer",
"python"
] | stackoverflow_0074535380_importerror_pdfminer_python.txt |
Q:
How to get all keys and values from aioredis
redis = aioredis.from_url(url='redis://some_url', decode_responses=True)
redis.set('key', 'value')
redis.set('key1', 'value1)
redis.get('key')
I want to get all keys and values with loop, like:
for key, values in redis.scan_iter():
print(key, value)
For example. I... | How to get all keys and values from aioredis | redis = aioredis.from_url(url='redis://some_url', decode_responses=True)
redis.set('key', 'value')
redis.set('key1', 'value1)
redis.get('key')
I want to get all keys and values with loop, like:
for key, values in redis.scan_iter():
print(key, value)
For example. I am looking for in docs, but can not find. Anybody... | [
"I find the answer.\nkeys = await redis.keys()\nfor key in keys:\n value = await redis.get(key)\n\nThis help to me!\n"
] | [
0
] | [] | [] | [
"aioredis",
"python",
"redis"
] | stackoverflow_0074559311_aioredis_python_redis.txt |
Q:
Pyspark 'from_json', dataframe return null for all json columns
Utilizing python (version 3.7.12) and pyspark (version 2.4.0).
I am trying to use a from_json statement using the columns and identified schema. However, the df returns as null. I am assuming I am incorrectly identifying the schema and type for the co... | Pyspark 'from_json', dataframe return null for all json columns | Utilizing python (version 3.7.12) and pyspark (version 2.4.0).
I am trying to use a from_json statement using the columns and identified schema. However, the df returns as null. I am assuming I am incorrectly identifying the schema and type for the columns.
The following code is the json string from a table I pulled fr... | [
"The data column actually contains a json array so the schema must be an ArrayType:\nschema = ArrayType(\n elementType = StructType(\n [\n StructField('zip', StringType(), True),\n StructField('phnumber', StringType(), True),\n StructField('name', StringType(), True)\n ... | [
0
] | [] | [] | [
"apache_spark_sql",
"pyspark",
"python"
] | stackoverflow_0074513136_apache_spark_sql_pyspark_python.txt |
Q:
Merge dataframes from two dictionaries through a loop
Tried to keep this relatively simple but let me know if you need more information.
I have 2 dictionaries made up of three dataframes each, these have been produced through loops then added into a dictionary. They have the keys ['XAUUSD', 'EURUSD', 'GBPUSD'] in ... | Merge dataframes from two dictionaries through a loop | Tried to keep this relatively simple but let me know if you need more information.
I have 2 dictionaries made up of three dataframes each, these have been produced through loops then added into a dictionary. They have the keys ['XAUUSD', 'EURUSD', 'GBPUSD'] in common:
trades_dict
{'XAUUSD': df_trades_1
'EURUSD': df_tr... | [
"\"\"\"\nPseudocode :\nFor each key in the list of keys in trades_dict :\n Pick that key's value (trades df) from trades_dict\n Using the same key, pick corresponding value (prices df) from prices_dict\n Merge both values (trades & prices dataframes)\n\"\"\"\n\ndf_merge_list = []\n\nfor key in trades_dict.... | [
1,
0
] | [] | [] | [
"dictionary",
"loops",
"merge",
"pandas",
"python"
] | stackoverflow_0074564510_dictionary_loops_merge_pandas_python.txt |
Q:
Is there a cleaner way to replace characters in a text file?
i am trying to replace characters in a text file, the code works but it just seems too long. I was wondering if there is a different way to do this?
(It is a good way for me to learn a better way than just a long repetivite way)
Thanks
with open('documen... | Is there a cleaner way to replace characters in a text file? | i am trying to replace characters in a text file, the code works but it just seems too long. I was wondering if there is a different way to do this?
(It is a good way for me to learn a better way than just a long repetivite way)
Thanks
with open('documento.txt', 'r') as file:
filedata = file.read()
filedata = file... | [
"In order to make this process more efficient, you may want to consider using a for loop with parallel lists containing what you want to replace and what you want to replace with. In your case, the code would look something like this:\nbeforeList = ['+', 'P', 'B', 'N', 'K', 'X', 'Q', 'T', '*', 'Y', '_', 'V', 'H', '... | [
0
] | [] | [] | [
"python",
"replace"
] | stackoverflow_0074564829_python_replace.txt |
Q:
Error: Could not locate a Flask application in VSCode
I am trying to learn Flask using VScode.
The tutorial that I am following is: Python Flask Tutorial: Full-Featured Web App Part 1 - Getting Started.
I did the following things:
Created a new virtualenv in a folder using: virtualenv venv
activated it as: venv\S... | Error: Could not locate a Flask application in VSCode | I am trying to learn Flask using VScode.
The tutorial that I am following is: Python Flask Tutorial: Full-Featured Web App Part 1 - Getting Started.
I did the following things:
Created a new virtualenv in a folder using: virtualenv venv
activated it as: venv\Scripts\activate (I am on Windows 10)
After that, I created... | [
"Issue raised in VsCode\nUnder Powershell, you have to set the FLASK_APP environment variable as follows:\n$env:FLASK_APP = \"webapp\"\nThen you should be able to run \"python -m flask run\" inside the hello_app folder. In other words, PowerShell manages environment variables differently, so the standard command-li... | [
11,
0,
0
] | [] | [] | [
"flask",
"python",
"visual_studio_code"
] | stackoverflow_0058320164_flask_python_visual_studio_code.txt |
Q:
python web scraping none value issue
I am trying to get the salary from this web_page but each time i got the same value "None"
however i tried to take different tags!
link_content = requests.get("https://wuzzuf.net/jobs/p/KxrcG1SmaBZB-Facility-Administrator-Majorel-Egypt-Alexandria-Egypt?o=1&l=sp&t=sj&a=search-v3... | python web scraping none value issue | I am trying to get the salary from this web_page but each time i got the same value "None"
however i tried to take different tags!
link_content = requests.get("https://wuzzuf.net/jobs/p/KxrcG1SmaBZB-Facility-Administrator-Majorel-Egypt-Alexandria-Egypt?o=1&l=sp&t=sj&a=search-v3")
soup = BeautifulSoup(link_content.text,... | [
"Page is being generated dynamically with Javascript, so Requests cannot see it as you see it. Try disabling Javascript in your browser and hard reload the page, and you will see a lot of information missing. However, data exists in page in a script tag.\nOne way of getting that information is by slicing that scrip... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074564707_beautifulsoup_python_web_scraping.txt |
Q:
Convert NETCDF file to TIFF when coordinates are variables (not coordinates)
How to convert the NetCDF to TIFF, when the coordinates are stored in another NetCDF file (and are a irregular grid, since this covers the Arctic region)?
An example of the NetCDF file can be downloaded here: https://drive.google.com/uc?e... | Convert NETCDF file to TIFF when coordinates are variables (not coordinates) | How to convert the NetCDF to TIFF, when the coordinates are stored in another NetCDF file (and are a irregular grid, since this covers the Arctic region)?
An example of the NetCDF file can be downloaded here: https://drive.google.com/uc?export=download&id=1i4OGCQhKlZ056H1YHq4hTb0EbEkl-pYd
The NetCDF file with the coord... | [
"Your files do not follow any standard that I know of. Each dimension is in its separate dataset.\nIf you are sure that the longitude/latitude is linear - which it might not be given that your dataset covers the polar regions - you can simply use gdal_translate to convert to TIFF and then gdal_edit.py -a_ulurll ulx... | [
0
] | [] | [] | [
"gdal",
"netcat",
"netcdf",
"python",
"tiff"
] | stackoverflow_0074545153_gdal_netcat_netcdf_python_tiff.txt |
Q:
How to verify RSA signature generated by Python-RSA using Crypto++
I have a server written in Python, and a C++ client. The Python server has a private RSA key, and the redistributable C++ client has the paired public key. The C++ client sends a string to the Python server, the server generates a signature by enco... | How to verify RSA signature generated by Python-RSA using Crypto++ | I have a server written in Python, and a C++ client. The Python server has a private RSA key, and the redistributable C++ client has the paired public key. The C++ client sends a string to the Python server, the server generates a signature by encoding this string with its private key, and sends it to the client in ASC... | [
"I abandoned Crypto++ because I couldn't get it to work on QtCreator + Windows, and used OpenSSL instead. It's horribly counterintuitive to code, but there is a lot of support and I got it to work with a member's help in this thread: Verify in OpenSSL C++ a signature generated in PyCryptoDome\nUse this if you are f... | [
0
] | [] | [] | [
"c++",
"crypto++",
"cryptography",
"python",
"rsa"
] | stackoverflow_0074554044_c++_crypto++_cryptography_python_rsa.txt |
Q:
Find the maximum frequency of an element in a given Array
This is the solution I have come up with but I'm unsure whether this is the best possible solution as far as Big (O) notation is concerned...
def solution(A):
B = [0, 0, 0, 0, 0]
for i in range (len(A)):
if A[i] == "Cardiology":
... | Find the maximum frequency of an element in a given Array |
This is the solution I have come up with but I'm unsure whether this is the best possible solution as far as Big (O) notation is concerned...
def solution(A):
B = [0, 0, 0, 0, 0]
for i in range (len(A)):
if A[i] == "Cardiology":
B[0] += 1
elif A[i] == "Neurology":
B[1] +... | [
"Because you know all of the possible values, you could use a dict with department names as keys and counts as values.\nYou could initialize it as:\ndepartments = {\"Cardiology\": 0, \"Neurology\": 0, \"Orthopaedics\": 0, \"Gynaecology\": 0, \"Oncology\": 0}\n\nAs a style suggestion, since you're iterating over the... | [
0,
0,
0
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0074564755_performance_python.txt |
Q:
How to fill missing text values with NA while scraping?
I am using beautifulsoup to create two dataframes of unique classes with text.
The first dataframe has a few missing values that is messing up the alignment in rows when I join them. I tried to use an if not statement but I still get error: get_text() is empt... | How to fill missing text values with NA while scraping? | I am using beautifulsoup to create two dataframes of unique classes with text.
The first dataframe has a few missing values that is messing up the alignment in rows when I join them. I tried to use an if not statement but I still get error: get_text() is empty.
soup = bs(response.text, 'html5lib')
for x in ... | [
"Avoid calling .get_text(strip=True) in your condition, cause you have to check if the element itself is available:\nif not x.find(\"span\", {\"class\": \"search_line_a__ details_table_data\"}):\n ...\n\nor\n A = x.find(\"span\", {\"class\": \"search_line_a__ details_table_data\"}).get_text(strip=True) if x.find... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074564440_beautifulsoup_python_web_scraping.txt |
Q:
How to use link to JPG as media content in message.edit_media method in aoigram, if it requests JSON object
I'm making test bot using aiogram now and i faced a problem.
I want to edit message media, but i only have a link to an image, and when i try to use an 'edit_media' method aiogram tells me that it can't pars... | How to use link to JPG as media content in message.edit_media method in aoigram, if it requests JSON object | I'm making test bot using aiogram now and i faced a problem.
I want to edit message media, but i only have a link to an image, and when i try to use an 'edit_media' method aiogram tells me that it can't parse JSON object.
(error)
In documentation said that 'media' parameter must be 'A JSON-serialized object for a new m... | [
"Found a solution. Needed to use InputMediaPhoto type:\nphoto = types.input_media.InputMediaPhoto(item_info[3])\nawait query.message.edit_media(media=photo)\n\nAnd all together code looks like this:\n@dp.callback_query_handler(kb.item_nav_cb.filter(action='next'))\nasync def item_next_cb_handler(query: types.Callba... | [
0
] | [] | [] | [
"aiogram",
"python",
"telegram",
"telegram_bot"
] | stackoverflow_0074564885_aiogram_python_telegram_telegram_bot.txt |
Q:
Runtime error: asyncio.run cannot be called from running event loop
import discord
import os
import schedule
import time
import requests
from bs4 import BeautifulSoup
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
client = commands.Bot(int... | Runtime error: asyncio.run cannot be called from running event loop | import discord
import os
import schedule
import time
import requests
from bs4 import BeautifulSoup
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
client = commands.Bot(intents=intents, command_prefix="!")
@client.event
async def on_ready():
pri... | [
"You can't call asyncio.run() inside of itself. Client.run() already calls this, so you can't use Client.run() in an async main.\nIf you only want to log something to Discord, you don't need a Client/Bot at all. This can just be done using a simple Webhook.\nAlso, Client.run() is not async, so you can't await it...... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074563899_discord_discord.py_python.txt |
Q:
Sorting students and what exams they are doing
I have a list of tuples and the tuples look like this (2, 11) which means exam 2 must be taken by student 11. The exams are numbered from 0 to however many exams there are and the same with students. I need to produce a 2D list where the first list is the exams the 0t... | Sorting students and what exams they are doing | I have a list of tuples and the tuples look like this (2, 11) which means exam 2 must be taken by student 11. The exams are numbered from 0 to however many exams there are and the same with students. I need to produce a 2D list where the first list is the exams the 0th student is taking and the second list is the exams... | [
"The exams is a list. In python, lists are passed by reference, so when you are appending exams to examsEachStudentsIsDoing you are just appending a reference to the exams in the examsEachStudentsIsDoing.\nAt the end of the loop, for last student, the exams is set to [0,2], hence for all the entries in examsEachStu... | [
1,
0,
0,
0
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0074564509_list_list_comprehension_python.txt |
Q:
Translate curl command to python requests.get
I have the following curl command which I can use to retrieve a list of users from a specific group in PagerDuty:
curl -H "Accept: application/vnd.pagerduty+json;version=2" -H "Authorization: Token token=xxx" -X GET --data-urlencode "team_ids[]=abc" 'https://api.pagerd... | Translate curl command to python requests.get | I have the following curl command which I can use to retrieve a list of users from a specific group in PagerDuty:
curl -H "Accept: application/vnd.pagerduty+json;version=2" -H "Authorization: Token token=xxx" -X GET --data-urlencode "team_ids[]=abc" 'https://api.pagerduty.com/users'
How can I translate this exact comm... | [
"Simply omit --data-urlencode from your params:\nimport requests\n\nparams = {\n 'team_ids[]':\"abc\",\n \"offset\": '0',\n}\nheaders = {\n 'Accept': 'application/vnd.pagerduty+json;version=2',\n 'Authorization': 'Token token=xxx',\n}\n\nresponse = requests.get('https://api.pagerduty.com/users', params=... | [
1,
0
] | [] | [] | [
"pagerduty",
"python",
"python_requests"
] | stackoverflow_0074564792_pagerduty_python_python_requests.txt |
Q:
How to select only specific defines in a SWIG interface?
i have a C header file with many defines for registers, and in my Python SWIG interface i only want to expose a few. My C header looks like this (just with many more defines):
#define REG_1 0x0001
#define REG_2 0x0002
#define REG_3 0x0003
Let's say in my ge... | How to select only specific defines in a SWIG interface? | i have a C header file with many defines for registers, and in my Python SWIG interface i only want to expose a few. My C header looks like this (just with many more defines):
#define REG_1 0x0001
#define REG_2 0x0002
#define REG_3 0x0003
Let's say in my generated Python module if I want to have all defines accessible... | [
"The only way I know of is to be repetitive and declare exactly what you want to expose:\n%module myheader\n%{\n#include myheader.h\n%}\n\n#define REG_1 0x0001\n\n",
"You can achieve this using the advanced renaming support of SWIG.\nGiven the demo header file (defs.h):\n#define WRAP_ME_1 1\n#define WRAP_ME_2 2\n... | [
0,
0
] | [] | [] | [
"c",
"header_files",
"python",
"swig"
] | stackoverflow_0074385357_c_header_files_python_swig.txt |
Q:
Seg Fault from dictionary initialization Python
So I am working on a project that deals with a large number of vehicles and transmissions between those vehicles. I have a working code that works well for small numbers of vehicles, but when I start using large numbers ~500 vehicles then the program will seg fault a... | Seg Fault from dictionary initialization Python | So I am working on a project that deals with a large number of vehicles and transmissions between those vehicles. I have a working code that works well for small numbers of vehicles, but when I start using large numbers ~500 vehicles then the program will seg fault about half the time. I have backtraced the seg fault u... | [
"The problem ended up being a error in the python to C++ interface. It only happens when there is a large number of calls, it seems to lose its place in memory and when it accesses that point again hits an error. I ended up just writing the complete code in C++ which solves the problem. If anyone else reads this it... | [
0
] | [] | [] | [
"dictionary",
"list_initialization",
"python",
"segmentation_fault"
] | stackoverflow_0072112587_dictionary_list_initialization_python_segmentation_fault.txt |
Q:
Pip: connection broken by 'ProtocolError'
I am trying to install a package with pip in a fresh virtual environment on Ubuntu 20.04.5, but I keep getting the following warning, when I run pip a second time. The installation of the package fails after the first attempt.
WARNING: Retrying (Retry(total=4, connect=None... | Pip: connection broken by 'ProtocolError' | I am trying to install a package with pip in a fresh virtual environment on Ubuntu 20.04.5, but I keep getting the following warning, when I run pip a second time. The installation of the package fails after the first attempt.
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after... | [
"I have encountered the same issue. Turns out I did some debugging by setting the environment variable SSLKEYLOGFILE to a file that I deleted afterwards, and pip won't work if it's unable to access or create this file.\nRemoving the environment variable will fix it\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"python_3.x"
] | stackoverflow_0073726324_pip_python_python_3.x.txt |
Q:
Draw outside a windows bounds with pygame
I'm looking to create something that interacts with your desktop in some way with pygame.
What I want to do is draw something outside of the pygame window, as in anywhere on the screen.
Is this possible at all?
What would be more helpful, if you can do it at all, is if you... | Draw outside a windows bounds with pygame | I'm looking to create something that interacts with your desktop in some way with pygame.
What I want to do is draw something outside of the pygame window, as in anywhere on the screen.
Is this possible at all?
What would be more helpful, if you can do it at all, is if you can draw without a window even on the screen.
| [
"I had an idea that to create a transparent fullscreen window That Can Be Displayed on The Desktop. \nimport pygame\nfrom win32api import GetSystemMetrics\nimport win32api\nimport win32con\nimport win32gui\n\npygame.init()\nscreen = pygame.display.set_mode((GetSystemMetrics(0),GetSystemMetrics(1)),pygame.FULLSCREEN... | [
1
] | [] | [] | [
"desktop",
"pygame",
"python",
"screen"
] | stackoverflow_0074564181_desktop_pygame_python_screen.txt |
Q:
How can I prevent Opencv from using a wrong path after installation / ImportError
There are two other Python versions on the system: 2.7 and - in a different environment - 3.7 including Opencv installed.
For some reasons I need another python version (3.8). Therefore I installed python 3.8 in a separate environmen... | How can I prevent Opencv from using a wrong path after installation / ImportError | There are two other Python versions on the system: 2.7 and - in a different environment - 3.7 including Opencv installed.
For some reasons I need another python version (3.8). Therefore I installed python 3.8 in a separate environment and after activating this environment I installed Opencv in this environment:
I open ... | [
"Do not install multiple package variants of OpenCV.\nInstall exactly one variant.\nRemove them all, then install one of them.\nAll of them contain the base modules.\nUse only the packages on PyPI (installable with pip). Those are official packages.\n"
] | [
0
] | [] | [] | [
"conda",
"installation",
"opencv",
"pip",
"python"
] | stackoverflow_0074564371_conda_installation_opencv_pip_python.txt |
Q:
How to use a column in dataframe as dictionary key value?
Suppose there is a dataset.
Let's say that the dataset has a column A which contains city names like "New York", "California", or "Florida"
now we have a dictionary like
my_dict = {"New York":1, "California":2, "Florida":3}
So I need to generate a column B... | How to use a column in dataframe as dictionary key value? | Suppose there is a dataset.
Let's say that the dataset has a column A which contains city names like "New York", "California", or "Florida"
now we have a dictionary like
my_dict = {"New York":1, "California":2, "Florida":3}
So I need to generate a column B such that if column A has a row value "New York", then column ... | [
"This seems rather contrived but works:\ndf = pd.DataFrame([my_dict]).stack().reset_index()\ndf.drop(df.columns[[0]], axis=1, inplace=True)\ndf.columns = ['A', 'B']\n\nand gives\n A B\n0 New York 1\n1 California 2\n2 Florida 3\n\n",
"Method 1\nimport pandas as pd\n\nmy_dict = {\"New York\":... | [
0,
0
] | [] | [] | [
"dataframe",
"dictionary",
"jupyter_notebook",
"python"
] | stackoverflow_0074564846_dataframe_dictionary_jupyter_notebook_python.txt |
Q:
Reduce steps in this simple maze puzzle?
Video Puzzle
Current code:
for i in range(6,0,-2):
Spaceship.step(2)
Dev.step(i)
for idk in range(3):
Dev.turnRight()
Dev.step(i*2)
Dev.turnRight()
Dev.step(i)
In this puzzle the objective is to get all the item (blue thing). With 6 line... | Reduce steps in this simple maze puzzle? |
Video Puzzle
Current code:
for i in range(6,0,-2):
Spaceship.step(2)
Dev.step(i)
for idk in range(3):
Dev.turnRight()
Dev.step(i*2)
Dev.turnRight()
Dev.step(i)
In this puzzle the objective is to get all the item (blue thing). With 6 line of code, and I'm currently at 8 line of code... | [
"This is a possible solution in only 6 lines:\nfor i in range(6, 0, -2):\n Spaceship.step(2)\n for k, j in enumerate([1, 2, 2, 2, 1]):\n Dev.step(i * j)\n if k != 4:\n Dev.turnRight()\n\nThe idea is to group all steps of the robot in a list in order to do a nested loop and turn only i... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074562403_python.txt |
Q:
How to write a text file from a dictionary in Python with values going from a list to string?
I am trying to write a text file from a dictionary in which the dictionary values is a list that I want to convert to a string with "," separators, for example:
["string1","string2","string3"] --> "string1,string2,string3... | How to write a text file from a dictionary in Python with values going from a list to string? | I am trying to write a text file from a dictionary in which the dictionary values is a list that I want to convert to a string with "," separators, for example:
["string1","string2","string3"] --> "string1,string2,string3"
When the list becomes one string I want to write its key (also a string with : separator) with i... | [
"You can use str.join to join the dictionary values with ,:\ndct = {\n \"key1\": [\"string1\", \"string2\", \"string3\"],\n \"key2\": [\"string4\", \"string5\", \"string6\"],\n \"key3\": [\"string7\", \"string8\", \"string9\"],\n}\n\nwith open(\"output.txt\", \"w\") as f_out:\n for k, v in dct.items():\... | [
3
] | [] | [] | [
"dictionary",
"io",
"python",
"text"
] | stackoverflow_0074565326_dictionary_io_python_text.txt |
Q:
Append element to 2D array
How can I append an element to first or second element of a numpy array in python?
My code does not work.
I did like this:
my_num = np.array([[],[]])
my_num[0] = np.append(my_num[0],6)
print(my_num[0])
But my_num is empty.
A:
Maybe try this:
my_num[0] = np.append(my_num[0],np.array([6... | Append element to 2D array | How can I append an element to first or second element of a numpy array in python?
My code does not work.
I did like this:
my_num = np.array([[],[]])
my_num[0] = np.append(my_num[0],6)
print(my_num[0])
But my_num is empty.
| [
"Maybe try this:\nmy_num[0] = np.append(my_num[0],np.array([6]))\n\nThe second argument in append must be the same \"shape\" as the first (i.e., an array). See Numpy docs here.\n"
] | [
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074565257_arrays_numpy_python.txt |
Q:
my simple_interest function is returning 0 and i'm not sure why even though i think my math is correct
i'm trying to make a program that calculates simple interest and the function i made to calculate the interest returns 0 when i run it and i don't know what the problem is
`year = int(input("Enter years: "))
mon... | my simple_interest function is returning 0 and i'm not sure why even though i think my math is correct | i'm trying to make a program that calculates simple interest and the function i made to calculate the interest returns 0 when i run it and i don't know what the problem is
`year = int(input("Enter years: "))
month = int(input("Enter months: "))
days = int(input("Enter days: "))
totalYears = float()
interest = float(... | [
"The variable TotalYears in the get_time function is not the same as the variable TotalYears referenced outside the function. When you want to assign a value to TotalYears in get_time, you need to declare \"Global\" to let python know that you are referencing the variable outside the scope of the get_time function.... | [
1,
1,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074565063_math_python.txt |
Q:
Cannot locate pygubu-designer.exe after instalation
I'm trying to install pygubu-designer, but the 'pygubu-designer.exe' never shows up in any of the folders after the installation process.
https://github.com/alejandroautalan/pygubu
https://github.com/alejandroautalan/pygubu-designer
I did:
pip install pygubu
cmd
... | Cannot locate pygubu-designer.exe after instalation | I'm trying to install pygubu-designer, but the 'pygubu-designer.exe' never shows up in any of the folders after the installation process.
https://github.com/alejandroautalan/pygubu
https://github.com/alejandroautalan/pygubu-designer
I did:
pip install pygubu
cmd
pip install pygubu-designer
cmd
I have couple of folders ... | [
"Could not locate pygubudesigner within my python310\\Scripts folder and any other but the cmd command mentioned in this issue: https://github.com/alejandroautalan/pygubu/issues/222 worked for me\npython -m pygubudesigner\n\n"
] | [
0
] | [] | [] | [
"pygubu",
"python",
"tkinter"
] | stackoverflow_0074533716_pygubu_python_tkinter.txt |
Q:
How to measure a text element in matplotlib
I need to lay out a table full of text boxes using matplotlib. It should be obvious how to do this: create a gridspec for the table members, fill in each element of the grid, take the maximum heights and widths of the elements in the grid, change the appropriate height a... | How to measure a text element in matplotlib | I need to lay out a table full of text boxes using matplotlib. It should be obvious how to do this: create a gridspec for the table members, fill in each element of the grid, take the maximum heights and widths of the elements in the grid, change the appropriate height and widths of the grid columns and rows. Easy peas... | [
"There doesn't seem to be any way to do this directly, but there's a way to do it indirectly: instead of using a text box, use TextPath, transform it to Axis coordinates, and then use the differences between min and max on each coordinate. (See https://matplotlib.org/stable/gallery/text_labels_and_annotations/demo_... | [
0
] | [] | [] | [
"matplotlib",
"python",
"text_rendering"
] | stackoverflow_0074493627_matplotlib_python_text_rendering.txt |
Q:
OpenCV Contrib Python missing functions in ximgproc
I cant find certain function when I list everything inside opencv-contrib ximgproc module. What am I missing?
Here is a "pip freeze" output:
Here is a list from dir(cv2.ximgproc):
Now, when I look at the source code OpenCV.sln I can see that some of the functio... | OpenCV Contrib Python missing functions in ximgproc | I cant find certain function when I list everything inside opencv-contrib ximgproc module. What am I missing?
Here is a "pip freeze" output:
Here is a list from dir(cv2.ximgproc):
Now, when I look at the source code OpenCV.sln I can see that some of the functions of "ximgproc" are not listed here and some are, for e... | [
"Not every (C++) API of OpenCV is exposed to Python.\nThe main modules are mostly covered. Stuff in contrib is more likely to lack annotations for Python bindings.\nIf any bindings are missing, you can DIY and try slapping a CV_EXPORTS_W to the declaration. There's a description of this somewhere... just copy what ... | [
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074563602_opencv_python.txt |
Q:
Creating a list for column names of dataframe while changing multiple values into one value
I have a dataframe named df which is the combination of multiple .csv files, so for certain index in each file there are several column names. Lets say column names are A, B, C, D, E for different .csv files. I want to chan... | Creating a list for column names of dataframe while changing multiple values into one value | I have a dataframe named df which is the combination of multiple .csv files, so for certain index in each file there are several column names. Lets say column names are A, B, C, D, E for different .csv files. I want to change all A, B, C, D, E s in column names into F.
I tried this;
df = pd.read_csv(path + config['fil... | [
"define col names first:\nto_replace_cols=['A','B','C','D','E']\n\ndf.columns = ['F' if i in to_replace_cols else i for i in df.columns]\n\n#one line\ndf.columns = ['F' if i in ['A','B','C','D','E'] else i for i in df.columns]\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"multiple_columns",
"pandas",
"python",
"replace"
] | stackoverflow_0074564796_dataframe_multiple_columns_pandas_python_replace.txt |
Q:
Create New Dict from Existing DIct Using List of Values
I have a list of values and want to create a new dictionary from an existing dictionary using the key/value pairs that correspond to the values in the list. I can't find a Stackoverflow answer that covers this.
example_list = [1, 2, 3, 4, 5]
original_dict = ... | Create New Dict from Existing DIct Using List of Values | I have a list of values and want to create a new dictionary from an existing dictionary using the key/value pairs that correspond to the values in the list. I can't find a Stackoverflow answer that covers this.
example_list = [1, 2, 3, 4, 5]
original_dict = {"a": 1, "b": 2, "c": 9, "d": 2, "e": 6, "f": 1}
desired_dic... | [
"You can use dict comprehension or you can use filter.\nexample_list = [1, 2, 3, 4, 5]\n\noriginal_dict = {\"a\": 1, \"b\": 2, \"c\": 9, \"d\": 2, \"e\": 6, \"f\": 1}\n\ndesired_dict = {key: value for key, value in original_dict.items() if value in example_list}\n\n# Option_2\ndesired_dict = dict(filter(lambda x: x... | [
2,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074565298_dictionary_list_python.txt |
Q:
Find the area between two curves plotted in matplotlib (fill_between area)
I have a list of x and y values for two curves, both having weird shapes, and I don't have a function for any of them. I need to do two things:
Plot it and shade the area between the curves like the image below.
Find the total area of this... | Find the area between two curves plotted in matplotlib (fill_between area) | I have a list of x and y values for two curves, both having weird shapes, and I don't have a function for any of them. I need to do two things:
Plot it and shade the area between the curves like the image below.
Find the total area of this shaded region between the curves.
I'm able to plot and shade the area between ... | [
"The area calculation is straightforward in blocks where the two curves don't intersect: thats the trapezium as has been pointed out above. If they intersect, then you create two triangles between x[i] and x[i+1], and you should add the area of the two. If you want to do it directly, you should handle the two cases... | [
6,
5,
4,
3,
2,
0
] | [] | [] | [
"area",
"matplotlib",
"python",
"scipy"
] | stackoverflow_0025439243_area_matplotlib_python_scipy.txt |
Q:
What is the best way to scrape multiple urls and tackle pagination problem (load more button)?
The main link is (https://www.europarl.europa.eu/meps/en/197818/BILLY_KELLEHER/meetings/past#detailedcardmep)
My code shows me only fist pages but I need to browse all of them for all the links (I have more than 100 link... | What is the best way to scrape multiple urls and tackle pagination problem (load more button)? | The main link is (https://www.europarl.europa.eu/meps/en/197818/BILLY_KELLEHER/meetings/past#detailedcardmep)
My code shows me only fist pages but I need to browse all of them for all the links (I have more than 100 links)
from bs4 import BeautifulSoup
import requests
page=0
list=[]
isHaveNextPage=True
links = [(f... | [
"The problem is: you may be incrementing the page number, but the format string has already been made. Updating page doesn't update the string, at all. You have to keep remaking the string with the new data.\nInstead of this: f\"https://...&page={page}...\" \ndo this: \"https://...&page=%i...\"\nThen do this:\nfor ... | [
1,
0
] | [] | [] | [
"html",
"javascript",
"python",
"web_scraping"
] | stackoverflow_0074563973_html_javascript_python_web_scraping.txt |
Q:
How to get pygame bar width with method?
enter image description hereHow I can get width of pygame bar? I mean the gray taskbar. I've tried to to following but it does not work properly.
import pygame
pygame.init()
disp = pygame.display.set_mode((640, 480))
disp.fill((0, 0, 0))
pygame.display.flip()
title = 'text... | How to get pygame bar width with method? | enter image description hereHow I can get width of pygame bar? I mean the gray taskbar. I've tried to to following but it does not work properly.
import pygame
pygame.init()
disp = pygame.display.set_mode((640, 480))
disp.fill((0, 0, 0))
pygame.display.flip()
title = 'text'
pygame.display.set_caption(title)
while Tru... | [
"You Can get the the bar width Beacause\nBar Width = Screen width.\nand this code is how i put the text in the center\nimport pygame\n\npygame.init()\nScreenWidth,ScreenHight = 640, 480\ndisp = pygame.display.set_mode((ScreenWidth, ScreenHight))\ndisp.fill((0, 0, 0))\npygame.display.flip()\ntitle = 'textdd'\nspaces... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074563349_pygame_python.txt |
Q:
Tesseract OCR extraction
I am building an OCR model where I have performed object detection on the images. I am calling the detection function to detect bounding boxes. I am cropping the images basis bounding boxes. The challenge I am facing is the cropped images are too small for tesseract for data extraction and... | Tesseract OCR extraction | I am building an OCR model where I have performed object detection on the images. I am calling the detection function to detect bounding boxes. I am cropping the images basis bounding boxes. The challenge I am facing is the cropped images are too small for tesseract for data extraction and it is impacting the accuracy ... | [
"Have you tried OCRing and then cropping, rather than the reverse? It may take longer but it is likely going to be more accurate.\nI have a lot of experience using ocrmypdf with PDFPlumber and Regex to parse PDF documents into spreadsheets and this is the process I generally follow:\nimport pandas as pd\nimport os\... | [
0
] | [] | [] | [
"ocr",
"python",
"python_imaging_library",
"tensorflow",
"tesseract"
] | stackoverflow_0074564535_ocr_python_python_imaging_library_tensorflow_tesseract.txt |
Q:
Is there a way I can modify some lines in site html code so it marks the checkbox?
So, there's a site I'm trying to parse so it can automatically raising my offers every two hours.
The site designed in that way that you have to mark with checkboxes the lots you want to raise.
Somehow in html code the checkbox does... | Is there a way I can modify some lines in site html code so it marks the checkbox? | So, there's a site I'm trying to parse so it can automatically raising my offers every two hours.
The site designed in that way that you have to mark with checkboxes the lots you want to raise.
Somehow in html code the checkbox doesn't have value, instead it looks like this:
I have to click it manually via using
wait.u... | [
"You can't use By.CLASS_NAME here since it has no class.\nYou can use:\n\n\nBy.CSS_SELECTOR to find by CSS selectors\n\nchbVal = '613' # in case you need be able to change this\n\n(By.CSS_SELECTOR, f'label > input[type=\"checkbox\"][value=\"{chbVal}\"][checked=\"\"]') # for checked\n\n(By.CSS_SELECTOR, f'label > in... | [
2
] | [] | [] | [
"beautifulsoup",
"html",
"parsing",
"python",
"selenium"
] | stackoverflow_0074565163_beautifulsoup_html_parsing_python_selenium.txt |
Q:
How to properly check if a number is a prime number
Hey so i have this function to check if a number is a prime number
def is_prime(n):
flag = True
for i in range(2, n ):
if (n % i) == 0:
flag = False
return flag
print(is_prime(1))
However when i test the number 1, it skips the fo... | How to properly check if a number is a prime number | Hey so i have this function to check if a number is a prime number
def is_prime(n):
flag = True
for i in range(2, n ):
if (n % i) == 0:
flag = False
return flag
print(is_prime(1))
However when i test the number 1, it skips the for loop and returns True which isn't correct because 1 is... | [
"You can first start by checking if n is greater than 1 the code should proceed, else it should return False. If n passes the first condition, only then the code can proceed to verify if n is indeed prime or not.\ndef is_prime(n):\n flag = True\n if n > 1:\n for i in range(2, n ):\n if (n % ... | [
1,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074564053_function_python.txt |
Q:
Python Getting Last evalues of a loop
I have a definition and it repeats with a while loop. I want to pull the penultimate value of m and ar from the operations that occur in the definition in each loop.
To do this, I opened an out file and tried to print the second-to-last element in each while loop.
But when I l... | Python Getting Last evalues of a loop | I have a definition and it repeats with a while loop. I want to pull the penultimate value of m and ar from the operations that occur in the definition in each loop.
To do this, I opened an out file and tried to print the second-to-last element in each while loop.
But when I look at this file as output, there is only 1... | [
"You open a new out file every time main() is called.\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nf = open(\"radial.out\",\"w\") # outside main()\ndef main(rho_c):\n \n ### Constants\n \n pi = 3.1415926535897\n gamma =5./3.\n m_sun = 2.998e33\n K = 1e10\n P_c = K*rho_c**gamma\n ... | [
1
] | [] | [] | [
"append",
"function",
"loops",
"python"
] | stackoverflow_0074565373_append_function_loops_python.txt |
Q:
How do I get my code to continue looping?
I'm trying to make the code repeat the line "player name invalid" and ask for the input repetively until the input is "player 1". How do i do that?
correct_n="player 1"
while True:
Name1 = input ("Enter Your Name: ")
if Name1 == correct_n:
cp = 'password'
... | How do I get my code to continue looping? | I'm trying to make the code repeat the line "player name invalid" and ask for the input repetively until the input is "player 1". How do i do that?
correct_n="player 1"
while True:
Name1 = input ("Enter Your Name: ")
if Name1 == correct_n:
cp = 'password'
while True:
password= input(... | [
"Because you have two while loops, it is not possible to use break to exit both of them. Instead, you should separate the loops so that the name loop runs until the name is correct, and then the password loop runs until the password matches.\ncorrect_n=\"player 1\"\nwhile True:\n Name1 = input(\"Enter Your Name:... | [
0
] | [
"Solution:\nwhile input('Enter your name: ') != 'player 1': print('Player name invalid')\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074565551_python.txt |
Q:
How to make this dictionary/key python code work
I am trying to make a function that takes a threshold and determines which names from a csv file of song names and their lyrics that contain human names and the function
should create a csv file named outputfile that contains the number of distinct names, the name o... | How to make this dictionary/key python code work | I am trying to make a function that takes a threshold and determines which names from a csv file of song names and their lyrics that contain human names and the function
should create a csv file named outputfile that contains the number of distinct names, the name of
the song and the artist.
import csv
def findName(th... | [
"What's the rationale for not using Pandas here?\nNot sure I fully understand your question, but I'm thinking something like:\ndf = pd.read_csv('allNames.csv')\n\n#partition df after threshold\ndf['index'] = df.index\n\ndef partition_return(threshold, df):\n df = df.loc[df['index'] >= threshold].reset_index(drop... | [
0
] | [] | [] | [
"csv",
"dictionary",
"function",
"key",
"python"
] | stackoverflow_0074565501_csv_dictionary_function_key_python.txt |
Q:
reshape pandas data frame: duplicated rows to columns, with textual data
I have a dataframe like this:
INDEX_COL col1
A Random Text
B Some more random text
C more stuff
A Blah
B Blah, ... | reshape pandas data frame: duplicated rows to columns, with textual data | I have a dataframe like this:
INDEX_COL col1
A Random Text
B Some more random text
C more stuff
A Blah
B Blah, Blah
C Yet more stuff
A erm
B ... | [
"You can use agg(list) and then explode the whole dataframe:\noutput = df.groupby('INDEX_COL').agg(list).T.apply(pd.Series.explode)\n\noutput:\nINDEX_COL A B C\ncol1 Random Text Some more random text more stuff\ncol1 Blah Blah, Blah Yet more stuff\ncol1 ... | [
2,
0
] | [] | [] | [
"data_wrangling",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074565364_data_wrangling_dataframe_pandas_python.txt |
Q:
Trying to create a class that creates a turtle
I'm trying to create a class where I can build a turtle so I can call that multiple times and get a bunch of turtles. I'm not sure exactly how to create a turtle with the name = turtle.Turtle(). It gives me an error but doesn't say why.
import turtle
class CreateTurtl... | Trying to create a class that creates a turtle | I'm trying to create a class where I can build a turtle so I can call that multiple times and get a bunch of turtles. I'm not sure exactly how to create a turtle with the name = turtle.Turtle(). It gives me an error but doesn't say why.
import turtle
class CreateTurtle:
# initialize constructor
def __init__(self, name... | [
"If you want to make many turtle from a class of Turtle, you should make class and call it with input and assign it to your variable. This is the minimal working example:\nclass Turtle:\n # initialize constructor\n def __init__(self, name, color, pensize, shape):\n self.name = name\n self.color ... | [
0,
0,
0
] | [] | [] | [
"python",
"turtle_graphics"
] | stackoverflow_0070072276_python_turtle_graphics.txt |
Q:
How to get a directory path in pyqt6 via QFileDialog?
Name: PyQt6
Version: 6.1.0
OS: Ubuntu 20.04.5 LTS
from PyQt6.QtWidgets import QFileDialog
HOME_PATH = os.getenv("HOME")
...
dir_path = QFileDialog.getExistingDirectory(
parent=self,
caption="Select directory",
directory=HOME_PATH,
options=QFi... | How to get a directory path in pyqt6 via QFileDialog? | Name: PyQt6
Version: 6.1.0
OS: Ubuntu 20.04.5 LTS
from PyQt6.QtWidgets import QFileDialog
HOME_PATH = os.getenv("HOME")
...
dir_path = QFileDialog.getExistingDirectory(
parent=self,
caption="Select directory",
directory=HOME_PATH,
options=QFileDialog.Option.ShowDirsOnly,
)
directory and options do n... | [
"The original question was mainly related to the new way PyQt6 uses Enums, which now always require the full namespace: until PyQt5, the syntax Class.FlagName was sufficient, but PyQt6 now requires Class.EnumName.FlagName.\nThe other issue is probably related to QTBUG-88709 and is part of a long series of issues th... | [
1
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0074557955_pyqt_python.txt |
Q:
Python Function to add column items to list based around criteria from a different column
[Code Sample] (https://i.stack.imgur.com/kx1UH.png)
I have created this code to show the percentage of missing values for each of these columns, how can I now create a new variable that contains only the column names for the ... | Python Function to add column items to list based around criteria from a different column | [Code Sample] (https://i.stack.imgur.com/kx1UH.png)
I have created this code to show the percentage of missing values for each of these columns, how can I now create a new variable that contains only the column names for the columns with over X% missing values?
Assumed it would be an if statement but not too sure what ... | [
"Something like this should work:\nthreshold = 1 #can be whatever you want\ndf.loc[df['percent_missing'] >= threshold, column_name]\n\nIf you want it as a list just do:\nlist(df.loc[df['percent_missing'] >= threshold, column_name])\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074564235_dataframe_jupyter_notebook_pandas_python.txt |
Q:
Is there any way to make dictionary key,value pairs to tuple?
I need to convert this dictionary:
{'A': 0, 'B': 1290, 'C': 515, 'D': 600}
Into this test case:
(A : 0) - (B : 1290) - (C : 515) - (D : 600)
This is how I derive my dictionary
def stock_list(list_of_art, list_of_cat):
new_dictionary = {}
... | Is there any way to make dictionary key,value pairs to tuple? | I need to convert this dictionary:
{'A': 0, 'B': 1290, 'C': 515, 'D': 600}
Into this test case:
(A : 0) - (B : 1290) - (C : 515) - (D : 600)
This is how I derive my dictionary
def stock_list(list_of_art, list_of_cat):
new_dictionary = {}
numbers = []
for character in list_of_cat:
... | [
"Just iterate over the keys and values of your dictionary, and format them into a string.\nd = {'A': 0, 'B': 1290, 'C': 515, 'D': 600}\n\nprint(\" - \".join(f'({k} : {v})' for k,v in d.items()))\n\n#(A : 0) - (B : 1290) - (C : 515) - (D : 600)\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074565285_python.txt |
Q:
Error when calculating singular values of a matrix
I'm trying to calculate the singular values of a matrix using 2 methods. The matrix I'm using is the red channel of a sunflower image. Here's the image if you need it.
The first method is using SVD:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
... | Error when calculating singular values of a matrix | I'm trying to calculate the singular values of a matrix using 2 methods. The matrix I'm using is the red channel of a sunflower image. Here's the image if you need it.
The first method is using SVD:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
A = mpimg.imread('sunflower.jpeg')
R... | [
"When I run your code after casting R to be .astype(np.int64), and round the values to 6 decimal places, and compare the two return values as set, I get that they return the same values. I suspect that one or more of\n\nUnexpected int overflow\nFloating point rounding errors\nOrder of the singular values\n\nis the ... | [
0
] | [] | [] | [
"image",
"numpy",
"python",
"svd"
] | stackoverflow_0074565226_image_numpy_python_svd.txt |
Q:
ValueError: `decode_predictions` expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 26)
I am using a model trained by myself to translate braille digits into plain text. As you can see this is a classification problem with 26 classes, one for each letter in the ... | ValueError: `decode_predictions` expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 26) | I am using a model trained by myself to translate braille digits into plain text. As you can see this is a classification problem with 26 classes, one for each letter in the alphabet.
This is the dataset that I used to train my model: https://www.kaggle.com/datasets/shanks0465/braille-character-dataset
This is how I a... | [
"If we take a look at what the prediction object acually is we can see that it has 26 values. These values are the propabiity for each letter that the model predicts:\n\nSo we need a way to map the prediction value to the respective letter.\nA simple way to do this could to create a list of all the 26 possible lett... | [
0
] | [] | [] | [
"conv_neural_network",
"keras",
"machine_learning",
"pre_trained_model",
"python"
] | stackoverflow_0074561274_conv_neural_network_keras_machine_learning_pre_trained_model_python.txt |
Q:
How to add numbers for one to 8 on the left and righ side of this function
Hi I have problem i dont knbwo how to add numbers order 1 to 8 on the left side and right side of this function. And another problem is there is always showing none when I print it I dont know why I thouth it was beacouse my function was em... | How to add numbers for one to 8 on the left and righ side of this function | Hi I have problem i dont knbwo how to add numbers order 1 to 8 on the left side and right side of this function. And another problem is there is always showing none when I print it I dont know why I thouth it was beacouse my function was empty but that din't help . So what can I do with this thank you very much.
| [
"Ok, I shortened a bit your code. Mainly replaced multiple if conditions with a replacement map, that you can pass to your function.\nsachy = [[0, 1, 0, 1, 0, 1, 0, 1],[1, 0, 1, 0, 1, 0, 1, 0],[0, 1, 0, 1, 0, 1, 0, 1],[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0],[0, 2, 0, 2, 0, 2, 0, 2],[2, 0, 2, 0, 2, 0, 2, 0... | [
0,
0
] | [] | [] | [
"function",
"nonetype",
"numbers",
"python"
] | stackoverflow_0074565450_function_nonetype_numbers_python.txt |
Q:
How to find the position/index of a particular file in a directory?
I am new to python.I have a list of file names contained in a folder and I want to build a function which can search and return the position of a particular file in the list of files.
A:
Suppose, you have a list of string list_of_names=["Abc","D... | How to find the position/index of a particular file in a directory? | I am new to python.I have a list of file names contained in a folder and I want to build a function which can search and return the position of a particular file in the list of files.
| [
"Suppose, you have a list of string list_of_names=[\"Abc\",\"Def\",\"Ghi\",\"Jkl\"].\nYou can use list.index() method to find the index of a particular string as given below:\n>> list_of_names.index(\"Abc\")\n>> 0\n>> list_of_names.index(\"Jkl\")\n>> 3\n\n",
"please do this\nnames = [filename1,filename2,............ | [
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0040675412_python.txt |
Q:
Find difference between two data frames
I have two data frames df1 and df2, where df2 is a subset of df1. How do I get a new data frame (df3) which is the difference between the two data frames?
In other word, a data frame that has all the rows/columns in df1 that are not in df2?
A:
By using drop_duplicates
pd.c... | Find difference between two data frames | I have two data frames df1 and df2, where df2 is a subset of df1. How do I get a new data frame (df3) which is the difference between the two data frames?
In other word, a data frame that has all the rows/columns in df1 that are not in df2?
| [
"By using drop_duplicates\npd.concat([df1,df2]).drop_duplicates(keep=False)\n\n\nUpdate :\n\nThe above method only works for those data frames that don't already have duplicates themselves. For example:\n\ndf1=pd.DataFrame({'A':[1,2,3,3],'B':[2,3,4,4]})\ndf2=pd.DataFrame({'A':[1],'B':[2]})\n\nIt will output like be... | [
291,
70,
22,
12,
7,
7,
5,
3,
3,
2,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0048647534_dataframe_pandas_python.txt |
Q:
Pandas: How to Squash Multiple Rows into One Row with More Columns
I'm looking for a way to convert 5 rows in a pandas dataframe into one row with 5 times the amount of columns (so I have the same information, just squashed into one row). Let me explain:
I'm working with hockey game statistics. Currently, there ar... | Pandas: How to Squash Multiple Rows into One Row with More Columns | I'm looking for a way to convert 5 rows in a pandas dataframe into one row with 5 times the amount of columns (so I have the same information, just squashed into one row). Let me explain:
I'm working with hockey game statistics. Currently, there are 5 rows representing the same game in different situations, each with 1... | [
"It sounds like what you are looking for is pd.get_dummies()\ncols = df.columns\n\n#get dummies\ndf1 = pd.get_dummies(df, columns = ['situation'])\n\n#drop all columns from existing df, including original col passed into get dummies\ndf1.drop(cols, axis=1 , inplace=True)\n\n#add dummy cols to original df\ndf = pd.c... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074565718_dataframe_pandas_python.txt |
Q:
how to resolve this "inf" problem with python code
i have a problem with this python code for inverting a Number
like Nb = 358 ---> inv = 853
but in the end i got 'inf' msg from the prog , and its runs normally in C language
def envers(Nb):
inv = 0
cond = True
while cond:
s = Nb % 10
inv = (inv*10)+ s
... | how to resolve this "inf" problem with python code | i have a problem with this python code for inverting a Number
like Nb = 358 ---> inv = 853
but in the end i got 'inf' msg from the prog , and its runs normally in C language
def envers(Nb):
inv = 0
cond = True
while cond:
s = Nb % 10
inv = (inv*10)+ s
Nb = Nb/10
if Nb == 0:
cond = False
retu... | [
"This is likely much easier to do via string manipulation, which has a friendly and simple syntax (which are a major reason to choose to use Python)\n>>> int(input(\"enter a number to reverse: \")[::-1])\nenter a number to reverse: 1234\n4321\n\nHow this works\n\ninput() returns a string\nstrings are iterable and [... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074565689_python.txt |
Q:
JSON Parsing with python from Rethink database [Python]
Im trying to retrieve data from a database named RethinkDB, they output JSON when called with r.db("Databasename").table("tablename").insert([{ "id or primary key": line}]).run(), when doing so it outputs [{'id': 'ValueInRowOfid\n'}] and I want to parse that ... | JSON Parsing with python from Rethink database [Python] | Im trying to retrieve data from a database named RethinkDB, they output JSON when called with r.db("Databasename").table("tablename").insert([{ "id or primary key": line}]).run(), when doing so it outputs [{'id': 'ValueInRowOfid\n'}] and I want to parse that to just the value eg. "ValueInRowOfid". Ive tried with JSON i... | [
"It looks like it's returning a dictionary ({}) inside a list ([]) of one element.\nTry:\ngetvalue = r.db(\"Databasename\").table(\"tablename\").sample(1).run()\n\nprint(getvalue[0]['id'])\n\n"
] | [
0
] | [] | [] | [
"database",
"json",
"parsing",
"python",
"rethinkdb_python"
] | stackoverflow_0074565449_database_json_parsing_python_rethinkdb_python.txt |
Q:
Download file with dcc.send_bytes
I am trying to create and download a pptx presentation with pptx and python dash. Although the file is created without an error, there are no slides created in the presentation.
Thanks in advance.
import dash
import dash_core_components as dcc
import dash_html_components as html
i... | Download file with dcc.send_bytes | I am trying to create and download a pptx presentation with pptx and python dash. Although the file is created without an error, there are no slides created in the presentation.
Thanks in advance.
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
... | [
"You can use this code instead:\ndef to_pptx(bytes_io):\n prs = Presentation()\n title_slide_layout = prs.slide_layouts[0]\n slide = prs.slides.add_slide(title_slide_layout)\n title = slide.shapes.title\n subtitle = slide.placeholders[1] \n title.text = \"Hello, World!\"\n subtitle.text = \"... | [
1
] | [] | [] | [
"download",
"plotly_dash",
"python"
] | stackoverflow_0074565356_download_plotly_dash_python.txt |
Q:
Preventing "Warning Potential Security Risk Ahead" in selenium python Firefox
So when using selenium python with firefox I need to prevent this:
This is what I have already tried
profile = webdriver.FirefoxOptions()
profile.accept_insecure_certs = True
profile.accept_untrusted_certs = True
firefox = webdriver.Fir... | Preventing "Warning Potential Security Risk Ahead" in selenium python Firefox | So when using selenium python with firefox I need to prevent this:
This is what I have already tried
profile = webdriver.FirefoxOptions()
profile.accept_insecure_certs = True
profile.accept_untrusted_certs = True
firefox = webdriver.Firefox(executable_path=utils.str_master_dir('geckodriver.exe'), options=profile)
...
... | [
"This should work:\nfrom selenium import webdriver\ncapabilities = webdriver.DesiredCapabilities().FIREFOX\ncapabilities['acceptInsecureCerts'] = True\ncapabilities['marionette'] = True\ndriver = webdriver.Firefox(desired_capabilities=capabilities)\n\nYou can also create a custom Firefox profile as described here\n... | [
1
] | [] | [] | [
"firefox_marionette",
"python",
"selenium",
"selenium_firefoxdriver"
] | stackoverflow_0074565289_firefox_marionette_python_selenium_selenium_firefoxdriver.txt |
Q:
How to get maximum values in a row and call the proper name of the appropriate column with pandas
I want to get the maximum values in a row and print the value and the name of the appropriate column.
s1 = pd.Series([5, 6, 7, 10, 12, 6, 8, 55, 9])
s2 = pd.Series([7, 8, 9, 16, 13, 8, 2, 11, 7])
df = pd.DataFrame([l... | How to get maximum values in a row and call the proper name of the appropriate column with pandas | I want to get the maximum values in a row and print the value and the name of the appropriate column.
s1 = pd.Series([5, 6, 7, 10, 12, 6, 8, 55, 9])
s2 = pd.Series([7, 8, 9, 16, 13, 8, 2, 11, 7])
df = pd.DataFrame([list(s1), list(s2)], columns = ["A", "B", "C", "D", "E", "F", "G", "H", "I"])
A B C D E F ... | [
"Sorting is relatively expensive (O(n*log(n)) complexity).\nUse nlargest:\nout = df.loc[0].nlargest(4)\n\nOutput:\nH 55\nE 12\nD 10\nI 9\nName: 0, dtype: int64\n\n",
"You can sort and then take the top N values:\n>>> df.loc[0].sort_values(ascending=False).iloc[:4]\nH 55\nE 12\nD 10\nI 9\... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074564823_pandas_python.txt |
Q:
Average on overlapping windows in Python
I'm trying to compute a moving average but with a set step size between each average. For example, if I was computing the average of a 4 element window every 2 elements:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
This should produce the average of [1, 2, 3, 4], [3, 4, 5, 6], [... | Average on overlapping windows in Python | I'm trying to compute a moving average but with a set step size between each average. For example, if I was computing the average of a 4 element window every 2 elements:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
This should produce the average of [1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10].
window_avg = [2.5... | [
"One way to compute the average of a sliding window across a list in Python is to use a list comprehension. You can use\n>>> range(0, len(data), 2)\n[0, 2, 4, 6, 8]\n\nto get the starting indices of each window, and then numpy's mean function to take the average of each window. See the demo below:\n>>> import numpy... | [
2,
1,
0
] | [] | [] | [
"moving_average",
"python",
"python_itertools"
] | stackoverflow_0021097039_moving_average_python_python_itertools.txt |
Q:
How to find type hints for psycopg2 functions
How can one find what type hints to use when annotating my python code for to package functions eg. What will thepsycopg2.connect return so that I can put it in place of ??? eg:
def sql_connect(sql_config: dict = None) -> ???:
db = psycopg2.connect(
... | How to find type hints for psycopg2 functions | How can one find what type hints to use when annotating my python code for to package functions eg. What will thepsycopg2.connect return so that I can put it in place of ??? eg:
def sql_connect(sql_config: dict = None) -> ???:
db = psycopg2.connect(
host=sql_config["host"],
port=sql_conf... | [
"Just use the psycopg2.connection as the type hint.\nAlso check with type(sql_connect())\n"
] | [
0
] | [] | [] | [
"python",
"python_typing",
"type_hinting"
] | stackoverflow_0074564998_python_python_typing_type_hinting.txt |
Q:
" no error message for this problem how could i make the could run correctly"?
the problem is that After choosing the name of the city, the code is freezing , he code is:
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
... | " no error message for this problem how could i make the could run correctly"? | the problem is that After choosing the name of the city, the code is freezing , he code is:
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks ... | [
"One easy fix would be to add the breakin an else block (Though not the best solution this will get you going):\nwhile True:\n if city not in CITY_DATA.keys():\n print(\"invaild city name please try again/n: \")\n city = input( \"please choose a city from (chicago , new york city , wash... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074565676_dataframe_pandas_python.txt |
Q:
Why is Anaconda Navigator not opening?
I have trouble with my anaconda3 navigator. I am using it with Python 3 and jupyter notebook. Today, because I had trouble with installing some packages, I updated everything and it worked fine. A few hours later, my anaconda navigator is not opening and when I open the Power... | Why is Anaconda Navigator not opening? | I have trouble with my anaconda3 navigator. I am using it with Python 3 and jupyter notebook. Today, because I had trouble with installing some packages, I updated everything and it worked fine. A few hours later, my anaconda navigator is not opening and when I open the PowerShell prompt I get the following error:
and... | [
"I got the solution, okay it is not really a solution,but better than nothing :)\nYou just have to uninstall Anaconda completely from your computer, also every folder with Anaconda things. Then you have to install it completely new, as if you never had Anaconda on your computer. For me, that helped - everything goe... | [
0,
0
] | [] | [] | [
"anaconda",
"conda",
"jupyter_notebook",
"powershell",
"python"
] | stackoverflow_0061688021_anaconda_conda_jupyter_notebook_powershell_python.txt |
Q:
return items from dictionary not as tuple
I have an excel file and I accumulate thre values for each fruit sort with each other.
So I do it like this:
def calulate_total_fruit_NorthMidSouth():
import openpyxl
import tabula
excelWorkbook = openpyxl.load_workbook(path, data_only=True)
sheet_factuu... | return items from dictionary not as tuple | I have an excel file and I accumulate thre values for each fruit sort with each other.
So I do it like this:
def calulate_total_fruit_NorthMidSouth():
import openpyxl
import tabula
excelWorkbook = openpyxl.load_workbook(path, data_only=True)
sheet_factuur = excelWorkbook['Facturen ']
new_list =[]... | [
"Try something like this:\ndef f():\n x = {'a': 1, 'b': 2, 'c': 3}\n return '\\n'.join(f'{a} {b}' for a, b in x.items())\n\nprint(f())\n# a 1\n# b 2\n# c 3\n\n",
"Not sure if this is the best way to solve this problem but you could add this to your code before printing:\nmylist = list(fruit_sums.items())\nf... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074565707_python.txt |
Q:
Checking if a file exist in S3 bucket or not?
I am trying to check if a file exist or not in a S3 bucket. I am currently using boto3 library in python.
I am using below code to check it exist or not -
file_name = 'random_name'
s3_client = boto3.client('s3')
result = s3_client.list_objects_v2(Bucket=b... | Checking if a file exist in S3 bucket or not? | I am trying to check if a file exist or not in a S3 bucket. I am currently using boto3 library in python.
I am using below code to check it exist or not -
file_name = 'random_name'
s3_client = boto3.client('s3')
result = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=file_name)
if 'Contents' in... | [
"Compare the keys directly using standard Python string comprehensions.\nThe answers to this question go further into detail on this boto3 file_upload does it check if file exists\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"boto3",
"python",
"python_3.x"
] | stackoverflow_0074565946_amazon_s3_amazon_web_services_boto3_python_python_3.x.txt |
Q:
How to perform split/merge/melt with Python and polars?
I have a data transformation problem where the original data consists of "blocks" of three rows of data, where the first row denotes a 'parent' and the two others are related children. A minimum working example looks like this:
import polars as pl
df_original... | How to perform split/merge/melt with Python and polars? | I have a data transformation problem where the original data consists of "blocks" of three rows of data, where the first row denotes a 'parent' and the two others are related children. A minimum working example looks like this:
import polars as pl
df_original = pl.DataFrame(
{
'Order ID': ['A', 'foo', 'bar'... | [
"Here's how I've attempted it:\nfill the nulls in the Parent Order ID column and use that to .groupby()\n>>> columns = [\"Order ID\", \"Direction\", \"Price\", \"Some Value\"]\n... names = pl.col(\"^Name .*$\") # All name columns\n... quotes = pl.col(\"^Quote .*$\") # All quote columns\n... (\n... df_origi... | [
1
] | [] | [] | [
"dataframe",
"join",
"melt",
"python",
"python_polars"
] | stackoverflow_0074562243_dataframe_join_melt_python_python_polars.txt |
Q:
Modifying pandas row value based on its length
I have a column in my pandas dataframe with the following values that represent hours worked in a week.
0 40
1 40h / week
2 46.25h/week on average
3 11
I would like to check every row, and ... | Modifying pandas row value based on its length | I have a column in my pandas dataframe with the following values that represent hours worked in a week.
0 40
1 40h / week
2 46.25h/week on average
3 11
I would like to check every row, and if the length of the value is larger than 2 digits -... | [
"It looks like you could ensure having h after the number:\ndf['Hours_per_week'].str.extract(r'(\\d{2}\\.?\\d*)h', expand=False)\n\nOutput:\n0 NaN\n1 40\n2 46.25\n3 NaN\nName: Hours_per_week, dtype: object\n\n",
"Assuming the series data are strings, try this:\ndf['Hours_per_week'].str.extract(... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074565953_dataframe_pandas_python.txt |
Q:
Python Pandas read_html multi_index table?
I am not sure if it should be called multi index. Here is the page I am trying to get data from:
Azure product availability by region.
There is hierarchy level: class "category-row" --> "service-row" --> "capability-row" .
pandas.read_html give me a flat table, with all v... | Python Pandas read_html multi_index table? | I am not sure if it should be called multi index. Here is the page I am trying to get data from:
Azure product availability by region.
There is hierarchy level: class "category-row" --> "service-row" --> "capability-row" .
pandas.read_html give me a flat table, with all values from three classes. Is there a way to get ... | [
"Not sure, if it fit your needs, but it is also take the table contents - May provide an expected result.\nExample\n...\ndata=[]\nsoup = BeautifulSoup(driver.page_source)\n\nfor r in soup.select('table tr.service-row:has([data-region-slug])'):\n row = [\n r.find_previous('tr', attrs={'class':'category-row... | [
1
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074563937_beautifulsoup_pandas_python_web_scraping.txt |
Q:
Make Source and Target column based on consecutive rows
I have the following problem
Person 1001 accomplishes activity A and then activity C (which follows activity A)
I need to move consecutive rows to target columns
df = pd.DataFrame([[1001, 'A'], [1001,'C'], [1004, 'D'],[1005, 'C'],
[1005,'D... | Make Source and Target column based on consecutive rows | I have the following problem
Person 1001 accomplishes activity A and then activity C (which follows activity A)
I need to move consecutive rows to target columns
df = pd.DataFrame([[1001, 'A'], [1001,'C'], [1004, 'D'],[1005, 'C'],
[1005,'D'], [1010, 'A'],[1010,'D'],[1010,'F']], columns=['CustomerNr'... | [
"you can use:\ndf['Target']=df['Activity'].shift(-1)\ndf['prev_CustomerNr']=df['CustomerNr'].shift(-1)\nprint(df)\n'''\n CustomerNr Activity Target prev_CustomerNr\n0 1001 A C 1001.0\n1 1001 C D 1004.0\n2 1004 D C 1005.0\n3 ... | [
1
] | [] | [] | [
"dataframe",
"linked_list",
"python"
] | stackoverflow_0074565119_dataframe_linked_list_python.txt |
Q:
All items overwritten by the last item when using pipeline to save picture in scrapy
I am new to scrapy and not a native English speaker, so sorry in advance if I make some silly mistakes or cannot make my point clear.I want to scrapy the information and covers of rock albums from a Chinese website (music.douban.... | All items overwritten by the last item when using pipeline to save picture in scrapy | I am new to scrapy and not a native English speaker, so sorry in advance if I make some silly mistakes or cannot make my point clear.I want to scrapy the information and covers of rock albums from a Chinese website (music.douban.com/tag/%E6%91%87%E6%BB%9A?start=0&type=T). When I am just using xpath to get non-picture ... | [
"Item fields are mutable, and right now in your parse method you create 1 item at the beginning of your method body and use that same item when you yield each of the results. What you need to do is create a unique item on each iteration of your for loop.\nFor example:\n def parse(self,response):\n albums... | [
0
] | [] | [] | [
"python",
"python_3.x",
"scrapy",
"web_crawler"
] | stackoverflow_0074565693_python_python_3.x_scrapy_web_crawler.txt |
Q:
The Labels on my window don't appear when the correct button is pressed
I have a quiz that I made in python (Tkinter). For some reason, when I press a button, I doesn't show the label. I have no more info about this, because it does not even give me an error message.
here is the (bad) code:
from random import *
d... | The Labels on my window don't appear when the correct button is pressed | I have a quiz that I made in python (Tkinter). For some reason, when I press a button, I doesn't show the label. I have no more info about this, because it does not even give me an error message.
here is the (bad) code:
from random import *
def submit():
ca = 0
ca = randint(1, 3)
if ca == 1:
if val... | [
"Your code is incomplete.\nBut the first thing that jumps out at me is that you have:\nval1 = IntVar()\n\nand in\ndef submit():\n\nyou're checking if:\nif val1 == 1:\n\nBut val1 is an IntVar Tkinter variable, which you would check with:\nval1.get()\n\nIn your code, your conditionals always fail, because val1 will n... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074566050_python_tkinter.txt |
Q:
How to solve inverse transform using MixMaxScaler on a single value
I'm trying to perform the inverse of MixMaxScaler from a single value. However, I get this error:
ValueError: Expected 2D array, got scalar array instead:
array=0.16019679677629.
Reshape your data either using array.reshape(-1, 1) if your data has... | How to solve inverse transform using MixMaxScaler on a single value | I'm trying to perform the inverse of MixMaxScaler from a single value. However, I get this error:
ValueError: Expected 2D array, got scalar array instead:
array=0.16019679677629.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.... | [
"You need to reshape it correctly:\npred = np.array([0.16])\n\nminmaxscaler_targets = MinMaxScaler()\n\nminmaxscaler_targets.fit(pred.reshape(-1,1))\nminmaxscaler_targets.inverse_transform(pred.reshape(-1,1))\n# array([[0.32]])\n\n"
] | [
0
] | [] | [] | [
"inverse",
"minmax",
"python",
"scikit_learn"
] | stackoverflow_0074563197_inverse_minmax_python_scikit_learn.txt |
Q:
How to create nested type of data in Python?
I want to make sure, that one of the arguments, passed when class creation is of certain type. Here is an example:
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class ListItems:
items: list | str | int | Li... | How to create nested type of data in Python? | I want to make sure, that one of the arguments, passed when class creation is of certain type. Here is an example:
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class ListItems:
items: list | str | int | ListItems
class PList:
def __init__(self, nam... | [
" def __init__(self, name: str, items: ListItems):\nthe items: ListItems bit is saying that items should be a ListItems object, it's not passing through the logic of what ListItems is doing, it's literally just comparing what type it is.\ni don't have much experience with typing, but i think you're looking for i... | [
0,
0
] | [
"Specifying input type isn't a thing in Python the way it is in TypeScript. I'm not sure you even need the class listItems. Just use a simple if statement in your init method.\nclass PList:\n def __init__(self, name, items):\n self.type = 'list'\n self.name = name\n if type(items) is list or type(items) i... | [
-1
] | [
"oop",
"python"
] | stackoverflow_0074565861_oop_python.txt |
Q:
How to go back to a point of code within a While True Loop in python?
I need my input 3 to be validated, therefore it needs to return back to input 3 if the "else block" is activated. also "if block" must go back to input 1 thats why ive put continue.
while True:
input 1
input 2
process
input 3
... | How to go back to a point of code within a While True Loop in python? | I need my input 3 to be validated, therefore it needs to return back to input 3 if the "else block" is activated. also "if block" must go back to input 1 thats why ive put continue.
while True:
input 1
input 2
process
input 3
if result == "c';
continue
elif result == "e"
... | [
"You can use flag variable to cope with nested loops. Such as:\nflag = True\nwhile flag == True:\n input('1')\n input('2')\n while True:\n result = input('3')\n if result == 'c':\n break\n elif result == 'e':\n flag= False\n break\n else:\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074565269_python.txt |
Q:
discord.py - edit the interaction message after a timeout in discord.ui.Select
How can I access the interaction message and edit it?
discord.ui.Select
class SearchMenu(discord.ui.Select):
def __init__(self, ctx, bot, data):
self.ctx = ctx
self.bot = bot
self.data = data
self.pl... | discord.py - edit the interaction message after a timeout in discord.ui.Select | How can I access the interaction message and edit it?
discord.ui.Select
class SearchMenu(discord.ui.Select):
def __init__(self, ctx, bot, data):
self.ctx = ctx
self.bot = bot
self.data = data
self.player = Player
values = []
for index, track in enumerate(self.data[:... | [
"You're trying to ask the View to send a message, which is not a method in discord.ui.View.\nYou could defer the response and don't let it timeout and allow the user to try again?\nasync def interaction_check(self, interaction: discord.Interaction):\n if interaction.user != self.ctx.author:\n embe... | [
0,
-1
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_3.x"
] | stackoverflow_0069265909_discord_discord.py_python_python_3.x.txt |
Q:
What is Pytorch equivalent of Pandas groupby.apply(list)?
I have the following pytorch tensor long_format:
tensor([[ 1., 1.],
[ 1., 2.],
[ 1., 3.],
[ 1., 4.],
[ 0., 5.],
[ 0., 6.],
[ 0., 7.],
[ 1., 8.],
[ 0., 9.],
[ 0., 10.]])
I woul... | What is Pytorch equivalent of Pandas groupby.apply(list)? | I have the following pytorch tensor long_format:
tensor([[ 1., 1.],
[ 1., 2.],
[ 1., 3.],
[ 1., 4.],
[ 0., 5.],
[ 0., 6.],
[ 0., 7.],
[ 1., 8.],
[ 0., 9.],
[ 0., 10.]])
I would like to groupby the first column and store the 2nd column as ... | [
"You can use this code:\nimport torch\nx = torch.tensor([[ 1., 1.],\n [ 1., 2.],\n [ 1., 3.],\n [ 1., 4.],\n [ 0., 5.],\n [ 0., 6.],\n [ 0., 7.],\n [ 1., 8.],\n [ 0., 9.],\n [ 0., 10.]])\n\nresult = [x[x[:,0]==i][:,1] for i in x[:,0].unique()]... | [
1
] | [] | [] | [
"pandas",
"python",
"pytorch"
] | stackoverflow_0074564843_pandas_python_pytorch.txt |
Q:
Pulp Python problem setting constraints when summing values in a column
Hi this is my first question here so go easy on me if I format things incorrectly.
I'm trying to model a table where each value is either 1 or 0.
I'd like to determine whether the sum of a column is 0 or not 0, then check how many columns are ... | Pulp Python problem setting constraints when summing values in a column | Hi this is my first question here so go easy on me if I format things incorrectly.
I'm trying to model a table where each value is either 1 or 0.
I'd like to determine whether the sum of a column is 0 or not 0, then check how many columns are > 0.
The underlying problem I'm trying to solve is appointment scheduling, wh... | [
"Your question is clear, but the setup on your LP isn’t real clear. We can come back to that.\nYou are getting the error because you used an if statement in your summation. That isn’t legal. When pulp makes the math model to solve, the value of the variables are not known, so we cannot use if statements in the for... | [
0,
0
] | [] | [] | [
"constraints",
"pulp",
"python"
] | stackoverflow_0074559219_constraints_pulp_python.txt |
Q:
Is there a way to send message to telegram with python without using a bot?
Sorry, if it's a dumb question.
I just want to know for sure yes, or no.
A:
It is possible to create a self-bot for telegram.
To get an inspiration on how to do it, I would suggest you dig into this GitHub repository.
| Is there a way to send message to telegram with python without using a bot? | Sorry, if it's a dumb question.
I just want to know for sure yes, or no.
| [
"It is possible to create a self-bot for telegram.\nTo get an inspiration on how to do it, I would suggest you dig into this GitHub repository.\n"
] | [
0
] | [] | [] | [
"python",
"telegram"
] | stackoverflow_0074564528_python_telegram.txt |
Q:
HTML Calendar Appearing Under Footer
I've created an HTML Calendar for my django app. However when I add it to one of my templates it adds it underneath my footer. I'm not understanding why this would happen.
{% extends "bf_app/app_bases/app_base.html" %}
{% block main %}
{% include "bf_app/overviews/overview... | HTML Calendar Appearing Under Footer | I've created an HTML Calendar for my django app. However when I add it to one of my templates it adds it underneath my footer. I'm not understanding why this would happen.
{% extends "bf_app/app_bases/app_base.html" %}
{% block main %}
{% include "bf_app/overviews/overview_nav.html" %}
<div class="flex justify... | [
"I had the same problem, using huiwenteo calendar tutorial.\nThis weird behavior is making Calendar class, more specific the formatmonth method. Because its returning calendar table, without closing html tag. So in your cal/utils.py file you should add cal += f'</table>\\n' to formatmonth method, before returning ... | [
0
] | [] | [] | [
"django",
"django_templates",
"html",
"python"
] | stackoverflow_0073341019_django_django_templates_html_python.txt |
Q:
unable to get the expected answer for string palindrom
Every time i am geting else condition as true. If i pass input string as "ama" then code should give input string is palindrom. But i am getting string is not palindrom.
Input: ami
output: ami
Expected:string is palindrom
Input: amit
output: tima
Expected:stri... | unable to get the expected answer for string palindrom | Every time i am geting else condition as true. If i pass input string as "ama" then code should give input string is palindrom. But i am getting string is not palindrom.
Input: ami
output: ami
Expected:string is palindrom
Input: amit
output: tima
Expected:string is n palindrom
def str_rev (input_str):
print("input_... | [
"A palindrome is a word that is the same backwards and forwards. Therefore ami is not a palindrome.\n",
"At a quick glance, your formatting is off, but I think your problem is with white space. Change:\nrev_str = \" \"\n\nto\nrev_str = \"\"\n\nto get rid of that extra white space.\nIn fact, you can trim your stri... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074566125_python.txt |
Q:
How to get the growth between two rows
I'm trying to get the growth (in %) between two values at different period. Here is how my DataFrame looks like:
sessionSource dateRange activeUsers
0 instagram.com current 5
1 instagram.com previous 0
2 l.instagram.com current 83... | How to get the growth between two rows | I'm trying to get the growth (in %) between two values at different period. Here is how my DataFrame looks like:
sessionSource dateRange activeUsers
0 instagram.com current 5
1 instagram.com previous 0
2 l.instagram.com current 83
3 l.instagram.com previous 11
4 ... | [
"Assuming you literally just need the percent change between current and previous and current/previous are in the correct order, you can just group the data based on the source and get the percent change of the group\n.Use the pandas.Series.pct_change() method on the grouped object and you should be good.\n# sort v... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074566108_dataframe_pandas_python.txt |
Q:
Time elapsed since first log for each user
I'm trying to calculate the time difference between all the logs of a user and the first log of that same user. There are users with several logs.
The dataframe looks like this:
16 00000021601 2022-08-23 17:12:04
20 00000021601 2022-08-23 17:12:04
21 0000003131... | Time elapsed since first log for each user | I'm trying to calculate the time difference between all the logs of a user and the first log of that same user. There are users with several logs.
The dataframe looks like this:
16 00000021601 2022-08-23 17:12:04
20 00000021601 2022-08-23 17:12:04
21 00000031313 2022-10-22 11:16:57
22 00000031313 20... | [
"You can try this code\nimport pandas as pd\n\ndates = ['2022-08-23 17:12:04',\n '2022-08-23 17:12:04',\n '2022-10-22 11:16:57',\n '2022-10-22 12:16:44',\n '2022-10-22 14:39:07',\n '2022-05-06 11:51:33',\n '2022-05-06 11:51:33',]\nids = [1,1,1,2,2,2,2]\ndf = pd.DataFr... | [
0
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074566047_dataframe_datetime_pandas_python.txt |
Q:
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid locator
so I'm trying to make this bot with selenium but when I'm trying to use the send keys func it doesn't work
I'm stuck on it for hours and I cant seem to find to solve the problem please if anyone has any idea I beg you t... | selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid locator | so I'm trying to make this bot with selenium but when I'm trying to use the send keys func it doesn't work
I'm stuck on it for hours and I cant seem to find to solve the problem please if anyone has any idea I beg you to help me thanks.
print(driver.title)
tos = driver.find_element("xpath", '//*[@id="pop"]/button')
tos... | [
"Try:\n# id instead of ID\nname = driver.find_element(\"id\", \"inpNick\") \n\n# or\nfrom selenium.webdriver.common.by import By\nname = driver.find_element(By.ID, \"inpNick\")\n\n",
"Instead driver.find_element(\"ID\", \"inpNick\") try\ndriver.find_element(By.ID, \"inpNick\")\n\nAlso, no need to add delays betw... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"webdriverwait",
"xpath"
] | stackoverflow_0074566182_python_selenium_selenium_webdriver_webdriverwait_xpath.txt |
Q:
How to parse and flatten nested JSON API response into tabular format
JSON structure:
{
"help": "https://data.boston.gov/api/3/action/help_show?name=datastore_search_sql",
"success": true,
"result": {
"records": [
{
"latitude": "42.38331999978103",
"p... | How to parse and flatten nested JSON API response into tabular format | JSON structure:
{
"help": "https://data.boston.gov/api/3/action/help_show?name=datastore_search_sql",
"success": true,
"result": {
"records": [
{
"latitude": "42.38331999978103",
"property_type": "Residential 1-family",
"neighborhood": "Cha... | [
"just use:\njson_data= response.json()\ndf=pd.json_normalize(json_data['result']['records'])\n\ndf\n\n| | latitude | property_type | neighborhood | description | year built | _full_text ... | [
0
] | [] | [] | [
"dictionary",
"flatten",
"json",
"json_normalize",
"python"
] | stackoverflow_0074564373_dictionary_flatten_json_json_normalize_python.txt |
Q:
pytest coverage 'if 0:' statement body not listed as a miss
Test marks the code as covered if the condition is 0 but as uncovered if the condition is a variable with value of zero.
I was trying a simple thing in pytest with coverage and I found this bug (?). I am not sure if I am missing something in how pytest or... | pytest coverage 'if 0:' statement body not listed as a miss | Test marks the code as covered if the condition is 0 but as uncovered if the condition is a variable with value of zero.
I was trying a simple thing in pytest with coverage and I found this bug (?). I am not sure if I am missing something in how pytest or python works.
Here bellow is my function
def dummy_func(a=0):
... | [
"So the answer to your question is that it's not a bug, it's expected behavior.\nFrom the coverage.py docs:\n\nAfter your program has been executed and the line numbers recorded,\ncoverage.py needs to determine what lines could have been executed.\nLuckily, compiled Python files (.pyc files) have a table of line\nn... | [
2
] | [] | [] | [
"code_coverage",
"pytest",
"python"
] | stackoverflow_0074564731_code_coverage_pytest_python.txt |
Q:
How to check user has put in correct number of arguments on command line in python
I'm trying to check that the user has entered two arguments on the command line - the iface name and passive for a type of scan - I thought the script would just exit if the wrong arguments entered but it still prints out the error ... | How to check user has put in correct number of arguments on command line in python | I'm trying to check that the user has entered two arguments on the command line - the iface name and passive for a type of scan - I thought the script would just exit if the wrong arguments entered but it still prints out the error message no matter how many arguments entered - what am I missing ?
import sys
import os
... | [
"sys.argv also returns the name of the python file. Try running:\nprint(sys.argv)\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074566228_python_python_3.x.txt |
Q:
Python nested Dictionaries to csv
I have a data set in this format:
data = { 'sensor1': {'units': 'x', 'values': [{'time': 17:00, 'value': 10},
{'time': 17:10, 'value': 12},
{'time': 17:20, 'value' :7}, ...]}
'sen... | Python nested Dictionaries to csv | I have a data set in this format:
data = { 'sensor1': {'units': 'x', 'values': [{'time': 17:00, 'value': 10},
{'time': 17:10, 'value': 12},
{'time': 17:20, 'value' :7}, ...]}
'sensor2': {'units': 'x', 'values': [{'time... | [
"You can use pandas to create a dataframe from your data and save it as CSV:\nimport pandas as pd\n\ndata = {\n \"sensor1\": {\n \"units\": \"x\",\n \"values\": [\n {\"time\": \"17:00\", \"value\": \"10\"},\n {\"time\": \"17:10\", \"value\": \"12\"},\n {\"time\": \"... | [
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074564045_dictionary_python.txt |
Q:
Python map() function with an existing list
might be a dumb question but why when I try to use map() function on an already existing list:
nums = [1,2,3,4,5]
result = map(lambda num: num+num , nums)
print(result)
it returns me: <map object at 0x7f41cef17130> , instead of my result;
on the contrary when I do this:... | Python map() function with an existing list | might be a dumb question but why when I try to use map() function on an already existing list:
nums = [1,2,3,4,5]
result = map(lambda num: num+num , nums)
print(result)
it returns me: <map object at 0x7f41cef17130> , instead of my result;
on the contrary when I do this:
nums = 1,2,3,4,5
result = list(map(lambda num: n... | [
"Others have already said this. In python you have a few datatypes that don't show the values directly and require another function. This is one of them. Others are a generator:\n(x for x in range(5))\n\n\n<generator object at ....>\n\nAnd zip:\nzip([1,2], [1,2])\n\n\n<zip at ....>\n\nWhat that means is basically ... | [
0
] | [] | [] | [
"list",
"map_function",
"python"
] | stackoverflow_0074566167_list_map_function_python.txt |
Q:
how to parse strings and apply them to dataframe
I have an excel table that use as reference for logical operators so I can join them later to apply a logical string to pandas dataframe.
dataframe
GOOD BAD UGLY
0 101 60 0
1 22 61 0
2 103 62 NaN
3 104 63 0
I can get values from the ... | how to parse strings and apply them to dataframe | I have an excel table that use as reference for logical operators so I can join them later to apply a logical string to pandas dataframe.
dataframe
GOOD BAD UGLY
0 101 60 0
1 22 61 0
2 103 62 NaN
3 104 63 0
I can get values from the excel sheet and append them into list. But How can par... | [
"You can create the full condition like this:\n>>> ' & '.join(f\"({f})\" for f in formulas)\n\"(df['GOOD'][0]>100) & (df['BAD'][1]>50) & (pd.isna(df['UGLY']))\"\n\nEach expression should be put in parentheses. Otherwise a > b & c > d will be parsed as a > (b & c) > d, not (a > b) & (c > d).\nThen eval it:\n>>> impo... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074566170_dataframe_pandas_python.txt |
Q:
How to explain the counter/map in this oneline code to count the frequency of a 2d array
count = defaultdict(int, sum(map(Counter, board), Counter()))
board is a 2d array: List[List[str]]
I can understand that this one-line code is to count the frequency of the board,
and we can write this way:
count = defaultdi... | How to explain the counter/map in this oneline code to count the frequency of a 2d array |
count = defaultdict(int, sum(map(Counter, board), Counter()))
board is a 2d array: List[List[str]]
I can understand that this one-line code is to count the frequency of the board,
and we can write this way:
count = defaultdict(int)
for i in range(len(board)):
for j in range(len(board[0]):
count[board[i][j... | [
"Let's say board is defined as such:\nboard = [[\"hello\", \"hello\"], [\"world\", \"hello\"]]\n\nThe call to map gives us:\n>>> list(map(Counter, board))\n[Counter({'hello': 2}), Counter({'world': 1, 'hello': 1})]\n\nWe can try to sum these counters, but we will get an error:\n>>> sum(map(Counter, board))\nTraceba... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0074566143_python.txt |
Q:
Merge datasets using pandas
Below I have code which was provided to me in order to join 2 datasets.
import pandas as pd
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
df= pd.read_csv("student/student-por.csv")
ds= pd.read_csv("student/student-mat.csv")
print("before merge")
print(df)
pri... | Merge datasets using pandas | Below I have code which was provided to me in order to join 2 datasets.
import pandas as pd
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
df= pd.read_csv("student/student-por.csv")
ds= pd.read_csv("student/student-mat.csv")
print("before merge")
print(df)
print(ds)
print("After merging:")
... | [
"Hi Hope you are doing well!\nThe error is happening because of the c symbol in the arguments of the merge function. Also merge function has a different signature and it doesn't have the argument by but instead it should be on, which accepts only the list of columns So in summary it should something similar to th... | [
0
] | [] | [] | [
"dataframe",
"dataset",
"pandas",
"python"
] | stackoverflow_0074562882_dataframe_dataset_pandas_python.txt |
Q:
How do you create cogs and what is the error here?
my main.py
import discord
from discord.ext import commands
import os
from secret import TOKEN
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix='$', intents=intents, case_insensitive=Tru... | How do you create cogs and what is the error here? | my main.py
import discord
from discord.ext import commands
import os
from secret import TOKEN
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix='$', intents=intents, case_insensitive=True, owner_id=262215934322671616)
@client.event
async de... | [
"\ncoroutine 'BotBase.load_extension' was never awaited\n\nThe error is telling you what the problem is (as errors usually do). load_extension is a coroutine and you're not awaiting it. Similarly, add_cog is also a coroutine that you're not awaiting, and your setup is not a coroutine while it should be.\nThe migrat... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074566202_discord_discord.py_python.txt |
Q:
Python3: Decoding an 'application/x-gzip' response with Requests
I'm using requests to download data from a website. The content is an EPG XML file packed in a compressed gz file. I've been googling and trying all night with no success.
This is the relevant snip of my current stage. I'v tried to change the encodin... | Python3: Decoding an 'application/x-gzip' response with Requests | I'm using requests to download data from a website. The content is an EPG XML file packed in a compressed gz file. I've been googling and trying all night with no success.
This is the relevant snip of my current stage. I'v tried to change the encoding to UTF-8 and ISO-8859-1, but it just gives me a different kind of no... | [
"Generally gzipped content is served as application/gzip. It seems requests doesn't know what to do with application/x-gzip, so you will have to decode it manually.\nimport gzip\n\nresult = gzip.decompress(response.content)\n\n"
] | [
0
] | [] | [] | [
"gzip",
"python",
"python_requests",
"xml"
] | stackoverflow_0074566359_gzip_python_python_requests_xml.txt |
Q:
Python with TKinter - how do you access data from an entry multiple times?
In this program, I have the user input their username into a login entry. Once they click the login button, the login_user() function is called to verify that their username exists in a .txt file.
I am trying to access the user's username i... | Python with TKinter - how do you access data from an entry multiple times? | In this program, I have the user input their username into a login entry. Once they click the login button, the login_user() function is called to verify that their username exists in a .txt file.
I am trying to access the user's username in a later part of the program, more specifically in this line:
welcomeLabel = tt... | [
"You have to call the get method of the entry after the user has had a chance to enter some data. Your code is trying to use the value about a millisecond after you create the entry widget.\nYou can do something like the following in the function that logs the user in:\nwelcomeLabel.configure(text=f\"Welcome {usern... | [
1,
0,
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0074566194_python_tkinter_tkinter_entry.txt |
Q:
How to retrieve Stripe Subscription using customer email
Given a customer's email address how do I access their subscriptions, specifically their subscription status. There is only 1 subscription service I provide, so any queries should only bring up one result.
e.g.
import stripe
def functionA(customer_email):... | How to retrieve Stripe Subscription using customer email | Given a customer's email address how do I access their subscriptions, specifically their subscription status. There is only 1 subscription service I provide, so any queries should only bring up one result.
e.g.
import stripe
def functionA(customer_email):
...
return customer_sub
sub = stripe.Subscription.r... | [
"First you need to get the customer ID, either using list (case-sensitive) or search (case insensitive):\nstripe.Customer.list(email=\"Test@example.com\")\nstripe.Customer.search(query=\"email:'test@example.com'\")\n\nthen you can list Subscriptions for that customer id:\nstripe.Subscription.list(customer=\"cus_123... | [
1
] | [] | [] | [
"python",
"stripe_payments"
] | stackoverflow_0074565120_python_stripe_payments.txt |
Q:
AWS Wrangler S3 reading parquet, writing to DynamoDB - Unsupported type numpy.ndarray
I am trying to read parquet into dataframe with AWS wrangler, while writing this data to DynamoDB its erroring out with unsupported type error - Unsupported type numpy.ndarray for value.......
wr.s3.read_parquet(path=s3_path, dat... | AWS Wrangler S3 reading parquet, writing to DynamoDB - Unsupported type numpy.ndarray | I am trying to read parquet into dataframe with AWS wrangler, while writing this data to DynamoDB its erroring out with unsupported type error - Unsupported type numpy.ndarray for value.......
wr.s3.read_parquet(path=s3_path, dataset=dataset, chunked=True)
and writing like
wr.dynamodb.put_df(df=df, table_name=table_... | [
"Finally able to get the answer, so it worked like this for me using tolist()-\ndf[\"key\"] = df[\"key\"].apply(lambda x: x.tolist())\n\nwr.dynamodb.put_df(df, \"test_table\") \n\n"
] | [
0
] | [] | [] | [
"amazon_dynamodb",
"amazon_web_services",
"aws_data_wrangler",
"numpy",
"python"
] | stackoverflow_0074549552_amazon_dynamodb_amazon_web_services_aws_data_wrangler_numpy_python.txt |
Q:
Extract most central area in a Binary Image
I am processing binary images, and was previously using this code to find the largest area in the binary image:
# Use the hue value to convert to binary
thresh = 20
thresh, thresh_img = cv2.threshold(h, thresh, 255, cv2.THRESH_BINARY)
cv2.imshow('thresh', thresh_img)
cv2... | Extract most central area in a Binary Image | I am processing binary images, and was previously using this code to find the largest area in the binary image:
# Use the hue value to convert to binary
thresh = 20
thresh, thresh_img = cv2.threshold(h, thresh, 255, cv2.THRESH_BINARY)
cv2.imshow('thresh', thresh_img)
cv2.waitKey(0)
cv2.destroyAllWindows() ... | [
"OpenCV comes with a point-polygon test function (for contours). It even gives a signed distance, if you ask for that.\nI'll find the contour that is closest to the center of the picture. That may be a contour actually overlapping the center of the picture.\nTimings, on my quadcore from 2012, give or take a millise... | [
4,
1
] | [] | [] | [
"binary_image",
"image_processing",
"opencv",
"python"
] | stackoverflow_0074564868_binary_image_image_processing_opencv_python.txt |
Q:
Selecting row from a Pandas DataFrame based on constraints
I have several datasets that I import as csv files and display them in a DataFrame in Pandas. The csv files are info about Covid updates.
The datasets has several columns relating to this, for example "country_region", "last_update" & "confirmed".
Let's sa... | Selecting row from a Pandas DataFrame based on constraints | I have several datasets that I import as csv files and display them in a DataFrame in Pandas. The csv files are info about Covid updates.
The datasets has several columns relating to this, for example "country_region", "last_update" & "confirmed".
Let's say I wanted to look up the confirmed cases of Covid for Germany.
... | [
"Something like this?\ndef filter(county_region_val, last_update_val, confirmed_val, df):\n df = df.loc[((df['county_region'] == county_region_val) & (df['last_update'] == last_update_val) & (df[''confirmed'] == confirmed_val)).reset_index(drop=True)\n return df\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074551104_dataframe_pandas_python.txt |
Q:
Binary String To Plaintext
I have a string which is like that "00100101 10010011 01010100". Every 8 bits there is a space and the string might be bigger. I want to convert it to plaintext with python3.
I am new in python and I tried some solutions I found here but without success.
A:
string = "00100101 10010011 ... | Binary String To Plaintext | I have a string which is like that "00100101 10010011 01010100". Every 8 bits there is a space and the string might be bigger. I want to convert it to plaintext with python3.
I am new in python and I tried some solutions I found here but without success.
| [
"string = \"00100101 10010011 01010100\"\nstring_list = string.split()\n\ndef bin2str(s):\n return ''.join([chr(int(s[i:i+8], 2)) for i in range(0, len(s), 8)])\n\nfor s in string_list:\n print(bin2str(s))\n\nWould solve your problem and print '%', '\\x93' and 'T'\n",
"I think this should work\nbits = \"001... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074566388_python.txt |
Q:
Getting "path" is not defined Pylance Error in my Flask app
This is my code in init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
DB_NAME = 'database.db'
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_... | Getting "path" is not defined Pylance Error in my Flask app | This is my code in init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
DB_NAME = 'database.db'
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
db.init_app(app)
from .vi... | [
"The problem was i didnt import path from os\nError Fix\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074566473_python.txt |
Q:
Django: html input type=input and checkbox
I have a problem with send data from input type='number' to django view.
I have a page with products, each of them has a checkbox and a quantity selection (input type='number')
<form action="{% url 'create-order' %}" method="POST">
{% csrf_token %}
<table class="t... | Django: html input type=input and checkbox | I have a problem with send data from input type='number' to django view.
I have a page with products, each of them has a checkbox and a quantity selection (input type='number')
<form action="{% url 'create-order' %}" method="POST">
{% csrf_token %}
<table class="table table-responsive table-borderless">
... | [
"<input class=\"input\" min=\"1\" value=1 type=\"number\" name=\"quantity\">\n\nThis tag basically ensures the value will be at least 1. Try\n <input class=\"input\" min=\"0\" value=0 type=\"number\" name=\"quantity\">\n\nFor the next part you need to match the correct item with its quantity and skip if the quan... | [
1
] | [] | [] | [
"checkbox",
"django",
"html",
"python"
] | stackoverflow_0074565401_checkbox_django_html_python.txt |
Q:
Manipulating column names in a multiindex dataframe
I converted the following dictionary to a dataframe:
dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}},
'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}}
d1 = defaultdict(dict)
for k,... | Manipulating column names in a multiindex dataframe | I converted the following dictionary to a dataframe:
dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}},
'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}}
d1 = defaultdict(dict)
for k, v in dic.items():
for k1, v1 in v.items():
f... | [
"Change this:\ndf.insert(loc=0, column='Mode', value='Website')\n\nto this:\ndf.insert(loc=0, column=('', 'Mode'), value='Website')\n\nthen your full code looks like this:\nimport pandas as pd\nfrom collections import defaultdict\n\ndic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':1... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074564504_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.