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:
Using math on 2 dictionary values together
Here is my code
AZcounties = {
"Maricopa" : "4,496,588",
"Pima" : "1,052,030",
"Pinal" : "449,557",
"Yavapai" : "242,253",
"Mohave" : "217,692",
"Yuma" : "206,990",
"Coconino" : "145,052"... | Using math on 2 dictionary values together | Here is my code
AZcounties = {
"Maricopa" : "4,496,588",
"Pima" : "1,052,030",
"Pinal" : "449,557",
"Yavapai" : "242,253",
"Mohave" : "217,692",
"Yuma" : "206,990",
"Coconino" : "145,052",
"Cochise" : "126,052",
... | [
"You can use the dict.get,\nvalue = int(AZcounties.get(county).replace(',', ''))\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074166870_python.txt |
Q:
how to generate per-pixel histogram from many images in numpy?
I have tens of thousands of images. I want to generate a histogram for each pixel. I have come up with the following code using NumPy to do this that works:
import numpy as np
import matplotlib.pyplot as plt
nimages = 1000
im_shape = (64,64)
nbins = 1... | how to generate per-pixel histogram from many images in numpy? | I have tens of thousands of images. I want to generate a histogram for each pixel. I have come up with the following code using NumPy to do this that works:
import numpy as np
import matplotlib.pyplot as plt
nimages = 1000
im_shape = (64,64)
nbins = 100
#predefine the histogram bins
hist_bins = np.linspace(0,1,nbins)
... | [
"You can vectorize it using np.meshgrid and providing indices for first, second and third dimension (the last dimension you already have).\ny_grid, x_grid = np.meshgrid(np.arange(64), np.arange(64))\n\nfor i in range(nimages):\n #create a simple image with normally distributed pixel values\n im = np.random.no... | [
0
] | [] | [] | [
"histogram",
"numpy",
"python",
"vectorization"
] | stackoverflow_0074159570_histogram_numpy_python_vectorization.txt |
Q:
How to add a text into a Rectangle?
I have a code that draws hundreds of small rectangles on top of an image :
The rectangles are instances of
matplotlib.patches.Rectangle
I'd like to put a text (actually a number) into these rectangles, I don't see a way to do that. matplotlib.text.Text seems to allow one... | How to add a text into a Rectangle? | I have a code that draws hundreds of small rectangles on top of an image :
The rectangles are instances of
matplotlib.patches.Rectangle
I'd like to put a text (actually a number) into these rectangles, I don't see a way to do that. matplotlib.text.Text seems to allow one to insert text surrounded by a rectangle... | [
"I think you need to use the annotate method of your axes object.\nYou can use properties of the rectangle to be smart about it. Here's a toy example:\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatch\n\nfig, ax = plt.subplots()\nrectangles = {'skinny' : mpatch.Rectangle((2,2), 8, 2),\n ... | [
44,
0
] | [] | [] | [
"label",
"matplotlib",
"python",
"rectangles"
] | stackoverflow_0014531346_label_matplotlib_python_rectangles.txt |
Q:
Python: List to Pandas DataFrame without duplicate values in column only
I have a List in python 3.x as follows:
print_hr()
ATMITMData('Bank Nifty')
print_hr()
print(bn_strikes)
print(tabulate(pd.DataFrame(bn_strikes), headers='keys', tablefmt='psql', showindex=False))
I get the list and the df like this:
List:
{... | Python: List to Pandas DataFrame without duplicate values in column only | I have a List in python 3.x as follows:
print_hr()
ATMITMData('Bank Nifty')
print_hr()
print(bn_strikes)
print(tabulate(pd.DataFrame(bn_strikes), headers='keys', tablefmt='psql', showindex=False))
I get the list and the df like this:
List:
{'ATM': 40800, 'ITM': [40700, 40600, 40500], 'OTM': [40900, 41000, 41100]}
DF... | [
"i have two solutions. First:\nimport pandas as pd\ndf=pd.DataFrame(bn_strikes)\ndf.loc[df.duplicated(['ATM']), 'ATM'] = \"\" # you can fill with np.nan instead of (\"\")\nprint(df)\n'''\n ATM ITM OTM\n0 40800 40700 40900\n1 40600 41000\n2 40500 41100\n\n'''\n\nsecond(taller... | [
1
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074166485_dataframe_python.txt |
Q:
How to prevent uploaded files from having the same name Flask Python
I am trying to build a website in python using flask that takes file uploads and saves them to a folder (called uploads). However, when two files with the same name are uploaded, the first one is overwritten by the last one. How can I prevent thi... | How to prevent uploaded files from having the same name Flask Python | I am trying to build a website in python using flask that takes file uploads and saves them to a folder (called uploads). However, when two files with the same name are uploaded, the first one is overwritten by the last one. How can I prevent this in a way that means that I don't lose any files? Would adding a timestam... | [
"You can generate an uuid and update the filename with it.\nYou can generate uuid like this,\nimport uuid\n\n... your code ..\nhash_value = uuid.uuid4().hex\nf.save(os.path.join(app.config['UPLOAD_FOLDER'], hash_value + secure_filename(f.filename)))\n\n"
] | [
0
] | [] | [] | [
"file_upload",
"flask",
"python"
] | stackoverflow_0074166962_file_upload_flask_python.txt |
Q:
Is there a way to retrieve all metrics for a video separated by subscription status for Youtube analytics API?
I am trying to find all views for all the videos that I have that is separated by subscription status of my viewers. But I'm getting an error using these dimensions.
I am currently using a Wrapper library... | Is there a way to retrieve all metrics for a video separated by subscription status for Youtube analytics API? | I am trying to find all views for all the videos that I have that is separated by subscription status of my viewers. But I'm getting an error using these dimensions.
I am currently using a Wrapper library called Analytix and here's how I'm querying the results:
report = client.retrieve(
dimensions=("video", "subscri... | [
"Author of analytix here. I'm a bit late to the party, but hopefully this should help.\nThe error \"unsupported dimension(s) for selected report type\" appears when two dimensions are incompatible. The YouTube Analytics API physically won't let you use those dimensions together.\nWhat I believe you're trying to do ... | [
0
] | [] | [] | [
"python",
"youtube_analytics_api",
"youtube_data_api"
] | stackoverflow_0073920171_python_youtube_analytics_api_youtube_data_api.txt |
Q:
Error installing packages(Numpy) on older version of python
I'm trying to run code from a repository from 2016 that doesn't label what versions of anything it's using, but I think I figured out that it was using Python version 3.4. I went ahead and installed that python version, but when I went to install the depe... | Error installing packages(Numpy) on older version of python | I'm trying to run code from a repository from 2016 that doesn't label what versions of anything it's using, but I think I figured out that it was using Python version 3.4. I went ahead and installed that python version, but when I went to install the dependencies, starting with Numpy, I got this error when running
pip ... | [
"The setup script for the version of Numpy you're trying to install is using an f-string. However, f-strings were introduced in Python 3.6, so your version does not support this. Installing an older version of numpy should work. Version 1.15.4 should be the latest one that supports Python 3.4.\npip install numpy==1... | [
0
] | [] | [] | [
"numpy",
"pip",
"python"
] | stackoverflow_0074166876_numpy_pip_python.txt |
Q:
Telegram Bot | How to handle multiple user at the same time?
I'm writing a telegram bot that can get data about cyrpto currencies. The bot work with no errors but it can handle just one user at the same time. If two users send request at the same time the bot get the data for who send request earlier than rerun fo... | Telegram Bot | How to handle multiple user at the same time? | I'm writing a telegram bot that can get data about cyrpto currencies. The bot work with no errors but it can handle just one user at the same time. If two users send request at the same time the bot get the data for who send request earlier than rerun for the other user and get data. this causes so much delay. How can ... | [
"It sounds like you might want to create some kind of queue object where requests can live & get handled in a first-in-first-out fashion. The asyncio or aiohttp modules might help with this.\n"
] | [
1
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram",
"telegram_bot"
] | stackoverflow_0074166999_python_python_telegram_bot_telegram_telegram_bot.txt |
Q:
PySpark: Too many WHEN statements?
I'm using Spark v2.4.0 and I occurred a strange phenomenon:
I have rather simple dataframe function and use it on some dataframe called "new":
from product_mapping import product_mapping
new2 = product_mapping(new)
new2.show()
product mapping (it's a separate python scri... | PySpark: Too many WHEN statements? | I'm using Spark v2.4.0 and I occurred a strange phenomenon:
I have rather simple dataframe function and use it on some dataframe called "new":
from product_mapping import product_mapping
new2 = product_mapping(new)
new2.show()
product mapping (it's a separate python script due to length of the statement)
impor... | [
"Here are my 2 cents: (The idea here is to concatenate three variables and then map based on the dictionary of key-value pairs)\n\nDeclare the function as follows:\n def product_mapping(df):\n\n conditions = { '301-1-30' : '102',\n '302-0-31' : '103',\n '302-1-31' : '104... | [
0
] | [] | [] | [
"apache_spark_sql",
"pyspark",
"python",
"when"
] | stackoverflow_0074156504_apache_spark_sql_pyspark_python_when.txt |
Q:
Python - Cannot Open .docx when I wrote a new line to it
Just learning how to use files in python. I created a word document "mydoc.docx", opens properly before I execute the code below:
myfile = open('mydoc.docx','w')
myfile.write ("hello"+'\n')
myfile.close()
After I ran the code above, the word document cannot... | Python - Cannot Open .docx when I wrote a new line to it | Just learning how to use files in python. I created a word document "mydoc.docx", opens properly before I execute the code below:
myfile = open('mydoc.docx','w')
myfile.write ("hello"+'\n')
myfile.close()
After I ran the code above, the word document cannot be opened any more showing "Word experienced an error trying ... | [
"That's expected. A \"docx\" has a very specific structure (under the covers, it's a series of zipped files) that includes the text of the document, plus formatting, metadata, change history, etc.\nWhat you have written with your Python program is a plain text file.\n",
"I think the issue might be that python wi... | [
1,
1,
0
] | [] | [] | [
"file",
"macos",
"ms_word",
"python"
] | stackoverflow_0074167012_file_macos_ms_word_python.txt |
Q:
ModuleNotFoundError: No module named 'rest_framework' (tried many solutions but not working)
I have encountered this error.
ModuleNotFoundError: No module named 'rest_framework'
I have a virtual environment setted up and the rest framework is installed correctly.
When I run pip3.10 show djangoframework, I get
Na... | ModuleNotFoundError: No module named 'rest_framework' (tried many solutions but not working) | I have encountered this error.
ModuleNotFoundError: No module named 'rest_framework'
I have a virtual environment setted up and the rest framework is installed correctly.
When I run pip3.10 show djangoframework, I get
Name: djangorestframework
Version: 3.14.0
Summary: Web APIs for Django, made easy.
Home-page: https:... | [
"You have two different python installations\nfrom pip3 show, there is this line:\nLocation: c:\\users\\chan\\desktop\\testpy\\lib\\site-packages\n\nbut your stack trace is listing files that are in\nFile \"C:\\Users\\Chan\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\LocalCache\\lo... | [
1,
1
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"python_3.x"
] | stackoverflow_0074166924_django_django_rest_framework_python_python_3.x.txt |
Q:
Zybooks 5.12 counting negative temperatures
I'm trying to write a code that will take 6 integers and count how many are negative. It needs to be formatted like this:
Enter Celsius temperature:
30
Enter Celsius temperature:
20
Enter Celsius temperature:
-5
Enter Celsius temperature:
-18
Enter Celsius temperature:
-... | Zybooks 5.12 counting negative temperatures | I'm trying to write a code that will take 6 integers and count how many are negative. It needs to be formatted like this:
Enter Celsius temperature:
30
Enter Celsius temperature:
20
Enter Celsius temperature:
-5
Enter Celsius temperature:
-18
Enter Celsius temperature:
-8
Enter Celsius temperature:
7
Number of below fr... | [
"You need to rewrite your code like this,\nnegtemp = 0\nfor _ in range(6):\n temp = int(input('Enter Celsius temperature:\\n'))\n if temp < 0:\n negtemp += 1\n \nprint('Number of below freezing temperatures: ', negtemp) \n\nYou aren tried to use while loop instead of if condition.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074167085_python.txt |
Q:
"FinalGrade is not defined" loop question
In my code, I'm trying to display the student with the highest grade in the class after calculating each grade received and their weight. For someone reason, I'm getting that the finalGrade is not defined. How would I display the student with the highest grade and their fi... | "FinalGrade is not defined" loop question | In my code, I'm trying to display the student with the highest grade in the class after calculating each grade received and their weight. For someone reason, I'm getting that the finalGrade is not defined. How would I display the student with the highest grade and their final grade as well?
def welcome():
print("He... | [
"Variables only exist in scopes. In this case finalGrades is defined in the aveGrade() function and can only be accessed from within this function. Therefore your main function does not \"know\" about the finalGrade variable. You can declare finalGrade in the global scope and then asign the value to it in the funct... | [
2
] | [] | [] | [
"function",
"loops",
"python"
] | stackoverflow_0074165956_function_loops_python.txt |
Q:
Django SearchQuery and SearchRank not finding results when 1 word matches in a 2 word query
I have a list of articles and I want to do a search using the PostgreSQL SearchQuery and SearchRank functionality. Here is the pseudo code:
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
fr... | Django SearchQuery and SearchRank not finding results when 1 word matches in a 2 word query | I have a list of articles and I want to do a search using the PostgreSQL SearchQuery and SearchRank functionality. Here is the pseudo code:
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
from .models import Article
vector = SearchVector('title', weight='A')
query = SearchQuery(value)
... | [
"Did you see this part of the documentation? Did you try that?\n\nhttps://docs.djangoproject.com/en/4.1/ref/contrib/postgres/search/#searchquery\nSo maybe you can do:\nquery = (SearchQuery('fast') | SearchQuery('computer'))\n\n"
] | [
0
] | [] | [] | [
"django",
"django_postgresql",
"django_rest_framework",
"python"
] | stackoverflow_0074167098_django_django_postgresql_django_rest_framework_python.txt |
Q:
Convert filepath string to python import string
I would like to convertos file paths like './foo/bar/file.py' to paths used in python import like 'foo.bar.file'.
I could very easily code my self these functions, but I wanted to know if there is a function for making that?
It would be great also if the functions wo... | Convert filepath string to python import string | I would like to convertos file paths like './foo/bar/file.py' to paths used in python import like 'foo.bar.file'.
I could very easily code my self these functions, but I wanted to know if there is a function for making that?
It would be great also if the functions works for windows and linux file paths
| [
"try this:\nimport pathlib\n\npath = pathlib.Path('foo/bar/file.py')\nformatted_path = '.'.join(path.with_suffix('').parts)\n\n# And do what you want with formatted_path\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074167119_python.txt |
Q:
Changing font type of Jupyter Notebook output in VSCode
I need help with changing the font of output in Jupyter Notebook. Sometime ago VSCode was updated and I saw the output font was changed from Consolas to Segoe UI. How can I revert this back?
A:
It looks like this is the fault of the new renderer of version ... | Changing font type of Jupyter Notebook output in VSCode | I need help with changing the font of output in Jupyter Notebook. Sometime ago VSCode was updated and I saw the output font was changed from Consolas to Segoe UI. How can I revert this back?
| [
"It looks like this is the fault of the new renderer of version 1.65 (link).\nOne work around is to go back to 1.64.2. The Jupyter extension need to be downgraded as well.\n",
"Press command + shift+ p and then VScode bar will open add > and search \"Open settings(UI)\"\nFor quick:\ndirectly type \"font\" in \"se... | [
4,
1,
0
] | [] | [] | [
"jupyter_notebook",
"python",
"visual_studio_code"
] | stackoverflow_0071369213_jupyter_notebook_python_visual_studio_code.txt |
Q:
is it possible to render a webpage directly to an image in python?
Now I am using selenium to save a web page to image.
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("some url")
browser.save_screenshot(img)
browser.quit()
But there is a problem that each time it will popup a window.
Is... | is it possible to render a webpage directly to an image in python? | Now I am using selenium to save a web page to image.
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("some url")
browser.save_screenshot(img)
browser.quit()
But there is a problem that each time it will popup a window.
Is there any way that can render a image directly to an image?
| [
"I found a workaround at How do I run Selenium in Xvfb?\nIt works fine in linux.\nfrom pyvirtualdisplay import Display\ndisplay = Display(visible=0, size=(800, 600))\ndisplay.start()\nbrowser = webdriver.Firefox()\nbrowser.get(\"some url\")\nbrowser.save_screenshot(img)\nbrowser.quit()\ndisplay.stop()\n\n",
"You ... | [
3,
1,
0
] | [] | [] | [
"python",
"selenium_webdriver"
] | stackoverflow_0020251692_python_selenium_webdriver.txt |
Q:
Why does remove() method does not work in certain instances?
mepstrip = ['AE38', 'AL29', 'AL30', 'AL35', 'AL41', 'BA37', 'BB37', 'BC37', 'CH24', 'CO26', 'GD29', 'GD30', 'GD35', 'GD38', 'GD41', 'GD46', 'PM29', 'SA24', 'T2V1', 'TDJ3']
indexlist = ['AE38', 'AE38C', 'AE38D', 'AL29', 'AL29C', 'AL29D', 'AL30', 'AL30C',... | Why does remove() method does not work in certain instances? | mepstrip = ['AE38', 'AL29', 'AL30', 'AL35', 'AL41', 'BA37', 'BB37', 'BC37', 'CH24', 'CO26', 'GD29', 'GD30', 'GD35', 'GD38', 'GD41', 'GD46', 'PM29', 'SA24', 'T2V1', 'TDJ3']
indexlist = ['AE38', 'AE38C', 'AE38D', 'AL29', 'AL29C', 'AL29D', 'AL30', 'AL30C', 'AL30D', 'AL35', 'AL35C', 'AL35D', 'AL41', 'AL41C', 'AL41D', 'AY2... | [
"You can't remove items from a list while iterating over it. Instead, you could make a copy of the list. And remove the items from that.\nnew_mepstrip = mepstrip.copy()\n\nfor i in mepstrip:\n if i not in indexlist:\n new_mepstrip.remove(i)\n\n"
] | [
0
] | [] | [] | [
"for_loop",
"python",
"remove_method"
] | stackoverflow_0074165602_for_loop_python_remove_method.txt |
Q:
Perform GridSearchCV with MLFlow
I just started using MLFlow and I am happy with what it can do. However, I cannot find a way to log different runs in a GridSearchCV from scikit learn.
For example, I can do this manually
params = ['l1', 'l2']
for param in params:
with mlflow.start_run(experiment_id=1):
... | Perform GridSearchCV with MLFlow | I just started using MLFlow and I am happy with what it can do. However, I cannot find a way to log different runs in a GridSearchCV from scikit learn.
For example, I can do this manually
params = ['l1', 'l2']
for param in params:
with mlflow.start_run(experiment_id=1):
clf = LogisticRegression(penalty = pa... | [
"I'd recommend hyperopt instead of scikit-learn's GridSearchCV. Hyperopt can search the space with Bayesian optimization using hyperopt.tpe.suggest. It will arrive at good parameters faster than a grid search and you can limit the number of iterations no matter the space size, so it's definitely better for large sp... | [
7,
0
] | [] | [] | [
"mlflow",
"python",
"scikit_learn"
] | stackoverflow_0060995542_mlflow_python_scikit_learn.txt |
Q:
Jquery not detecting Flask session
I am facing a situation where I am able to set a session with Flask and verify the session exists when visiting the Python endpoints directly. When I make my frontend return the session status, the Python endpoint returns not logged in.
Python:
@app.route("/status")
def status():... | Jquery not detecting Flask session | I am facing a situation where I am able to set a session with Flask and verify the session exists when visiting the Python endpoints directly. When I make my frontend return the session status, the Python endpoint returns not logged in.
Python:
@app.route("/status")
def status():
try:
session["access_token"]
... | [
"I didn't get this to work with Jquery, but native JS fetch:\napp.config['SESSION_COOKIE_DOMAIN'] = \".domain.net\"\napp.config[\"SESSION_COOKIE_NAME\"] = \"domain-session\"\napp.config[\"REMEMBER_COOKIE_DOMAIN\"] = \"None\"\n\nasync function postData(url = '') {\n // Default options are marked with *\n const res... | [
0
] | [] | [] | [
"flask",
"jquery",
"python",
"session"
] | stackoverflow_0074166490_flask_jquery_python_session.txt |
Q:
Finding minimum value with groupby() by comparing two columns
I am trying to find a minimum number using groupby() by comparing two columns (Each containing a time duration)
Sample data:
Ambulance_ID Centroid_ID Hospital_ID Regular_Ambu_TT MSU_TT
37 1 6 1,871884861 ... | Finding minimum value with groupby() by comparing two columns | I am trying to find a minimum number using groupby() by comparing two columns (Each containing a time duration)
Sample data:
Ambulance_ID Centroid_ID Hospital_ID Regular_Ambu_TT MSU_TT
37 1 6 1,871884861 0,459994444
39 2 13 1,5999... | [
"Here is one approach\n\nGet the min per column\nGet a min per row to get the final minimum .\n\ndf_mins = pd.DataFrame()\ndf_mins[['Centroid_ID', 'min_Regular_Ambu_TT']] = df_A2C_TT_temp.groupby('Centroid_ID')['Regular_Ambu_TT'].min().reset_index()\ndf_mins[['Centroid_ID', 'min_MSU_TT']] = df_A2C_TT_temp.groupby('... | [
4
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074166775_dataframe_jupyter_notebook_pandas_python_python_3.x.txt |
Q:
Is it possible to use selenium click outside web browser?
I searched a lot for how to click with selenium outside of web browser (like Desktop applications, for example WhatsApp or Telegram), but I didn't find a way.
This is what clicks only on browser:
driver.find_element(By.XPATH, value='//span').click()
I know... | Is it possible to use selenium click outside web browser? | I searched a lot for how to click with selenium outside of web browser (like Desktop applications, for example WhatsApp or Telegram), but I didn't find a way.
This is what clicks only on browser:
driver.find_element(By.XPATH, value='//span').click()
I know other packages like pyautogui, but I need to use headless clic... | [
"AFAIK the answer is: No, you can't.\nSelenium doesn't support clicking or any other iterations with elements out of the Web browser.\n"
] | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074159618_python_selenium_selenium_webdriver.txt |
Q:
Efficient way to select strings from a list based on a certain condition
I have a list of strings, I want to filter out these strings base on a given year. for example, in the below list, I only want strings with years above 2018 and also strings that don't contain years. My solution is current, I just need a bett... | Efficient way to select strings from a list based on a certain condition | I have a list of strings, I want to filter out these strings base on a given year. for example, in the below list, I only want strings with years above 2018 and also strings that don't contain years. My solution is current, I just need a better way to do this.
data = [
'/soccer/zimbabwe/premier-soccer-league/result... | [
"You need to append the values to a list (result in the below code). You can do like this,\nimport re\n\nresult = []\nfor i in data:\n match = re.match(r'.*(\\d{4})', i)\n if match:\n if int(match.group(1)) > 2018:\n result.append(i)\n else:\n result.append(i)\n\nOutput:\n['/soccer... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074167215_python_regex.txt |
Q:
Is there another way to convert ee.Number to float except getInfo()?
Hello friends!
Summarization:
I got a ee.FeatureCollection containing around 8500 ee.Point-objects. I would like to calculate the distance of these points to a given coordinate, lets say (0.0, 0.0).
For this i use the function geopy.distance.dist... | Is there another way to convert ee.Number to float except getInfo()? | Hello friends!
Summarization:
I got a ee.FeatureCollection containing around 8500 ee.Point-objects. I would like to calculate the distance of these points to a given coordinate, lets say (0.0, 0.0).
For this i use the function geopy.distance.distance() (ref: https://geopy.readthedocs.io/en/latest/#module-geopy.distance... | [
"I would use .map instead of your looping. This stays server side until you export the table (or possibly do a .getInfo on the whole thing)\n\nfc_containing_points = ee.FeatureCollection('projects/eephiladamhiwi/assets/Flensburg_100') \n\nfc_containing_points.map(lambda feature: feature.set(\"distance_to_point\", f... | [
0
] | [] | [] | [
"google_earth_engine",
"optimization",
"python"
] | stackoverflow_0074161495_google_earth_engine_optimization_python.txt |
Q:
Problem with 3D contour plots in matplotlib
I created a 3D contour map in Mathematica a while back, and I am trying to do it in Python this time. First let me show you what I obtained:
Mathematica:
Python:
Now, I would like the foreground (the visible part of the hills) to hide the background (the invisible part... | Problem with 3D contour plots in matplotlib | I created a 3D contour map in Mathematica a while back, and I am trying to do it in Python this time. First let me show you what I obtained:
Mathematica:
Python:
Now, I would like the foreground (the visible part of the hills) to hide the background (the invisible part). In the Python version, it seems as if you are ... | [
"Matplotlib is not really great when it comes to 3D plot. You lowered the opacity of the surface to make the contour lines visible. I'm afraid that what you are asking is impossible to achieve with matplotlib.\nWhat if you were to try a different library? For example Plotly or Mayavi?\nimport numpy as np\nimport pl... | [
1,
0
] | [] | [] | [
"contour",
"contourf",
"matplotlib",
"python",
"python_3.x"
] | stackoverflow_0074166875_contour_contourf_matplotlib_python_python_3.x.txt |
Q:
Why does my python code run perfectly fine on runestone but not on vscode?
def CreditPay(rate, payment, verbose):
balance = 1000 # Amount currently owed
month = 1 #Number of months
paid = 0 # Amount paid so far
while balance > payment:
balance = balance + balance*rate/100 - payment
... | Why does my python code run perfectly fine on runestone but not on vscode? | def CreditPay(rate, payment, verbose):
balance = 1000 # Amount currently owed
month = 1 #Number of months
paid = 0 # Amount paid so far
while balance > payment:
balance = balance + balance*rate/100 - payment
paid += payment
if verbose:
print(f'Balance after month... | [
"My problem was I downloaded code runner extension. I had to go to its settings.json and change python -u to python3 -u. thanks for the help. still new to programming.\n",
"What python interpreter are you using? f-string got introduced in python3.\nTo select your python interpreter with Vscode open up the command... | [
1,
0
] | [] | [] | [
"python",
"syntax",
"syntax_error"
] | stackoverflow_0074167023_python_syntax_syntax_error.txt |
Q:
locating an element on an iframe within an iframe
Hi I need some help with locating the button on an iframe which I think is within another iFrame. I tried everything that I could find but got no success. I can't copy-paste the whole code but have attached the screenshot that explains the tree.
A:
Please try thi... | locating an element on an iframe within an iframe | Hi I need some help with locating the button on an iframe which I think is within another iFrame. I tried everything that I could find but got no success. I can't copy-paste the whole code but have attached the screenshot that explains the tree.
| [
"Please try this:\ndriver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, \"iframe.swg-dialog\"))\ndriver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, \"iframe[src*='publicatioId=barpage.com']\"))\ndriver.find_element(By.CSS_SELECTOR, div[data-test-id='close-button']).click()\n\nWhen you finished worki... | [
1,
0
] | [] | [] | [
"css_selectors",
"iframe",
"python",
"selenium",
"xpath"
] | stackoverflow_0074157363_css_selectors_iframe_python_selenium_xpath.txt |
Q:
ERROR: Could not find a version that satisfies the requirement pandas (from fuzzytm) (from versions: none)
I have created a new version of my package and have uploaded it to Pypi's test server using:
python -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*
To test if it works, I have created a... | ERROR: Could not find a version that satisfies the requirement pandas (from fuzzytm) (from versions: none) | I have created a new version of my package and have uploaded it to Pypi's test server using:
python -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*
To test if it works, I have created a new virtual environment with Python 3.8 and ran:
pip install -i https://test.pypi.org/simple/ FuzzyTM==0.5.0
(... | [
"I ran into the same issue. The problem is that pandas does not have releases in TestPypi, only in Pypi. You will need to specify the index for your dependencies.\nThe solution is here.\n"
] | [
0
] | [] | [] | [
"pandas",
"pypi",
"python",
"version"
] | stackoverflow_0073811782_pandas_pypi_python_version.txt |
Q:
My menu loop isn't working and I don't know why
I'm writing code for a project and I am just finishing up the menu, where there are 5 options and the user inputs a number to select said option. Here's my code:
display_menu(True)
command = input("Enter a number (0 to exit): ")
while command != 0:
if co... | My menu loop isn't working and I don't know why | I'm writing code for a project and I am just finishing up the menu, where there are 5 options and the user inputs a number to select said option. Here's my code:
display_menu(True)
command = input("Enter a number (0 to exit): ")
while command != 0:
if command == 1:
namefile = input("Enter word list f... | [
"command is a string returned by input, and you're comparing to an int. You need to explicitly convert that string to an int.\ncommand = int(input(\"Enter a number (0 to exit): \"))\n\n",
"As @Chris said you must not compare string and integer.\nYou may convert the input to an integer or you can test for an alpha... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074167154_python.txt |
Q:
Time complexity and number of calls
I have trouble finding the time complexity of my program and the exact formula to compute the number of calls (represented by the length of the list). Here is my python program that I wrote:
from math import *
def calc(n):
i = n
li = []
while i>0:
j = 0
... | Time complexity and number of calls | I have trouble finding the time complexity of my program and the exact formula to compute the number of calls (represented by the length of the list). Here is my python program that I wrote:
from math import *
def calc(n):
i = n
li = []
while i>0:
j = 0
li.append(1)
while j<n:
... | [
"Maybe plotting your total number of calls against your value for n will help:\nimport matplotlib.pyplot as plt\n\nx = [i for i in range(1, 16)]\ny = [calc(n) for n in x]\n\nplt.plot(x, y)\nplt.show()\n\n\n",
"For computing time complexity of this program we come from most inner loop.\nk=j\nwhile k<n:\n li.appe... | [
0,
0
] | [] | [] | [
"python",
"time_complexity"
] | stackoverflow_0074166725_python_time_complexity.txt |
Q:
Creating lists inside a list in Python
values = ['random word1', 20, 'random word2', 54…]
The list has a string then a value and again a string then afterwards a value. The amount of strings followed by values is random. The words are random and the values are random as well
I want to convert the list to somethin... | Creating lists inside a list in Python | values = ['random word1', 20, 'random word2', 54…]
The list has a string then a value and again a string then afterwards a value. The amount of strings followed by values is random. The words are random and the values are random as well
I want to convert the list to something like this:
values = [['random word1', 20],... | [
"values = ['random word1', 20, 'random word2', 54]\nvalues = [values[i:i+2] for i in range(0,len(values),2)]\nprint(values)\n\n",
"Try this:\nvalues = ['random word1', 20, 'random word2', 54]\nprint([list(x) for x in zip(values[::2], values[1::2])])\n\n",
"You can do it with zip and list slicing.\nlist(map(list... | [
2,
2,
1
] | [
"b = [[values[i], values[i+1]] for i in range(len(values)) if i%2==0]\n\n"
] | [
-2
] | [
"list",
"python"
] | stackoverflow_0074167340_list_python.txt |
Q:
How do I integrate a logical boolean constraint into the standard matrix form of a Mixed Integer Linear Problem in scipy.optimize.milp / linprog?
I want to implement boolean logic and dependent variables into a Mixed-Integer Linear Program with scipy.optimize.milp using a highs solver.
How do I set the actual matr... | How do I integrate a logical boolean constraint into the standard matrix form of a Mixed Integer Linear Problem in scipy.optimize.milp / linprog? | I want to implement boolean logic and dependent variables into a Mixed-Integer Linear Program with scipy.optimize.milp using a highs solver.
How do I set the actual matrices and vectors c, A_ub, b_ub, A_eq, b_eq to fit these exemplary Boolean operations of the exemplary MILP:
Boolean variables: a, b, c, d, e, f, g, h, ... | [
"Disclaimer\nGeneralization is fine, but sometimes we lose exploitable substructures in mathematical-optimization. Sometimes this is bad!\nRecommendation\nThat being said, i recommend the following.\nIntermediate language: Conjunctive normal form\n\nIt's well known, that we can express any boolean function with it\... | [
1,
1
] | [] | [] | [
"boolean_logic",
"linear_programming",
"mixed_integer_programming",
"python",
"scipy_optimize_minimize"
] | stackoverflow_0074158965_boolean_logic_linear_programming_mixed_integer_programming_python_scipy_optimize_minimize.txt |
Q:
Why is my code not working and checking the input
trying to check for "50" and other strings to see if they follow the if statements that i used and for some reason they don't, can someone help ?
A:
The first elif block always returns True.
Use in instead:
elif answer in {"forty-two", "forty two"}:
Take a look ... | Why is my code not working and checking the input | trying to check for "50" and other strings to see if they follow the if statements that i used and for some reason they don't, can someone help ?
| [
"The first elif block always returns True.\nUse in instead:\nelif answer in {\"forty-two\", \"forty two\"}:\n\nTake a look here for good explanations\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074167399_python.txt |
Q:
How to display a history chart for multiple symbols with yahoo query?
What is the command to display the chart in https://yahooquery.dpguthrie.com/guide/ticker/historical/
I tried this code
import pandas as pd
import matplotlib.pyplot as plt
from yahooquery import Ticker
tickers = Ticker('aapl nflx', asynchronou... | How to display a history chart for multiple symbols with yahoo query? | What is the command to display the chart in https://yahooquery.dpguthrie.com/guide/ticker/historical/
I tried this code
import pandas as pd
import matplotlib.pyplot as plt
from yahooquery import Ticker
tickers = Ticker('aapl nflx', asynchronous=True)
df = tickers.history()
df["adjclose"].plot()
plt.xticks(rotation=90... | [
"The symbol and date are indexes into the dataframe. By plotting the whole dataframe, you are getting both series plotted sequentially.\nHere's one way to plot each ticker:\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom yahooquery import Ticker\n\ntickers = Ticker('aapl nflx', asynchronous=True)\ndf =... | [
1,
1
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074167019_matplotlib_pandas_python.txt |
Q:
How to install a missing python package from inside the script that needs it?
Assuming that you already have pip or easy_install installed on your python distribution, I would like to know how can I installed a required package in the user directory from within the script itself.
From what I know pip is also a pyt... | How to install a missing python package from inside the script that needs it? | Assuming that you already have pip or easy_install installed on your python distribution, I would like to know how can I installed a required package in the user directory from within the script itself.
From what I know pip is also a python module so the solution should look like:
try:
import zumba
except ImportErr... | [
"Updated for newer pip version (>= 10.0):\ntry:\n import zumba\nexcept ImportError:\n from pip._internal import main as pip\n pip(['install', '--user', 'zumba'])\n import zumba\n\nThanks to @Joop I was able to come-up with the proper answer. \ntry:\n import zumba\nexcept ImportError:\n import pip\... | [
27,
11,
3,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0017271444_pip_python.txt |
Q:
Activate Conda environment
I have installed Anaconda on Windows. I try need to activate conda environment but I do not know how. Coud you anybody advice how to do it step by step? I got this message:
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Warning:
This... | Activate Conda environment | I have installed Anaconda on Windows. I try need to activate conda environment but I do not know how. Coud you anybody advice how to do it step by step? I got this message:
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Warning:
This Python interpreter is in a cond... | [
"Here is Anaconda's documentation for creating and activating conda environments. You'll want to first create the environment, then activate it. Depending on your OS, versioning, environment %PATH, etc you may have other questions. However this is a good place to start.\nNote that if using powershell, first use con... | [
1,
0
] | [] | [] | [
"conda",
"python"
] | stackoverflow_0057112339_conda_python.txt |
Q:
Import flask not working on my macbook pro m1 chip
import flask shows an error in my Vs code.
when I tried to check the version I found 2 versions of python installed.
I don't know if due to that it is causing the problem.
what should I do?enter image description here
A:
It is all because you haven't installed t... | Import flask not working on my macbook pro m1 chip | import flask shows an error in my Vs code.
when I tried to check the version I found 2 versions of python installed.
I don't know if due to that it is causing the problem.
what should I do?enter image description here
| [
"It is all because you haven't installed the module. It wouldn't really run without installing.\nSo you would have to install it. The issue here is that I don't use MAC so I can't explain but I have found a video that would explain it to you.\nLink: https://www.youtube.com/watch?v=yBdZZGPpYxg\nWatch the video. In t... | [
0,
0,
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0067310790_python_visual_studio_code.txt |
Q:
Python - TypeError not all arguments converted duting string formation
I have a script that will accept a random number from a server and then it will tell me if its even or odd, however when I run it I get an error
TypeError not all arguments converted during string formation
Here is the full error message:
Tr... | Python - TypeError not all arguments converted duting string formation | I have a script that will accept a random number from a server and then it will tell me if its even or odd, however when I run it I get an error
TypeError not all arguments converted during string formation
Here is the full error message:
Traceback (most recent call last):
File "client.py", line 18, in
if (RNUM % 2... | [
"The variable RNUM is a string. To convert it to an integer, call int(RNUM).\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074113155_python.txt |
Q:
Add Item to new List based on Key Value Pair
I'd like to loop through a list and add certain items to a new list if they meet the criteria. I have:
loans = [
{
"loan_price": 700,
"remaining_months": 9,
"repayment_interval": "monthly",
"future_value": 1000,
},
{
"... | Add Item to new List based on Key Value Pair | I'd like to loop through a list and add certain items to a new list if they meet the criteria. I have:
loans = [
{
"loan_price": 700,
"remaining_months": 9,
"repayment_interval": "monthly",
"future_value": 1000,
},
{
"loan_price": 500,
"remaining_months": 13,
... | [
"Try this,\ninexpensive_loans = []\n\nfor item in loans:\n if item.get(\"loan_price\") <= 500:\n inexpensive_loans.append(item)\n\nprint(f\"{inexpensive_loans}\")\n\nIssues with your code\n\nYou are not calling appending function inexpensive_loans.append\nYou need to get the value from item (item.get(\"lo... | [
1
] | [] | [] | [
"if_statement",
"list",
"loops",
"python"
] | stackoverflow_0074167530_if_statement_list_loops_python.txt |
Q:
"i is not accessed Pylance". the "i" in for loop doesn't work
The variables in all of the following for loops says that "variable is not accessed Pylance"
The font color of the variable is "dead".
if special == "n" and numbers == "n":
for i in range(l):
password.append(random.choice(cha... | "i is not accessed Pylance". the "i" in for loop doesn't work | The variables in all of the following for loops says that "variable is not accessed Pylance"
The font color of the variable is "dead".
if special == "n" and numbers == "n":
for i in range(l):
password.append(random.choice(chars))
elif special == "y" and numbers == "y":
fo... | [
"As was mentioned in the comments, the reason for the warning is that you don't use the variable; the convention in python is to use _ for such variables. You can get rid of this problem by using random.choices, passing it a k value of the number of random values you want. I've modified your code to simplify it; no... | [
1
] | [] | [] | [
"for_loop",
"pylance",
"python",
"variables"
] | stackoverflow_0074167371_for_loop_pylance_python_variables.txt |
Q:
Determining if a letter in a list of letters is uppercase
I am attempting to write a program where it takes a list input by the user and determines if the letter in the list is uppercase or not. This is the code I have so far.
# Write a Python function to count how many letters in a string are in uppercase.
prin... | Determining if a letter in a list of letters is uppercase | I am attempting to write a program where it takes a list input by the user and determines if the letter in the list is uppercase or not. This is the code I have so far.
# Write a Python function to count how many letters in a string are in uppercase.
print("Hey, do you wanna see a cool trick I can do? I can count how... | [
"Your code has a few problems. The first is that you are not declaring capital before incrementing it. You should have capital = 0 before the for a loop. Second, you are comparing with ==, but you should use is instead. Lastly, to check if a letter is uppercase, you must call letter.isupper() (not letter.isupper). ... | [
1,
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074167397_loops_python.txt |
Q:
Why does PyCharm after running any code gives out the same result?
I have recently started learning programming in Python and I'm using PyCharm as a text reader, I was trying out a few simple codes which I was following from a tutorial, these are the codes that I've tried:
Print("Hello World")
and also a simple c... | Why does PyCharm after running any code gives out the same result? | I have recently started learning programming in Python and I'm using PyCharm as a text reader, I was trying out a few simple codes which I was following from a tutorial, these are the codes that I've tried:
Print("Hello World")
and also a simple calculator code:
num1 = input("Enter a number")
num2 = input("Enter anoth... | [
"Within PyCharm, you may just need to keep track of which script you are running in PyCharm. Right-click the script you want to run and choose run or debug. You can also search for 'Hi, Pycharm' in your code to find the script that is running with menu: edit: find: find in files.\n",
"I had the same problem, yo... | [
2,
1
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0068421899_pycharm_python.txt |
Q:
How do I plot the gradient calculated from a multivariable function?
Let's say I have following python code:
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure()
ax=plt.axes(projection='3d')
x=y=np.linspace(1,10,100)
X,Y=np.meshgrid(x,y)
Z=np.sin(X)**3+np.cos(Y)**3
ax.plot_surface(X,Y,Z)
plt.show()... | How do I plot the gradient calculated from a multivariable function? | Let's say I have following python code:
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure()
ax=plt.axes(projection='3d')
x=y=np.linspace(1,10,100)
X,Y=np.meshgrid(x,y)
Z=np.sin(X)**3+np.cos(Y)**3
ax.plot_surface(X,Y,Z)
plt.show()
How do I calculate from this code the gradient and plot it? I am also co... | [
"gradient is a vector. It has 2 components (in this case, since we are dealing with function ℝ²→ℝ, X,Y↦Z(X,Y)), one which is ∂Z/∂X, (also a function of X and Y), another which is ∂Z/∂Y.\nSo, np.gradients returns both. np.gradient(Z), called with a 100×100 array of Z, returns a list [∂Z/∂X, ∂Z/∂Y], both being also 1... | [
1,
0
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0074165151_matplotlib_plot_python.txt |
Q:
How to make WPF MVVM Bindings work in python.NET (Cpython)?
I'm trying to port this IronPython WPF example to CPython with python.NET.
I'm able to get the window running after fixing some known issues (adding __namespace__ to the ViewModel class, using Single Thread Apartment and updating the syntax of pyevent.py ... | How to make WPF MVVM Bindings work in python.NET (Cpython)? | I'm trying to port this IronPython WPF example to CPython with python.NET.
I'm able to get the window running after fixing some known issues (adding __namespace__ to the ViewModel class, using Single Thread Apartment and updating the syntax of pyevent.py to python3), but bindings are ignored: I can write in the textbox... | [
"Unfortunately pythonnet does not support defining binding in the xaml file.\n"
] | [
0
] | [] | [] | [
"python",
"python.net",
"wpf"
] | stackoverflow_0072458372_python_python.net_wpf.txt |
Q:
Why do i get the same result even with different byteorder?
This is when we convert numbers to bytes :
print(int.to_bytes(65, length=1, byteorder='big')) #this converts numbers to characters
result:
A
why do i see the same result even if i used different byteorder ?
print(int.from_bytes(b'A', byteorder='big', si... | Why do i get the same result even with different byteorder? | This is when we convert numbers to bytes :
print(int.to_bytes(65, length=1, byteorder='big')) #this converts numbers to characters
result:
A
why do i see the same result even if i used different byteorder ?
print(int.from_bytes(b'A', byteorder='big', signed=True))
print(int.from_bytes(b'A', byteorder='little', signed... | [
"Probably because one char ('A') is stored in a single byte. The change of order big/little is visible with many bytes. Tested with 2 different bytes:\n>>> print(int.from_bytes(b'AB', byteorder='big', signed=True))\n16706\n>>> print(int.from_bytes(b'AB', byteorder='little', signed=True))\n16961\n\nSee python docs\n... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0074167545_python.txt |
Q:
How do I get a coordinates list from an svgpathtools bezier curve?
I have python code to create a bezier curve, from which I create a bezier path.
Here are my imports:
import from svgpathtools import Path, Line, CubicBezier
Here is my code:
bezier_curve = CubicBezier(start_coordinate, control_point_1, contr... | How do I get a coordinates list from an svgpathtools bezier curve? | I have python code to create a bezier curve, from which I create a bezier path.
Here are my imports:
import from svgpathtools import Path, Line, CubicBezier
Here is my code:
bezier_curve = CubicBezier(start_coordinate, control_point_1, control_point_2, end_coordinate)
bezier_path = Path(bezier_curve)
I woul... | [
"Seems like a pretty reasonable question. Surprised there's no answer. I had to do this myself recently, and the secret is point().\nHere's how I got it done, using your boilerplate as a starting point:\nfrom svgpathtools import Path, Line, CubicBezier\n\nbezier_curve = CubicBezier(start=(300+100j), control1=(100+1... | [
8,
2,
1,
0
] | [] | [] | [
"python",
"svg",
"svg_path"
] | stackoverflow_0043383249_python_svg_svg_path.txt |
Q:
Parse timestamp from a txt file?
I have a large text file on the web that I am using requests to obtain and parse data from. The text file begins each line with a format like [Mon Oct 10 08:58:26 2022]. How can I get the latest 7 days or convert only the datetime to an object or string for storing and parsing late... | Parse timestamp from a txt file? | I have a large text file on the web that I am using requests to obtain and parse data from. The text file begins each line with a format like [Mon Oct 10 08:58:26 2022]. How can I get the latest 7 days or convert only the datetime to an object or string for storing and parsing later? I simply want to extract the timest... | [
"You can use TimedRotatingFileHandler for daily or 7-days logs.\nread more about timed rotating file handler here\nand\nread more about extracting timestamps from files\n",
"Can you tell me if this snippet solves your problem?\nfrom datetime import datetime\n\nlog_line = \"[Sun Oct 09 06:14:26 2022] Wiladoc is br... | [
0,
0
] | [] | [] | [
"datetime",
"python",
"python_requests",
"timestamp"
] | stackoverflow_0074163098_datetime_python_python_requests_timestamp.txt |
Q:
Iteration results in fixed-size groups
I can iterate over a list or string in fixed-size slices like this:
for n in range(0, len(somelongstring), 10):
print(somelongstring[n:n+10])
But how do I iterate over 10-line slices from an open file, or over some other iterable, without reading the whole thing into a l... | Iteration results in fixed-size groups | I can iterate over a list or string in fixed-size slices like this:
for n in range(0, len(somelongstring), 10):
print(somelongstring[n:n+10])
But how do I iterate over 10-line slices from an open file, or over some other iterable, without reading the whole thing into a list? Every so often I need to do this, and t... | [
"I finally remembered that the term for this is \"chunking\", and then I was able to track it down, in the itertools recipes no less. Boiled down, it's this head-spinning little trick with zip (actually zip_longest, but who's counting):\ndef chunk(source, n):\n return zip_longest(*([iter(source)] * n))\n\nFirst ... | [
1,
0,
0,
0
] | [
"Use itertools.islice with enumerate like this\nimport itertools\nsome_long_string = \"ajbsjabdabdkabda\"\nfor n in itertools.islice(enumerate(some_long_string), 0, None ,10):\n print(some_long_string[n[0]:n[0]+10])\n# output\najbsjabdab\ndkabda\n\nIf you are dealing with file then you can use chunk while file.r... | [
-1
] | [
"python",
"python_itertools"
] | stackoverflow_0074165798_python_python_itertools.txt |
Q:
python opencv how do i matchtemplate for same shapes with different colors and brightness
im using matchtemplate to detect 2x2 sqaures on dark background. with my code, it detects most of the squares without any problem but it fails detecting when the color of the squares are dark and blackish. i tried normalize ... | python opencv how do i matchtemplate for same shapes with different colors and brightness | im using matchtemplate to detect 2x2 sqaures on dark background. with my code, it detects most of the squares without any problem but it fails detecting when the color of the squares are dark and blackish. i tried normalize in opencv but it didnt work well.. also tried using mask but it didnt work either (maybe i used... | [
"The problem you are facing is that part of the squares you want to detect does not follow the rule \"lighter than background\" and are \"darker than background\". The solution to this problem is to use template image with reversed colors:\n\n^-- inversed template\nimport cv2\nimport numpy as np\nimport time\n ... | [
1
] | [] | [] | [
"opencv",
"python",
"python_3.x",
"template_matching"
] | stackoverflow_0074167407_opencv_python_python_3.x_template_matching.txt |
Q:
math formula wrong integration
`the formula im trying to integrate. https://prnt.sc/OMvgREyExFjd
in the task if y = 1.4 and f = 0.5 then the answer is appx 0.28991
but i get 0.608....
where did i make it wrong i rewrote code 3 times and every single time i got different answer.
import math
y = 1.4
f = 0.5
a = (1-(... | math formula wrong integration | `the formula im trying to integrate. https://prnt.sc/OMvgREyExFjd
in the task if y = 1.4 and f = 0.5 then the answer is appx 0.28991
but i get 0.608....
where did i make it wrong i rewrote code 3 times and every single time i got different answer.
import math
y = 1.4
f = 0.5
a = (1-((1+(2*y)/(y-1)-(f**2)-(math.sqrt((1+... | [
"Following the picture you provided, your formula IS well implemented, in the sense that it gives the answer P(phi=0.5, 1.4) = 0.608236. (I coded it up in Python and Mathematica to test it).\nWhat is that you are trying to accomplish here? Perhaps your text formula is wrong in the first place? Without much backgrou... | [
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074167387_math_python.txt |
Q:
How to append to a string?
Here I am counting each character in a string and return that character with it's number of occurences in the string. e.g.: ab("aabbc") and return a string: a2b2c1
However I have a list here where instead of returning a2b2c1, it returns ['a',2,'b',2,'c',1]. I want it to return it in the ... | How to append to a string? | Here I am counting each character in a string and return that character with it's number of occurences in the string. e.g.: ab("aabbc") and return a string: a2b2c1
However I have a list here where instead of returning a2b2c1, it returns ['a',2,'b',2,'c',1]. I want it to return it in the form of a string, and not a list... | [
"Consider recognizing that strings are immutable in python:\ndef ab(n):\n char = []\n i = 0\n while i < len(n):\n run_length = 1\n while i + 1 < len(n) and n[i] == n[i + 1]:\n run_length += 1\n i += 1\n char.append(str(run_length))\n char.append(n[i])\n ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074167470_python.txt |
Q:
How to add Copyright to Nuitka generated Exe
To add copyright to nuitka generated exe
Script-
python -m nuitka -standalone --windows-company-name=MYcompany --windows-file-version=1.1.0 --windows-product-name=app --enable-plugin=tk-inter main.py
I want to know how to add copyright to the exe file generated using N... | How to add Copyright to Nuitka generated Exe | To add copyright to nuitka generated exe
Script-
python -m nuitka -standalone --windows-company-name=MYcompany --windows-file-version=1.1.0 --windows-product-name=app --enable-plugin=tk-inter main.py
I want to know how to add copyright to the exe file generated using Nuitka
| [
"Not the best answer, but for me is working.\nPS. This will not work for every EXE file like GoDot ones, just give it a try.\nI use Resource Hacker to edit this stuffs. I used this RH when I used pyinstaller and there I had no control over metadata file, with nuitka I use it just to add that copyright info on the m... | [
0
] | [] | [] | [
"nuitka",
"python",
"python_3.9"
] | stackoverflow_0071752122_nuitka_python_python_3.9.txt |
Q:
How to print the value of "object at somthing"
I am using Azure Confidential Ledger, and I am trying to query it. But when I want to print a variable that contain value I encounter following line as an output:
bound method ConfidentialLedgerClientOperationsMixin.list_ledger_entries of <azure.confidentialledger._p... | How to print the value of "object at somthing" | I am using Azure Confidential Ledger, and I am trying to query it. But when I want to print a variable that contain value I encounter following line as an output:
bound method ConfidentialLedgerClientOperationsMixin.list_ledger_entries of <azure.confidentialledger._patch.ConfidentialLedgerClient object at 0x000001BAD3... | [
"Try this:\nd = ledger_client.list_ledger_entries()\n\ninstead of this\nd = ledger_client.list_ledger_entries\n\nin your code, you did not assign the the result of the method call to the var d but instead assigned the method list_ledger_entries's object of ledger_client to d\n"
] | [
1
] | [] | [] | [
"azure",
"python"
] | stackoverflow_0074167593_azure_python.txt |
Q:
Add the missing numbers in the table in order
I need modify a csv file with pandas. I have the following table:
Interface Description
1 Used
2 Used
3 Used
4 Used
6 Used
8 Used
12 Used
17 Used
I need to match the "Interface" column wit... | Add the missing numbers in the table in order | I need modify a csv file with pandas. I have the following table:
Interface Description
1 Used
2 Used
3 Used
4 Used
6 Used
8 Used
12 Used
17 Used
I need to match the "Interface" column with a range of 1, 20, complete the table with the mis... | [
"Use merge in combination with fillna\ndf = pd.DataFrame({\n 'Interface': [1, 2, 3, 4, 6, 8, 12, 17],\n 'Description': 'Used'})\ndf2 = pd.DataFrame({'Interface': range(1, 21)}).merge(df, how=\"left\").fillna(\"free\")\n\n",
"Another way using reindex\ndf.set_index('Interface').reindex(range(1,21)).fillna('f... | [
4,
3,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074167295_pandas_python.txt |
Q:
Can a wrapper/decorator function in Python disable all logging inside the code it wraps
I want to decorate/wrap a function and prevent the logging of all logs from within that function's scope.
def prevent_logs_wrapper(func):
...
...
...
@prevent_logs_wrapper
def some_logs():
logger.info('Log an i... | Can a wrapper/decorator function in Python disable all logging inside the code it wraps | I want to decorate/wrap a function and prevent the logging of all logs from within that function's scope.
def prevent_logs_wrapper(func):
...
...
...
@prevent_logs_wrapper
def some_logs():
logger.info('Log an info msg')
logger.warning('Log a warning msg')
and instead of this output
[INFO] Log an i... | [
"There is no such possibility in the logging, but it is available in the Polog library. Install it:\n$ pip install polog\n\nAnd use the unlog decorator for your functions:\nfrom polog import log, unlog\n\n@unlog\ndef function():\n log(\"some text\") # It won't work!\n\nThe Polog is more powerful than standard lo... | [
1
] | [] | [] | [
"logging",
"python",
"python_decorators"
] | stackoverflow_0070237153_logging_python_python_decorators.txt |
Q:
Whitespace issues, Python dice roll simulator
My output differs from what my professor wants, below is my code, my output, and the desired output. The white space between the number and the 's' and the ':' is the issue, it shouldn't be there. I've tried the leading whitespace strip function, the trailing one, the ... | Whitespace issues, Python dice roll simulator | My output differs from what my professor wants, below is my code, my output, and the desired output. The white space between the number and the 's' and the ':' is the issue, it shouldn't be there. I've tried the leading whitespace strip function, the trailing one, the join function. I keep getting errors. Something sim... | [
"By default, print puts a space between each argument supplied to it. You can override this by specifying the sep argument... but it's usually easier to provide one argument, which you can build as an f-string.\nprint(f'{numbers}s: {\"*\" * roll_list[numbers]}')\n\n",
"Try\nprint(\"%ds:\" % numbers, '*' * roll_li... | [
1,
0
] | [
"There is some issue with the printing function. See this\ndef print_histogram(): #defines the for loop below, printing the desired outcome\n for numbers in range(2, 13):\n print(f'{numbers}s', ':', '*' * roll_list[numbers])\n\nAlmost identical, but i changed the first argument of print(), putting numbers insid... | [
-1
] | [
"python",
"whitespace"
] | stackoverflow_0074167639_python_whitespace.txt |
Q:
How do I split cell strings if cell value contains a specific word in Python?
I am trying to write some code in python that will split the string in a cell if the cell value contains a certain word.
I have made a sample dataframe to explain the challenge I'm facing.
d = {'Message': [1, 2,3], 'Details': ['I WANT IT... | How do I split cell strings if cell value contains a specific word in Python? | I am trying to write some code in python that will split the string in a cell if the cell value contains a certain word.
I have made a sample dataframe to explain the challenge I'm facing.
d = {'Message': [1, 2,3], 'Details': ['I WANT IT ALL', 'HELLO WORLD','NOPE IT IS NOT CORRECT']}
df = pd.DataFrame(data=d)
df
I can... | [
"here you go.\ndef get_left(value: str) -> str:\n return df.query(\"Details.str.contains(@value)\").at[0, \"Details\"].split(value)[0]\n\n\ndf[\"New Column\"] = np.where(df[\"Details\"].str.contains(\"WANT\"), get_left(\"WANT\"), \"other\")\nprint(df)\n\n Message Details New Column\n0 1 ... | [
1
] | [] | [] | [
"pandas",
"python",
"strsplit"
] | stackoverflow_0074167612_pandas_python_strsplit.txt |
Q:
Tokenizing a Gensim dataset
Im trying to tokenize a gensim dataset, which I've never worked with before and Im not sure if its a small bug or im not doing it properly.
I loaded the dataset using
model = api.load('word2vec-google-news-300')
and from my understanding, to tokenize using nltk all I need to do it call... | Tokenizing a Gensim dataset | Im trying to tokenize a gensim dataset, which I've never worked with before and Im not sure if its a small bug or im not doing it properly.
I loaded the dataset using
model = api.load('word2vec-google-news-300')
and from my understanding, to tokenize using nltk all I need to do it call
tokens = word_tokenize(model)
H... | [
"word2vec-google-news-300 isn't a dataset that's appropriate to 'tokenize'; it's the pretrained GoogleNews word2vec model released by Google circa 2013 with 3 million word-vectors. It's got lots of word-tokens, each with a 300-dimensional vector, but no multiword texts needing tokenization.\nYou can run type(model)... | [
0
] | [] | [] | [
"gensim",
"python",
"tokenize"
] | stackoverflow_0074167136_gensim_python_tokenize.txt |
Q:
Factorial function in python is being limited
I made a simple factorial program:
import sys
sys.set_int_max_str_digits(0)
sys.setrecursionlimit(1000000)
def factorial(x):
if x == 0 | x == 1:
return 1
elif x > 1:
return x * factorial(x - 1)
i = 0
while 1:
print(factorial(i), '\n')
... | Factorial function in python is being limited | I made a simple factorial program:
import sys
sys.set_int_max_str_digits(0)
sys.setrecursionlimit(1000000)
def factorial(x):
if x == 0 | x == 1:
return 1
elif x > 1:
return x * factorial(x - 1)
i = 0
while 1:
print(factorial(i), '\n')
i += 1
But after a while the program halts. I wan... | [
"Recursion is not meant to be infinite. Eventually your program would fail, even on a system with a huge amount of memory.\nAlso note that the recursion limit given to setrecursionlimit() is not a guarantee that you'll get that recursion depth. To quote from the sys.setrecursionlimit documentation:\n\nThe highest p... | [
1
] | [] | [] | [
"factorial",
"limit",
"python",
"recursion"
] | stackoverflow_0074167711_factorial_limit_python_recursion.txt |
Q:
python call module other script
I want to make a module script like module.py and I want to call these modules in other script files. How can I do that?
module.py
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by impor... | python call module other script | I want to make a module script like module.py and I want to call these modules in other script files. How can I do that?
module.py
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.comm... | [
"from module import <thing to import>\n\nYou mean like this?\nYou can do\nfrom module import opt, driver, insta, delay\n\nAnd anything else you need.\nIf you want to import everything do from module import *\n",
"One way to do it is to create a function in module.py:\n# module.py\nimport time\nfrom selenium impor... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0074167723_python_python_3.x_selenium_selenium_chromedriver.txt |
Q:
pandas - filter only works on 1 row when used as a stored variable?
Having a strange issue with using a filter in loc.
example df:
Name trail
0 XYZ True
1 A True
2 B True
3 C True
# Trail filter
filter_trail = (df['trail'] == False)
# Set a row to False to check
df.at[3, 'trail'] = ... | pandas - filter only works on 1 row when used as a stored variable? | Having a strange issue with using a filter in loc.
example df:
Name trail
0 XYZ True
1 A True
2 B True
3 C True
# Trail filter
filter_trail = (df['trail'] == False)
# Set a row to False to check
df.at[3, 'trail'] = False
# use the filter, using loc because I will combine conditions
df.l... | [
"filter_trail is not created as a reference to the Dataframe, rather a boolean calculated value from one of trail column of the DF. Thereby, creating a new set of data, which was calculated from DF column, but not referencing it.\nTwo of the fellow stackoverflow contributors (comments above) and me as third tried o... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074166758_dataframe_pandas_python.txt |
Q:
physically stretch plot in horizontal direction in python
I want a simple x,y plot created with matplotlib stretched physically in x-direction.
The intention is to get a result were it is easier for me to detect features in the signal.
So I don't want to change any scales or values or limits. Just change the dista... | physically stretch plot in horizontal direction in python | I want a simple x,y plot created with matplotlib stretched physically in x-direction.
The intention is to get a result were it is easier for me to detect features in the signal.
So I don't want to change any scales or values or limits. Just change the distance between two gridpoint in my output file...
I want to do th... | [
"You can change the figure size by using plt.figure(figsize=(20,5)). See the documentation of the figure command.\n",
"I know, this is a bit out of the context. But if someone is looking for a solution while using pandas plot which internally uses matplotlib. Here is the solution.\ndf.plot('col_x', 'col_y', title... | [
16,
9,
4,
0
] | [] | [] | [
"matplotlib",
"plot",
"python",
"stretch"
] | stackoverflow_0020398920_matplotlib_plot_python_stretch.txt |
Q:
After you create a class, how do you add information from a csv to a python object, without using a module
I am struggling to understand classes/objects and using a csv with them.
I have a CSV with 26 rows, 1 being the header, the other containing rows of info. Small example below
id,food,food_print,cal1,cal2,expi... | After you create a class, how do you add information from a csv to a python object, without using a module | I am struggling to understand classes/objects and using a csv with them.
I have a CSV with 26 rows, 1 being the header, the other containing rows of info. Small example below
id,food,food_print,cal1,cal2,expi1999,expi2000,expi2001
1,bun,bun_bun,45.3434,199.32323,23.3333,45.4444,33.33333
2,burger,burger_bun,45.342343,20... | [
"Assuming all colums are filled in every row:\ntry:\nfor line in foodfile:\n foodfields = foodfile.readline().strip().split(',')\n meals.append(City(foodfields[1],foodfields[2],foodfields[3],foodfields[4],foodfields[5],foodfields[6],foodfields[7]))\n\n",
"true tone to avoid dynamic classes. Because your co... | [
0,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074167747_csv_python.txt |
Q:
How to read csv's into Pandas that use a quote separator but also non-escaped left and right double quotes that need to be ignored
I have CSV files that need to be read in that have some lines that read fine but others that look like this:
2022-10-04, "", some data in col3, moredata, "data in quotes, like the size... | How to read csv's into Pandas that use a quote separator but also non-escaped left and right double quotes that need to be ignored | I have CSV files that need to be read in that have some lines that read fine but others that look like this:
2022-10-04, "", some data in col3, moredata, "data in quotes, like the size for this thing is 23'' x \28" with this description, moredata
2022-10-05, "", some data in col3, moredata, "data in quotes, like the s... | [
"Given test.txt:\nstart_date, end_date, product_code, available, category_rank, brand,name,category,price\n2022-10-05,2022-10-10,3716372837,1.0,\"\",brand1,\"Puzzle, 300'' p, 23” x 15\\\", great\",Games,39.99\n\nDoing:\ndf = pd.read_csv('test.txt', escapechar='\\\\')\nprint(df)\n\nOutput:\n start_date end_date... | [
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074167634_csv_pandas_python.txt |
Q:
Trying to make a tkinter menu button that do multiple tasks
I've been trying to make a button in menu bar in the tkinter app and can't seem to figure out how to make this button make multiple tasks. I've tried the following, it forgets the frame correctly but don't execute the carr function.
from tkinter import *
... | Trying to make a tkinter menu button that do multiple tasks | I've been trying to make a button in menu bar in the tkinter app and can't seem to figure out how to make this button make multiple tasks. I've tried the following, it forgets the frame correctly but don't execute the carr function.
from tkinter import *
root = Tk()
menu_bar = Menu(root)
file_menu = Menu(menu_bar, tea... | [
"The proper solution is to create a function for the button.\ndef do_carr():\n frame.pack_forget()\n carr()\n...\nfile_menu.add_command(label=\"Carré\", command=do_carr)\n\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074166531_python_tkinter.txt |
Q:
Parsing List Elements into Multiple Lists in Python
I have managed to pull a list from a data source. The list elements are formatted like this (note the first number is NOT the index):
0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 ... | Parsing List Elements into Multiple Lists in Python | I have managed to pull a list from a data source. The list elements are formatted like this (note the first number is NOT the index):
0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 smoked cheese 200
etc.
This means when printed... | [
"If the goal is a dataframe, why not just make that rather than the two lists. If you turn your string into a Series, you can us pandas.Series.str.extract() to split it into the columns you want:\nimport pandas as pd\n\ns = '''0 cheese 100\n1 cheddar cheese 1100\n2 ... | [
2,
1,
1,
1,
1,
0
] | [] | [] | [
"list",
"pandas",
"parsing",
"python"
] | stackoverflow_0074166977_list_pandas_parsing_python.txt |
Q:
how to check if an object is a certain type in python
Im trying to make a method that checks if the object will be of a faculty type based from the faculty class. This is the code but im getting a syntax error?
def addFaculty(self, f_obj):
if f_obj isinstance(f_obj, Faculty):
return True
... | how to check if an object is a certain type in python | Im trying to make a method that checks if the object will be of a faculty type based from the faculty class. This is the code but im getting a syntax error?
def addFaculty(self, f_obj):
if f_obj isinstance(f_obj, Faculty):
return True
else:
self.directory.append(f_obj)
| [
"Try this:\ndef addFaculty(self, f_obj): \n return isinstance(f_obj, Faculty)\n\nor:\ndef addFaculty(self, f_obj):\n return type(f_obj) is Faculty \n\n",
"Class name not acceptable to use from method scope. For this purposes use __class__ attr of obj self.\ndef addFaculty(self, f_obj): \n if isinstance(f... | [
0,
0
] | [
"Alternative way to implement simular feature is to use __init_subclass__ method\nclass Faculty:\n dictionary= {}\n def __init_subclass__ (cls, **kwargs): \n Faculty.dictionary[cls.__name__] = cls\n \nclass New(Faculty):\n pass\n\nprint(Faculty.dictionary)\n\nOutput: {'New': (class '__main__.New')}\... | [
-1
] | [
"isinstance",
"methods",
"object",
"python",
"types"
] | stackoverflow_0074167697_isinstance_methods_object_python_types.txt |
Q:
How to get the most repated elements in a dataframe/array
I compiled a list of the top artists for every year across 14 years and I want to gather the top 7 for the 14 years combined so my idea was to gather them all in a dataframe then gather the most repeated artists for these years, but it didn't work out.
#Col... | How to get the most repated elements in a dataframe/array | I compiled a list of the top artists for every year across 14 years and I want to gather the top 7 for the 14 years combined so my idea was to gather them all in a dataframe then gather the most repeated artists for these years, but it didn't work out.
#Collecting the top 7 artists across the 14 years
artists = []
year... | [
"You're very close - you just need to flatten your list of lists into a single list, then call value_counts:\nartists_flat = [a for lst in artists for a in lst]\npd.Series(artists_flat).value_counts().head(n)\n\nYour current code is counting the occurrences of entire lists (as strings), rather than individual artis... | [
0,
0
] | [] | [] | [
"data_science",
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0073724397_data_science_dataframe_pandas_python_python_3.x.txt |
Q:
Python while loop not ending when list empty
I was trying to find out a way to perform in-order tree transversal iteratively without using a tuple. Not sure why but the list is going from [] to [None] and runs the while loop one more time
https://leetcode.com/problems/binary-tree-inorder-traversal/description/
de... | Python while loop not ending when list empty | I was trying to find out a way to perform in-order tree transversal iteratively without using a tuple. Not sure why but the list is going from [] to [None] and runs the while loop one more time
https://leetcode.com/problems/binary-tree-inorder-traversal/description/
def inorderTraversal(self, root: Optional[TreeNode])... | [
"I am assuming what you are trying to do here is convert a tree to an in-order list of elements to look at. It is possible you're trying to do something else, but if so, it is unclear.\ndef inOrderTraversal(ls: TreeNode) -> List[int]:\n // Recurse into the left branch\n if isinstance(ls.left, int):\n l... | [
0
] | [] | [] | [
"python",
"python_3.x",
"while_loop"
] | stackoverflow_0074167907_python_python_3.x_while_loop.txt |
Q:
I'm trying to update conda and get PermissionError(13, 'Access is denied')
I would like to update conda, anaconda, and python to the latest versions. I executed the following commands and received the following prompts. What's happening and how can I fix this? I appreciate the help
C:\Users\nabr>conda update --all... | I'm trying to update conda and get PermissionError(13, 'Access is denied') | I would like to update conda, anaconda, and python to the latest versions. I executed the following commands and received the following prompts. What's happening and how can I fix this? I appreciate the help
C:\Users\nabr>conda update --all
Solving environment: done
==> WARNING: A newer version of conda exists. <==
... | [
"I was having the same issue and I found some solutions to this error here.\nThe solutions included:\n\nrunning the Anaconda prompt as administrator and reinstalling Anaconda, then changing from 'for all users' to 'for myself' \"\ndeleting the pip folders in AppData/Temp\ninstalling python packages, dependencies or... | [
0
] | [
"I had this problem and solved. \nRun Anaconda Prompt as administrator. \n"
] | [
-1
] | [
"anaconda",
"conda",
"python"
] | stackoverflow_0053242903_anaconda_conda_python.txt |
Q:
How to convert a file into a list then into a dictionary in python
I have a file with each line containing a name and some numbers for instance
John, 55 , 77, 89
Sarah, 78, 45, 67
Joe, 40, 99, 63, 89,60
I was able to convert this to a list using split(). But I can’t figure out how to turn it to a dictionary from t... | How to convert a file into a list then into a dictionary in python | I have a file with each line containing a name and some numbers for instance
John, 55 , 77, 89
Sarah, 78, 45, 67
Joe, 40, 99, 63, 89,60
I was able to convert this to a list using split(). But I can’t figure out how to turn it to a dictionary from there. I have something like [‘John’, ‘55,’ ‘77,’… etc. How do I covert t... | [
"The quickest way is probably a dict comprehension.\nnn_list = ['John', 55 , 77, 89, 'Sarah', 78, 45, 67, 'Joe', 40, 99, 63]\nnn_dict = {block[0]:block[1:] for block in (nn_list[i:i+4] for i in range(0,len(nn_list),4))}\n\n",
"You can use the csv module and a dictionary comprehension:\nimport csv\n\nwith open(fil... | [
1,
0
] | [] | [] | [
"dictionary",
"file",
"python"
] | stackoverflow_0074167933_dictionary_file_python.txt |
Q:
How to Hot-Reload in ReactJS Docker
This might sound simple, but I have this problem.
I have two docker containers running. One is for my front-end and other is for my backend services.
these are the Dockerfiles for both services.
front-end Dockerfile :
# Use an official node runtime as a parent image
FROM node:8
... | How to Hot-Reload in ReactJS Docker | This might sound simple, but I have this problem.
I have two docker containers running. One is for my front-end and other is for my backend services.
these are the Dockerfiles for both services.
front-end Dockerfile :
# Use an official node runtime as a parent image
FROM node:8
WORKDIR /app
# Install dependencies
COP... | [
"Try this in your docker-compose.yml \nversion: \"3.2\"\n\nservices:\n\n frontend:\n build: ./frontend\n environment:\n CHOKIDAR_USEPOLLING: \"true\"\n volumes:\n - /app/node_modules\n - ./frontend:/app\n ports:\n - 80:3000\n depends_on: \n - backend\n\n backend: \n buil... | [
36,
1
] | [] | [] | [
"docker",
"node.js",
"python",
"reactjs"
] | stackoverflow_0061576659_docker_node.js_python_reactjs.txt |
Q:
Python Circle - Pixel by pixel
So, I saw a related 'topic' question on here, but it is using a different method.
Further, I understand there are more efficient algorithms out there such as Mid-point/Bresenham's.
Yet, at least thus far in my discovery, perhaps 'simple and traditional' is best for my needed end-poin... | Python Circle - Pixel by pixel | So, I saw a related 'topic' question on here, but it is using a different method.
Further, I understand there are more efficient algorithms out there such as Mid-point/Bresenham's.
Yet, at least thus far in my discovery, perhaps 'simple and traditional' is best for my needed end-point application.
Thus I put together t... | [
"I would iterate over the pixels themselves and not over polar coordinates in arbitrary steps:\nr_squared = r*r\nfor x1 in range(0, r):\n for y1 in range(0, r):\n if x1*x1 + y1*y1 < r_squared:\n img.putpixel((x + x1, y + y1), (0, 0, 0, 255))\n img.putpixel((x + x1, y - y1), (0, 0, 0, 255))\n img.... | [
2,
1
] | [] | [] | [
"graphics",
"python",
"python_imaging_library"
] | stackoverflow_0074164650_graphics_python_python_imaging_library.txt |
Q:
How can I add gunicorn so that I can deploy my flask application with docker-compose?
I already can run the docker-compose with flask. However, I really don't know how can I add gunicorn in the command so that it can be used. I already added it in my requirements.txt file. Here I can show you my docker-compose.yml... | How can I add gunicorn so that I can deploy my flask application with docker-compose? | I already can run the docker-compose with flask. However, I really don't know how can I add gunicorn in the command so that it can be used. I already added it in my requirements.txt file. Here I can show you my docker-compose.yml and Dockerfile.
docker-compose.yml
version: "3.7"
services:
waitfordb:
image: d... | [
"I have a flask app with gunicorn, docker and docker-compose and it works like this:\nDockerfile\nuser.app is the location in the directory and create_app() is defined in that file. In your case replace ENTRYPOINT with CMD.\nOther info here ...\nCMD gunicorn -b 0.0.0.0:5000 --timeout 120 --access-logfile - \"user.... | [
0
] | [] | [] | [
"amazon_ec2",
"docker",
"docker_compose",
"flask",
"python"
] | stackoverflow_0074168062_amazon_ec2_docker_docker_compose_flask_python.txt |
Q:
How do I insert results of a function into a locally stored database?
I've written a function that returns the Width, Height, and Dominant Color of an image, and I don't know how to store the results into a database. Here's the code I have so far:
import os
from colorthief import ColorThief
from PIL import Image
... | How do I insert results of a function into a locally stored database? | I've written a function that returns the Width, Height, and Dominant Color of an image, and I don't know how to store the results into a database. Here's the code I have so far:
import os
from colorthief import ColorThief
from PIL import Image
os.chdir("x")
def get_details():
for f in os.listdir("x"):
i... | [
"There are 3 general options to make a local \"database\":\n\nUse a SQL database such as sqlite3. This solution needs some configurations it is a relatively simple solution.\n\nUse a NoSQL type database such as MongoDB but it is more complicated to setup.\n\nFinal option (and least suggested but the simplest) is to... | [
0,
0
] | [] | [] | [
"database",
"python"
] | stackoverflow_0074165145_database_python.txt |
Q:
HE!P!!! How do I make a method that iterates through list and checks type to print based on the type
I want to make a method(showList) that iterates through a list called dictionary and based on the type of object it prints either student, faculty, or both. the parameters needs to be s(for students), f(for faculty... | HE!P!!! How do I make a method that iterates through list and checks type to print based on the type | I want to make a method(showList) that iterates through a list called dictionary and based on the type of object it prints either student, faculty, or both. the parameters needs to be s(for students), f(for faculty), and b(for both) and b needs to be default parameter for method. The object types are either Student or ... | [
"You can only return once from a given function. Since you said you want to print a string for each item in self.directory based on the type of the item, I think what you might want to do is:\ndef showList():\n for i in self.directory:\n if isinstance(i, Student) and isinstance(i, Faculty):\n ... | [
0
] | [] | [] | [
"list",
"loops",
"methods",
"python",
"types"
] | stackoverflow_0074168087_list_loops_methods_python_types.txt |
Q:
PyQt5 - QTime not changing values
I wanted to create a simple timer that gets shown to the screen and was using QTime to track the amount of time passed. However when I create a time with QTime(0, 0, 0) it will always stay at the initial value and will never change.
from PyQt5.QtCore import QTime
time = QTime(0, ... | PyQt5 - QTime not changing values | I wanted to create a simple timer that gets shown to the screen and was using QTime to track the amount of time passed. However when I create a time with QTime(0, 0, 0) it will always stay at the initial value and will never change.
from PyQt5.QtCore import QTime
time = QTime(0, 0, 0)
print(time.toString("hh:mm:ss")) ... | [
"From the documentation the function signature is...\nQTime QTime::addSecs(int s) const\n\nSo you need...\ntime = time.addSecs(20)\nprint(time.toString(\"hh:mm:ss\"))\n\n",
"There is a super simple fix to this. time.addSecs(20) returns a value. So do time = time.addSecs(20) instead. That will fix your problem.... | [
1,
1,
0
] | [] | [] | [
"pyqt5",
"python",
"qt"
] | stackoverflow_0074162826_pyqt5_python_qt.txt |
Q:
How to replace a random value from an array with another one
So I have this array:
TEST = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])
And I want to replace a single random number from the array with 6.
With an exact value I would replace him with:
TEST[0,0] = 6
But since it's a random number that alternate... | How to replace a random value from an array with another one | So I have this array:
TEST = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])
And I want to replace a single random number from the array with 6.
With an exact value I would replace him with:
TEST[0,0] = 6
But since it's a random number that alternates I cannot do that (or maybe I can and just don't know how)
We als... | [
"For a slightly different take, numpy.put() allows you to replace and value at the flattened index in an array.\nSo in the case of:\ntest = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,4,5]])\n\nyou could pick a number in the range 0 - 15 and put() your value there.\ntest = np.array([[1,2,3,4,5], [0,0,1,1,1], [0,1,2,... | [
2,
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074168051_arrays_numpy_python.txt |
Q:
Handling the token expiration in fastapi
I'm new with fastapi security and I'm trying to implement the authentication thing and then use scopes.
The problem is that I'm setting an expiration time for the token but after the expiration time the user still authenticated and can access services
import json
from jose ... | Handling the token expiration in fastapi | I'm new with fastapi security and I'm trying to implement the authentication thing and then use scopes.
The problem is that I'm setting an expiration time for the token but after the expiration time the user still authenticated and can access services
import json
from jose import jwt,JWTError
from typing import Optiona... | [
"I 'd wanted to comment on Unyime Etim's advice\nbut have no rating yet so this would be a separate answer\nI just wanted to add that jwt.decode has a built-in method to check \"exp\"\nand it does check it by default (https://github.com/mpdavis/python-jose/blob/96474ecfb6ad3ce16f41b0814ab5126d58725e2a/jose/jwt.py#L... | [
4,
2,
2,
1,
0
] | [] | [] | [
"fastapi",
"python",
"scope",
"security",
"token"
] | stackoverflow_0068811220_fastapi_python_scope_security_token.txt |
Q:
Proper way to document keys in TypedDict?
What is the proper way to document keys inside a TypedDict? I don't see much information inside PEP 589 – TypedDict.
I can think of a few solutions:
Document keys inside a docstring (is there a standard field to use here?):
class Foo(TypedDict):
"""
I am a docume... | Proper way to document keys in TypedDict? | What is the proper way to document keys inside a TypedDict? I don't see much information inside PEP 589 – TypedDict.
I can think of a few solutions:
Document keys inside a docstring (is there a standard field to use here?):
class Foo(TypedDict):
"""
I am a documented schema.
Keys:
key: This key h... | [
"If we look at the class typing.TypedDict(dict) signature in the documentation we see it's a class, as the official docs start by saying:\n\nTypedDict declares a dictionary type that expects all of its instances to have a certain set of keys\n\nSo documenting the TypedDict is straightforward because it also uses Cl... | [
1
] | [] | [] | [
"docstring",
"python",
"python_sphinx",
"sections",
"typeddict"
] | stackoverflow_0074129732_docstring_python_python_sphinx_sections_typeddict.txt |
Q:
Can cmath.sqrt be applied to a NumPy array?
I want to calculate the square root of a numpy array of negative numbers.
I tried with np.sqrt() but it gives error beacuse the domain.
Then, I found that for complex numbers you can use cmath.sqrt(x) but it also gives me an error.
Here's my code
import numpy as np
impor... | Can cmath.sqrt be applied to a NumPy array? | I want to calculate the square root of a numpy array of negative numbers.
I tried with np.sqrt() but it gives error beacuse the domain.
Then, I found that for complex numbers you can use cmath.sqrt(x) but it also gives me an error.
Here's my code
import numpy as np
import cmath
from cmath import sqrt
x = np.arange(-10... | [
"You could use numpy.emath.sqrt() which will work with negative numbers and return the complex square roots:\nimport numpy as np\n\nx = np.array([-4, -16, -25, 100, 64])\n\nnp.emath.sqrt(x)\n# array([ 0.+2.j, 0.+4.j, 0.+5.j, 10.+0.j, 8.+0.j])\n\n",
"Yes, you can iterate to perform cmath on individual elements ... | [
3,
3
] | [] | [] | [
"arrays",
"numpy",
"python",
"python_cmath",
"sqrt"
] | stackoverflow_0074168184_arrays_numpy_python_python_cmath_sqrt.txt |
Q:
How can I convert text to columns with Python?
I have this data:
Event|Time|Meta|Meet|Date
50 Y Free|22.30|U|IL NASA Winter Blast Off|Nov 30, 2018
100 Y Free|55.50|U|Greg's Super Splash|Jun 16, 2011
50 Y Breast|27.07|X|CCIW Swimming Championships|Feb 10, 2006
50 L Breast|33.70||1st Cyprus International Masters Swi... | How can I convert text to columns with Python? | I have this data:
Event|Time|Meta|Meet|Date
50 Y Free|22.30|U|IL NASA Winter Blast Off|Nov 30, 2018
100 Y Free|55.50|U|Greg's Super Splash|Jun 16, 2011
50 Y Breast|27.07|X|CCIW Swimming Championships|Feb 10, 2006
50 L Breast|33.70||1st Cyprus International Masters Swim Meet|Oct 22, 2016
100 Y Breast|58.97||CCIW Swimmin... | [
"rows = data.split() splits the entire file into a list of words. str.split() with no argument splits on whitespace. You probably want data = src.readlines() in the line above, which reads the file line by line into a list.\ndef beautify_data(swimmer_name):\n with open(f\"assets\\\\data\\\\{swimmer_name}.txt\", ... | [
2
] | [] | [] | [
"python",
"replace",
"split",
"string",
"strip"
] | stackoverflow_0074168271_python_replace_split_string_strip.txt |
Q:
How to run a Python script on Linux?
I'm a Windows user. I'm currently working on a Linux Mint machine. I tried running a python script the same way I would on Windows: I created a myscript.py file on the desktop and double clicked it, but it would just open it in a text editor.
The test script is very simple, the... | How to run a Python script on Linux? | I'm a Windows user. I'm currently working on a Linux Mint machine. I tried running a python script the same way I would on Windows: I created a myscript.py file on the desktop and double clicked it, but it would just open it in a text editor.
The test script is very simple, there is only one line:
input("Success!")
Th... | [
"Method one: some as Windows (not the best option)\nTell the file-manager to open files ending in .py in python /usr/bin/python3 (note the slash at the start).\nThen double click it.\nMethod two (not the best option)\nOpen a shell and type python3 «script name»\nMethod three (the preferred method)\n\nAdd #!/usr/bi... | [
1,
1,
0,
0
] | [] | [] | [
"linux",
"linux_mint",
"python",
"terminal"
] | stackoverflow_0071427901_linux_linux_mint_python_terminal.txt |
Q:
How do I use the Python keyboard module to detect a key press?
I am working on a self challenge of making a cash register in Python, and I'm looking to use the keyboard module for inputting values instead of typing them into the console. However, I think the keyboard module command I'm using to detect key presses ... | How do I use the Python keyboard module to detect a key press? | I am working on a self challenge of making a cash register in Python, and I'm looking to use the keyboard module for inputting values instead of typing them into the console. However, I think the keyboard module command I'm using to detect key presses is not becoming false after pressing the key, meaning the number I j... | [
"There are usually many different ways to code something. Some are better than others. In a problem that is based on keyboard input, like your cash register/adding machine project, I would go with an event-driven approach. Your sample code represents a polling approach. It can work, but it may not be as efficient.\... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0069792108_python.txt |
Q:
Query parameter setting with Swagger
How can I change the required fields (address, token_id, etc) to not be required like limit and offset in swagger?
This is specific for GET requests
model
class NFT(models.Model):
address = models.CharField(max_length=42)
owner_address = models.CharField(max_length=42)
... | Query parameter setting with Swagger | How can I change the required fields (address, token_id, etc) to not be required like limit and offset in swagger?
This is specific for GET requests
model
class NFT(models.Model):
address = models.CharField(max_length=42)
owner_address = models.CharField(max_length=42)
token_id = models.IntegerField()
t... | [
"Since drf-yasg follows the serializer definition, you can add required=False in the serializer\nclass NFTSerializer(serializers.ModelSerializer):\n\n address = serializers.CharField(required=False)\n token_id = serializers.IntegerField(required=False)\n\n class Meta:\n model = NFT\n fields =... | [
1
] | [] | [] | [
"django_rest_framework",
"drf_yasg",
"python",
"python_3.x",
"swagger"
] | stackoverflow_0074168139_django_rest_framework_drf_yasg_python_python_3.x_swagger.txt |
Q:
Conda Environment with specific Tensorflow and Numpy Version
I need to setup a conda environment for tensorflow. I do so via environment.yml file. I have to specify my version of tensorflow (latest 2.5.0) because otherwise conda installs tf 1.14. But because tensorflow seems not to work properly with the latest nu... | Conda Environment with specific Tensorflow and Numpy Version | I need to setup a conda environment for tensorflow. I do so via environment.yml file. I have to specify my version of tensorflow (latest 2.5.0) because otherwise conda installs tf 1.14. But because tensorflow seems not to work properly with the latest numpy version I want to use numpy 1.19 or older. With the following ... | [
"conda looks at the packages that you want to install, check their dependencies and then determines which versions will work together. Package maintainers thereby impose limits. If we do\nconda search --info tensorflow\nwe see that it has a dependency for tensorflow-base=2.5.0:\ntensorflow 2.5.0 mkl_py38hbe2df88_0\... | [
3,
0
] | [] | [] | [
"conda",
"environment",
"numpy",
"python",
"tensorflow"
] | stackoverflow_0068974406_conda_environment_numpy_python_tensorflow.txt |
Q:
Python Channelizer
After years of telling myself I would, I'm finally switching from MATLAB to Python. I am having difficulty finding a Python equivalent to MATLAB's Channelizer. Is there one?
A:
Yes, PyFilterBank will do the trick.
| Python Channelizer | After years of telling myself I would, I'm finally switching from MATLAB to Python. I am having difficulty finding a Python equivalent to MATLAB's Channelizer. Is there one?
| [
"Yes, PyFilterBank will do the trick.\n"
] | [
0
] | [] | [] | [
"filter",
"matlab",
"python",
"signal_processing"
] | stackoverflow_0074168310_filter_matlab_python_signal_processing.txt |
Q:
Add column in dataframe from another dataframe matching the id and based on condition in date columns pandas
My problem is a very complex and confusing one, I haven't been able to find the answer anywhere.
I basically have 2 dataframes, one is price history of certain products and the other is invoice dataframe th... | Add column in dataframe from another dataframe matching the id and based on condition in date columns pandas | My problem is a very complex and confusing one, I haven't been able to find the answer anywhere.
I basically have 2 dataframes, one is price history of certain products and the other is invoice dataframe that contains transaction data.
Sample Data:
Price History:
product_id updated price
id ... | [
"merge_asof is what you are looking for:\npd.merge_asof(\n invoice,\n price_history,\n left_on=\"transaction_date\",\n right_on=\"updated\",\n by=\"product_id\",\n)[[\"transaction_date\", \"product_id\", \"quantity\", \"price\"]]\n\n",
"merge_asof with arg direction\nmerged = pd.merge_asof(\n le... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074168054_dataframe_pandas_python.txt |
Q:
instead of summing the two values, it just repeats it
my code in python is supposed to sum the two variables and return a value, but it keeps returning the two numbers together:
A = input("insert a value: ")
B = input("insert another value: ")
if A >= B:
R == A + B
print ("this is the result", R)
else:
... | instead of summing the two values, it just repeats it | my code in python is supposed to sum the two variables and return a value, but it keeps returning the two numbers together:
A = input("insert a value: ")
B = input("insert another value: ")
if A >= B:
R == A + B
print ("this is the result", R)
else:
R == A - B
print ("this is the result", R)
input 1:... | [
"input() returns a string (str) object, so when you try to add A and B together, they end up being concatenated.\nYou need to cast the result from input() to an integer (int). Try something like this instead:\nA = int(input(\"insert a value: \"))\nB = int(input(\"insert another value: \"))\n\n"
] | [
0
] | [
"I don't write python code, but you need to cast the input from type String to Int\nA_INPUT = input(\"insert a value: \")\nB_INPUT = input(\"insert another value: \")\n\nA = int(A_INPUT)\nB = int(B_INPUT)\n\nif A >= B:\n R == A + B \n print (\"this is the result\", R)\nelse:\n R == A - B\n print (\"this... | [
-1
] | [
"if_statement",
"python",
"sum"
] | stackoverflow_0074168387_if_statement_python_sum.txt |
Q:
How to remove duplicates in a row that is separated by a space | Pandas
I just finished cleaning my data and I noticed that there are columns that have duplicate values in the rows that are separated by a space. I was wondering what is the best way to remove the space after the first value and then all values afte... | How to remove duplicates in a row that is separated by a space | Pandas | I just finished cleaning my data and I noticed that there are columns that have duplicate values in the rows that are separated by a space. I was wondering what is the best way to remove the space after the first value and then all values after it.
There are some columns that have multiple duplicates such as 42.35 42.2... | [
"\napplymap: apply in every cell\nx.split(\" \")[0]: choose the first value split by a space\n\ndf.applymap(lambda x: float(str(x).split(\" \")[0]))\n\n",
"You could replace with a regex that looks for digits followed by a space.\ndf.replace(r\"^(\\d+\\.\\d+) .*\", r\"\\1\", regex=True, inplace=True)\n\nYou could... | [
3,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074168308_dataframe_pandas_python.txt |
Q:
SMTP gets rejected in Python TCP socket but works in Telnet
I'm trying to implement an email verifier as a project and am fiddling with SMTP. However, when I try to connect to servers, I get the following:
554 smtp6.server.rpi.edu ESMTP not accepting messages
250 smtp6.server.rpi.edu Hello [IP Address Redacted], p... | SMTP gets rejected in Python TCP socket but works in Telnet | I'm trying to implement an email verifier as a project and am fiddling with SMTP. However, when I try to connect to servers, I get the following:
554 smtp6.server.rpi.edu ESMTP not accepting messages
250 smtp6.server.rpi.edu Hello [IP Address Redacted], pleased to meet you
550 5.0.0 Command rejected
550 5.0.0 Command... | [
"It's because you sent the HELO message before receiving the HELLO message from the server, doing the SMTP protocol in a wrong way.\nYour code may work for some sites, because it depends on a server implementation and network delays.\nI recommend using the standard library, stmplib.\nIf you insist your own code, re... | [
1
] | [] | [] | [
"python",
"smtp",
"telnet"
] | stackoverflow_0074167485_python_smtp_telnet.txt |
Q:
Achieving interface without inheritance in Python
I have a sorted linked list
class SortedLinkedList:
# ...
def insert(self, value: int):
# ...
if node.value > value:
self.add_before(node, value)
# ...
I would like to generalize the type of values that a Node can hold f... | Achieving interface without inheritance in Python | I have a sorted linked list
class SortedLinkedList:
# ...
def insert(self, value: int):
# ...
if node.value > value:
self.add_before(node, value)
# ...
I would like to generalize the type of values that a Node can hold from only ints to any object that overloads the > operat... | [
"What you're looking for is typing.Protocol.\nclass Sortable(Protocol):\n def __gt__(self, other) -> bool: ...\n\nWith this, any class that defines __gt__ will be detected as an implicit subtype of Sortable. Note that in Pythons >= 3.8, you may need to to make other positional:\nclass Sortable(Protocol):\n de... | [
6
] | [] | [] | [
"pylance",
"python",
"python_typing"
] | stackoverflow_0074168458_pylance_python_python_typing.txt |
Q:
Can't find soulution tkinter KeyError: 0
from tkinter import *
from tkinter import font
window = Tk ()
window.title(" ")
button = {}
name = -1
def click(number):
button[number].config(bg="gray")
print(number)
for x in range(15):
for y in range(15):
name = name + 1
button[name] = Button(... | Can't find soulution tkinter KeyError: 0 | from tkinter import *
from tkinter import font
window = Tk ()
window.title(" ")
button = {}
name = -1
def click(number):
button[number].config(bg="gray")
print(number)
for x in range(15):
for y in range(15):
name = name + 1
button[name] = Button(window, command=click(name), bg="white")
... | [
"Adding in command=click(name) doesn't work as you are trying to assign command to the value returned from click(name) (you are accidentally running the function, which is then causing the KeyError).\nInstead, try doing command=lambda: click(name)\n"
] | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074168465_python_tkinter.txt |
Q:
While loop wont run until tray icon is closed
import pystray
import PIL.Image
from datetime import datetime
from text_to_speech import speak
from time import time, sleep
import os
from gtts import gTTS
import vlc
image = PIL.Image.open('hourglass.jpg')
def on_clicked(icon, item):
icon.stop()
icon = pystray.I... | While loop wont run until tray icon is closed | import pystray
import PIL.Image
from datetime import datetime
from text_to_speech import speak
from time import time, sleep
import os
from gtts import gTTS
import vlc
image = PIL.Image.open('hourglass.jpg')
def on_clicked(icon, item):
icon.stop()
icon = pystray.Icon('Hourglass', image, menu=pystray.Menu(
... | [
"The icon.run() internally run a loop. So until this loop breaks (by closing the window) the code below will not be executed. If you want for the icon and the code below to run independently, you can use Threads.\nimport threading\n\ndef run_icon():\n icon = pystray.Icon('Hourglass', image, menu=pystray.Menu(\n ... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0073352530_python.txt |
Q:
module 'keras.engine' has no attribute 'Layer'
I tried to run matterport/MaskRCNN code but faced the following error
----> 6 from mrcnn.model import MaskRCNN
/usr/local/lib/python3.7/dist-packages/mrcnn/model.py in <module>()
253
254
--> 255 class ProposalLayer(KE.Layer):
256 """Receives anchor ... | module 'keras.engine' has no attribute 'Layer' | I tried to run matterport/MaskRCNN code but faced the following error
----> 6 from mrcnn.model import MaskRCNN
/usr/local/lib/python3.7/dist-packages/mrcnn/model.py in <module>()
253
254
--> 255 class ProposalLayer(KE.Layer):
256 """Receives anchor scores and selects a subset to pass as proposals
... | [
"I encountered this problem when I was running the project.\nhttps://github.com/matterport/Mask_RCNN\nIn the file model.py,\nthere was a line\nimport keras.engine as KE\nI changed it to\nimport keras.engine.topology as KE\nand the problem disappeared.\n",
"I found this in the github issue discussion and it worked... | [
9,
9,
6,
6,
5,
4,
2,
0
] | [
"I struggled for a bit with both the outdated Keras and Tensorflow versions on this Mask-RCNN repo.\nIf you want to use the current versions, instead of replacing lines I recommend you cloning the following repo:\nhttps://github.com/akTwelve/Mask_RCNN\nIt has been updated to run on tensorflow v2+ and keras v2+.\n"
... | [
-1
] | [
"artificial_intelligence",
"conv_neural_network",
"keras",
"machine_learning",
"python"
] | stackoverflow_0067905185_artificial_intelligence_conv_neural_network_keras_machine_learning_python.txt |
Q:
"Index out of range" error in Python when using for loop and conditionals to reject a value before creating another list
I'm extremely new to Python and coding in general. This program is trying to take a list of 6 input numbers and run each through an equation against an already initialized list of 6 numbers. How... | "Index out of range" error in Python when using for loop and conditionals to reject a value before creating another list | I'm extremely new to Python and coding in general. This program is trying to take a list of 6 input numbers and run each through an equation against an already initialized list of 6 numbers. However I also want to reject any user input that is less or equal to 0.
Resistance = [12, 16, 27, 39, 56, 81]
Current = []
Power... | [
"The \"Power\" list doesn't keep up with 'x' because the code trying to get x-th value out of it despite the fact that it doesn't exist.\nSo, I suggest that the code might be enhaced in two ways.\n\nDon't change lists before you are sure that the input is right. So, utilize an intermediate variable for input.\n\nTh... | [
2
] | [] | [] | [
"for_loop",
"if_statement",
"indexing",
"list",
"python"
] | stackoverflow_0074168515_for_loop_if_statement_indexing_list_python.txt |
Q:
How to solve the logistic regression model prediction error?
Given a data set of 13389 data records with "win" (binary) as the target variable, a logistic regression model with confusion matrix is built, but it comes out (1) only 4017 records are predicted (0,0) and (1,1) but no records in (0,1) and (1,0), and als... | How to solve the logistic regression model prediction error? | Given a data set of 13389 data records with "win" (binary) as the target variable, a logistic regression model with confusion matrix is built, but it comes out (1) only 4017 records are predicted (0,0) and (1,1) but no records in (0,1) and (1,0), and also (2) ValueError: y_true takes value in {'0', '1'} and pos_label i... | [
"\nI am not sure how you defined your y_test. But could you check this page for your confusion matrix? Your results shows that all of your predictions are true. However it should be better of using it with your y_true and y_pred as like here..\nhttps://scikit-learn.org/stable/modules/generated/sklearn.metrics.confu... | [
0
] | [] | [] | [
"confusion_matrix",
"python"
] | stackoverflow_0074168569_confusion_matrix_python.txt |
Q:
Master Password in Password Manager with Python
I've created a terminal-based password manager in which we enter the master password and then we can choose either we have to add a new password or view the existing passwords. I've created it with the help of cryptography.fernet.
The only problem I have is that when... | Master Password in Password Manager with Python | I've created a terminal-based password manager in which we enter the master password and then we can choose either we have to add a new password or view the existing passwords. I've created it with the help of cryptography.fernet.
The only problem I have is that when the master password is entered for the first time we... | [
"It's because Fernet(key) ignores extra bytes that you appended to the result of Fernet.generate_key(). If it had been implemented well, it should have thrown an exception.\nRefer to the 'Using passwords with Fernet' section at the end of their documentation.\nAs a side note, 'cryptography' is somewhat an opinionat... | [
0
] | [] | [] | [
"cryptography",
"fernet",
"password_manager",
"python"
] | stackoverflow_0074167317_cryptography_fernet_password_manager_python.txt |
Q:
EinopsError: Error while processing rearrange-reduction pattern "(b1 b2) h w c -> (b1 h) (b2 w) c"
I'm learning the basics of einops to incorporate in my code.
process = transforms.Compose([
transforms.Resize(225),
transforms.ToTensor()
])
cat = Image.open('cat.jpeg').convert('RGB')
cat = process(cat)
r... | EinopsError: Error while processing rearrange-reduction pattern "(b1 b2) h w c -> (b1 h) (b2 w) c" | I'm learning the basics of einops to incorporate in my code.
process = transforms.Compose([
transforms.Resize(225),
transforms.ToTensor()
])
cat = Image.open('cat.jpeg').convert('RGB')
cat = process(cat)
rearrange(cat, '(b1 b2) h w c -> (b1 h) (b2 w) c', b1=2, b2=2)
Raises the error:
EinopsError: Error whi... | [
"Einops message is exactly right in this case: in your pattern input has 4 dimensions: '(b1 b2) h w c', but you provide a tensor with only three dimensions.\nYou should process a batch of 4 images and stack them to get a 4 dim tensor. Your current transformation gets 3-dim tensor (single image) and returns 3-dim te... | [
1,
0
] | [] | [] | [
"einops",
"python"
] | stackoverflow_0074061942_einops_python.txt |
Q:
PyCharm won't import PyGame
I'm fairly new to python and decided to try PyGame only to find it won't import.
line 1, in <module>
import pygame
ModuleNotFoundError: No module named 'pygame'
I am on windows 10, I am using PyCharm Build #PE-182.3684.126, and I pip installed it through CMD. I have reinstalled PyG... | PyCharm won't import PyGame | I'm fairly new to python and decided to try PyGame only to find it won't import.
line 1, in <module>
import pygame
ModuleNotFoundError: No module named 'pygame'
I am on windows 10, I am using PyCharm Build #PE-182.3684.126, and I pip installed it through CMD. I have reinstalled PyGame twice so far and it still won... | [
"Open your PyCharm project. Go to File->Settings->Project->Project Interpreter. There will be a list of all installed modules on the current python environment you are using. If pygame is not listed there, it hasn't been installed for that PyCharm project (using that python environment).\n\nYou can install it by us... | [
3,
0,
0,
0
] | [] | [] | [
"pycharm",
"pygame",
"python"
] | stackoverflow_0053575888_pycharm_pygame_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.