content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
how to compare values of two dictionaries with list comprohension?
How to compare only the values of two dictonaries?
So I have this:
dict1 = {"appe": 3962.00, "waspeen": 3304.08}
dic2 = {"appel": 3962.00, "waspeen": 3304.08}
def compare_value_dict(dic):
return dic
def compare_value_dict2(dic2):
retur... | how to compare values of two dictionaries with list comprohension? | How to compare only the values of two dictonaries?
So I have this:
dict1 = {"appe": 3962.00, "waspeen": 3304.08}
dic2 = {"appel": 3962.00, "waspeen": 3304.08}
def compare_value_dict(dic):
return dic
def compare_value_dict2(dic2):
return dic2
def compare_dic(dic1, dic2):
if dic1 == dic2:
... | [
"You can't use == on the dict.values() dictionary view objects, as that specific type doesn't act like a set. Instead values_view_foo == values_view_bar is only ever true if both refer to the same dictionary view object. The contents don't matter.\nIt'll depend entirely on the types of values that the dictionary co... | [
5,
0
] | [
"you can go with the function dic.keys() that returns a vector containing all \"headers\" from your dictionary. And in the for loop, you can compare.\n"
] | [
-1
] | [
"dictionary",
"dictview",
"python"
] | stackoverflow_0074591555_dictionary_dictview_python.txt |
Q:
how add custom fild to all objects of django model
i have db where is companies and custom users, i want add custom field for different companies. Example: user have only NAME, if company is "EXAMPLE": user have fields only NAME and AGE, elif "VIN": user have only NAME and SIZE and AGE and WORK, else: only name. H... | how add custom fild to all objects of django model | i have db where is companies and custom users, i want add custom field for different companies. Example: user have only NAME, if company is "EXAMPLE": user have fields only NAME and AGE, elif "VIN": user have only NAME and SIZE and AGE and WORK, else: only name. How add this custom fields and update it. Thanks, sory fo... | [
"you must have separated models that refers OneToOne key to user model like this:\nclass Example(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE, )\n name = models.CharField(max_length=30)\n age= models.IntegerField()\n\nclass Vin(models.Model):\n user = models.OneToOneField(... | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0074591721_django_django_models_django_views_python.txt |
Q:
How Can we Loop Through a Range of Rolling Dates?
I did some Googling and figured out how to generate all Friday dates in a year.
# get all Fridays in a year
from datetime import date, timedelta
def allfridays(year):
d = date(year, 1, 1) # January 1st
d += timedelta(days = 8 - 2) ... | How Can we Loop Through a Range of Rolling Dates? | I did some Googling and figured out how to generate all Friday dates in a year.
# get all Fridays in a year
from datetime import date, timedelta
def allfridays(year):
d = date(year, 1, 1) # January 1st
d += timedelta(days = 8 - 2) # Friday
while d.year == year:
yield ... | [
"First, we have to figure out how to get the first Friday of a given year. Next, we will calculate the start, end days.\nimport datetime\n\nFRIDAY = 4 # Based on Monday=0\nWEEK = datetime.timedelta(days=7)\n\n\ndef first_friday(year):\n \"\"\"Return the first Friday of the year.\"\"\"\n the_date = datetime.d... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074586200_python_python_3.x.txt |
Q:
write('\n') command does not deposit new line
I am working on a convertor file in colab python. When creating the txt file on specific places I need it to write down the 0 and change line, although it does not.
Please help, here is my code:
f=open('dimac_outfs1.txt')
with open('dimac_outfs1.txt','a') as writefile:... | write('\n') command does not deposit new line | I am working on a convertor file in colab python. When creating the txt file on specific places I need it to write down the 0 and change line, although it does not.
Please help, here is my code:
f=open('dimac_outfs1.txt')
with open('dimac_outfs1.txt','a') as writefile:
for i in range(len(my_array)):
if my_array[i... | [
"If I understand this correctly, you command does not work.\nI think if you check the debugger you will notice that there is an EOL error in :\n else:\n writefile.write(str(str(my_array[i] + '\\n')) \n\nYou are missing a parenthesis.\nOtherwise, the\nwith open(<file>,'a') as f:\nf.write(str(i)+'\\n')\n\nworks ... | [
1
] | [] | [] | [
"arrays",
"file",
"python"
] | stackoverflow_0074591656_arrays_file_python.txt |
Q:
Django mail_admins not sending an email
i have tried using send_mail and it work properly (its html showing value '1') but When i access localhost:8000/emailAdmins , its showing a 'none' word in html, please help me why my mail_admins doesn't work
My setting
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='myemail@gma... | Django mail_admins not sending an email | i have tried using send_mail and it work properly (its html showing value '1') but When i access localhost:8000/emailAdmins , its showing a 'none' word in html, please help me why my mail_admins doesn't work
My setting
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='myemail@gmail.com'
EMAIL_HOST_PASSWORD='password'
EMAIL_... | [
"Add this line with your email configuration it worked for me\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0055015391_django_python.txt |
Q:
how to compare variable in different columns pandas
I want to compare three variable in three dataframe columns. but it gave me an error TypeError: unhashable type: 'Series'. below is my code
import pandas as pd
df = pd.DataFrame(columns=['Entry','Middle','Exit'])
entry_value = '17.98'
middle_value = '12.16'
exit_... | how to compare variable in different columns pandas | I want to compare three variable in three dataframe columns. but it gave me an error TypeError: unhashable type: 'Series'. below is my code
import pandas as pd
df = pd.DataFrame(columns=['Entry','Middle','Exit'])
entry_value = '17.98'
middle_value = '12.16'
exit_value = '1.2'
df = df.append({'Entry' : entry_value , 'Mi... | [
"You can search for a column but if you want to search for multiple columns you must either convert them to a single list or define them as a single series.\nif entry_value in df[['Entry','Middle','Exit']].stack().to_list():\n print('entry')\nelif middle_value in df[['Entry','Middle','Exit']].stack().to_list():\... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074591879_dataframe_pandas_python.txt |
Q:
Runtime error not showing when using asyncio to run discord bot
I'm developing discord bot with discord.py==2.1.0.
I use cog to write the main function that I wanna use, but I found when the whole bot is wrapped in async function and called by asyncio.run(), my terminal won't show any error message when there is ... | Runtime error not showing when using asyncio to run discord bot | I'm developing discord bot with discord.py==2.1.0.
I use cog to write the main function that I wanna use, but I found when the whole bot is wrapped in async function and called by asyncio.run(), my terminal won't show any error message when there is any runtime error in my cog script.
Here is the example application. ... | [
"Client.start() doesn't configure logging, so if you want to use that then you have to do it yourself (there's setup_logging to add a basic config). run() configures logging for you.\nFor more info, read the docs. https://discordpy.readthedocs.io/en/stable/logging.html?highlight=logging\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074591873_discord_discord.py_python.txt |
Q:
How to generate perlin noise in pygame?
I am trying to make a survival game and I have a problem with perlin noise. My program gives me this:
But I want something like islands or rivers.
Here's my code:
#SetUp#
import pygame, sys, random
pygame.init()
win = pygame.display.set_mode((800, 600))
pygame.display.set_c... | How to generate perlin noise in pygame? | I am trying to make a survival game and I have a problem with perlin noise. My program gives me this:
But I want something like islands or rivers.
Here's my code:
#SetUp#
import pygame, sys, random
pygame.init()
win = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Isom')
x = 0
y = 0
s = 0
tilel = list... | [
"image of randomly genrated terrain\ncode for perlin noise in pygame:\n from PIL import Image\n import numpy as np\n from perlin_noise import PerlinNoise\n import random\n import pygame\n pygame.init()\n\n noise = PerlinNoise(octaves=6, seed=random.randint(0, 100000))\n xpix, ypix = 500, 500\n pic = [[nois... | [
1,
0,
0
] | [] | [] | [
"perlin_noise",
"pygame",
"python"
] | stackoverflow_0070084741_perlin_noise_pygame_python.txt |
Q:
What is the most efficient way to generate a list of random numbers all within a range that have a fixed sum so that their boundaries are approached?
I am trying to generate a list of 12 random weights for a stock portfolio in order to determine how the portfolio would have performed in the past given different we... | What is the most efficient way to generate a list of random numbers all within a range that have a fixed sum so that their boundaries are approached? | I am trying to generate a list of 12 random weights for a stock portfolio in order to determine how the portfolio would have performed in the past given different weights assigned to each stock. The sum of the weights must of course be 1 and there is an additional restriction: each stock must have a weight between 1/24... | [
"The following works. Particularly confusing to me is that np.empty(12) seemed to always return the same array. So once it had been initialized, it stayed the same.\nThis seems to produce numbers above 0.22 reasonably often.\nimport numpy as np\nfrom random import random, seed\n\n# boundaries on weightings\nn = 1... | [
0,
0
] | [] | [] | [
"algorithm",
"numpy",
"python",
"random",
"random_seed"
] | stackoverflow_0074573355_algorithm_numpy_python_random_random_seed.txt |
Q:
Dash Choosing an ID and then Make Plot with Multiple Sliders
I have a dataset which is similar to below one. Please note that there are multiple values for a single ID.
import pandas as pd
import numpy as np
import random
df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='20min... | Dash Choosing an ID and then Make Plot with Multiple Sliders | I have a dataset which is similar to below one. Please note that there are multiple values for a single ID.
import pandas as pd
import numpy as np
import random
df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='20min'),
'SBP':[random.uniform(110, 160) for n in ra... | [
"The solution below only requires vey minor modifications to your example code. It essentially filters the original dataframe twice (once for TIME_OF_DAY='Night', and once for TIME_OF_DAY='Morning') and concatenates them before plotting.\nI've also modified the bins in the to_day_period function to only produce two... | [
1
] | [] | [] | [
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074448717_plotly_plotly_dash_python.txt |
Q:
Why do I get this "sheet" not found error?
import openpyxl as rp
ton1 = rp.load_workbook("transactions.xlsx")
gol = ton1["Sheet1"]
joi = sheet["a1"]
print(joi.value)
Following mosh course ...stuck with this...need help
A:
The error NameError: name 'sheet' is not defined is legit. If you want to read from an... | Why do I get this "sheet" not found error? | import openpyxl as rp
ton1 = rp.load_workbook("transactions.xlsx")
gol = ton1["Sheet1"]
joi = sheet["a1"]
print(joi.value)
Following mosh course ...stuck with this...need help
| [
"The error NameError: name 'sheet' is not defined is legit. If you want to read from an Excel spreadsheet in python/openpyxl, you need to define it first and in your case, that is gol.\nYou can try this :\nimport openpyxl as rp\n\nton1 = rp.load_workbook(\"transactions.xlsx\")\n\ngol = ton1[\"Sheet1\"]\n\njoi = gol... | [
0
] | [] | [] | [
"nameerror",
"openpyxl",
"python"
] | stackoverflow_0074592073_nameerror_openpyxl_python.txt |
Q:
BadRequestKeyError werkzeug.exceptions.BadRequestKeyError: KeyError: 'nume_pacient'
I want to get the text from my input with name="nume_pacient" when pressing the button, to pass it to python code and use it in a query in a database; I want the results to be loaded in the same page.
HTML PAGE:
{% extends "base.ht... | BadRequestKeyError werkzeug.exceptions.BadRequestKeyError: KeyError: 'nume_pacient' | I want to get the text from my input with name="nume_pacient" when pressing the button, to pass it to python code and use it in a query in a database; I want the results to be loaded in the same page.
HTML PAGE:
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{%block content %}
<h1>This is the home p... | [
"Don't add a tags inside buttons (not only in form but everywhere), provide action attribute to form:\n<form method=\"POST\" action=\"/pacienti/cautare\">\n <input type=\"text\" name=\"nume_pacient\">\n <button type=\"submit\">Cautare Pacient</button>\n</form> \n\nThen in your python code you need to get ... | [
0
] | [] | [] | [
"api",
"flask",
"html",
"post",
"python"
] | stackoverflow_0074591157_api_flask_html_post_python.txt |
Q:
Access pandas masks in a dictionary
I have a dictionary containing several pandas masks as strings for a specific dataframe, but I can't find a way to use those masks.
Here is a short reproducible example :
df = pd.DataFrame({'age' : [10, 24, 35, 67], 'strength' : [0 , 3, 9, 4]})
masks = {'old_strong' : "(df['ag... | Access pandas masks in a dictionary | I have a dictionary containing several pandas masks as strings for a specific dataframe, but I can't find a way to use those masks.
Here is a short reproducible example :
df = pd.DataFrame({'age' : [10, 24, 35, 67], 'strength' : [0 , 3, 9, 4]})
masks = {'old_strong' : "(df['age'] >18) & (df['strength'] >5)",
... | [
"Use DataFrame.query with changed dictionary:\nmasks = {'old_strong' : \"(age >18) & (strength >5)\",\n 'young_weak' : \"(age <18) & (strength <5)\"}\n\nprint (df.query(masks['young_weak']))\n age strength\n0 10 0\n\n",
"Another way is to set up the masks as functions (lambda expressions) inst... | [
6,
1,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0056456780_pandas_python.txt |
Q:
How to select, inside a df, only columns that have numeric values
i have multiple columns and want to see inside them what are the null values. then i want to know if columns that have null values are numeric
df.isnull().sum() -> gives me the sum of null values inside the df (question 2 - in pandas the result are ... | How to select, inside a df, only columns that have numeric values | i have multiple columns and want to see inside them what are the null values. then i want to know if columns that have null values are numeric
df.isnull().sum() -> gives me the sum of null values inside the df (question 2 - in pandas the result are only the top 5 and last 5 colums; How can i see all columns? )
then fro... | [
"1st, you can type 'df.info()'\nThere is about null data and amount of index.\nIf it is small data,\nyou can check like this\nfor i in range(len(df.index)):\n for j in range(len(df.columns)):\n if df.isna().iloc[i][j] == True:\n print(f'index is {i}, column is {df.columns[j]}')\n\nbut if it is ... | [
0
] | [] | [] | [
"data_cleaning",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074576055_data_cleaning_dataframe_pandas_python.txt |
Q:
How to scrape the table of states?
I am trying to scrape the table from:
https://worldpopulationreview.com/states
My code:
from bs4 import BeautifulSoup
import requests
import pandas as pd
url = 'https://worldpopulationreview.com/states'
page = requests.get(url)
soup = BeautifulSoup(page.text,'lxml')
table = soup.... | How to scrape the table of states? | I am trying to scrape the table from:
https://worldpopulationreview.com/states
My code:
from bs4 import BeautifulSoup
import requests
import pandas as pd
url = 'https://worldpopulationreview.com/states'
page = requests.get(url)
soup = BeautifulSoup(page.text,'lxml')
table = soup.find('table', {'class': 'jsx-a3119e4553b... | [
"The table data is dynamically loaded by JavaScript and bs4 can't render JS but you can do the job bs4 with an automation tool something like selenium and grab the table using pandas DataFrame.\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom selenium.webdriver.... | [
3,
2
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074591839_beautifulsoup_python_web_scraping.txt |
Q:
Periodic task in Qt without interrupting events
I have a graphic application in python using QWidget. The user can change elements by moving the mouse (using mouseMoveEvent), and the program should periodically (e.g., once per second) compute a function update_forces based on these elements.
Problem: the mouseMove... | Periodic task in Qt without interrupting events | I have a graphic application in python using QWidget. The user can change elements by moving the mouse (using mouseMoveEvent), and the program should periodically (e.g., once per second) compute a function update_forces based on these elements.
Problem: the mouseMoveEvent doesn't trigger as often while update_forces is... | [
"The solution is to use multiprocessing rather than threading.\nfrom multiprocessing import Process\nif __name__ == '__main__':\n p = Process(target=updater, args=())\n p.start()\n\ndef updater(queue,test):\n while(True):\n update_forces()\n time.sleep(1)\n\nThe problem with this is that no d... | [
0
] | [] | [] | [
"pyqt",
"python",
"qt",
"qwidget"
] | stackoverflow_0074590391_pyqt_python_qt_qwidget.txt |
Q:
PyCharm 2022.1.2 does not hit the debug breakpoint with Django
I can't get Python debugger to work on PyCharm 2022.1.2 with Django 4.
When I set the breakpoint inside the view function and then call this view in the browser, nothing happens when started in debug mode...
breakpoint_selected
However breakpoint is hi... | PyCharm 2022.1.2 does not hit the debug breakpoint with Django | I can't get Python debugger to work on PyCharm 2022.1.2 with Django 4.
When I set the breakpoint inside the view function and then call this view in the browser, nothing happens when started in debug mode...
breakpoint_selected
However breakpoint is hit when I set it for import.
breakpoint_hit
I have 2 configurations, ... | [
"Solved this by deleting the .idea directory from top-level django project dir. Not sure what were the mechanics behind it, but it worked and now breakpoints work perfectly.\n"
] | [
0
] | [] | [] | [
"breakpoints",
"debugging",
"django",
"pycharm",
"python"
] | stackoverflow_0074582147_breakpoints_debugging_django_pycharm_python.txt |
Q:
How to use pyspark to convert row array into multiple columns?
I've raw data like this:
Column A
Column B
"A:1, B:2, C:3"
XXX
The result I want is like this:
Column A
A
B
C
Column B
"A:1, B:2, C:3"
1
2
3
XXX
Can anyone help with pyspark code?
A:
df =spark.createDataFrame([
(78,'"A:1, B:2, C:3"'),
],
('id',... | How to use pyspark to convert row array into multiple columns? | I've raw data like this:
Column A
Column B
"A:1, B:2, C:3"
XXX
The result I want is like this:
Column A
A
B
C
Column B
"A:1, B:2, C:3"
1
2
3
XXX
Can anyone help with pyspark code?
| [
"df =spark.createDataFrame([\n(78,'\"A:1, B:2, C:3\"'),\n],\n('id', 'ColumnA'))\n\nReplace the \" with nothing. Split the resulting string with , and this will give you a list. Iterate the list elements converting them to lists by splitting with : and make all those lists of StructType. Explode the list. group by ... | [
0,
0
] | [] | [] | [
"apache_spark_sql",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074543049_apache_spark_sql_dataframe_pyspark_python.txt |
Q:
How to create a dataframe from a list of lists?
I need to create a dataframe from a list which contains 10 stocks data in a list.. but the required format is all items should be listed in one column instead of each column for each element.
The required format should look like this image below,
I tried this (the e... | How to create a dataframe from a list of lists? | I need to create a dataframe from a list which contains 10 stocks data in a list.. but the required format is all items should be listed in one column instead of each column for each element.
The required format should look like this image below,
I tried this (the entire code),
import openpyxl
import pandas as pd
xl ... | [
"Each list inside the list will be a new column. If you convert these lists into a single list, you can get the output you want. You can use:\ndf=pd.DataFrame([i for sublist in all_cols_list for i in sublist])\n\n"
] | [
1
] | [] | [] | [
"openpyxl",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074592291_openpyxl_pandas_python_python_3.x.txt |
Q:
Why Rust HashMap is slower than Python dict?
I wrote scripts performing the same computations with dict and hashmap in Rust and in Python. Somehow the Python version is more than 10x faster. How is that happens?
Rust script:
`
use std::collections::HashMap;
use std::time::Instant;
fn main() {
let now = Instan... | Why Rust HashMap is slower than Python dict? | I wrote scripts performing the same computations with dict and hashmap in Rust and in Python. Somehow the Python version is more than 10x faster. How is that happens?
Rust script:
`
use std::collections::HashMap;
use std::time::Instant;
fn main() {
let now = Instant::now();
let mut h = HashMap::new();
for... | [
"Rust by default doesn't have optimizations enabled, because it's annoying for debugging. That makes it, in debug mode, slower than Python. Enabling optimizations should fix that problem.\nThis behaviour is not specific to Rust, it's the default for most compilers (like gcc/g++ or clang for C/C++, both require the ... | [
0
] | [] | [] | [
"hashmap",
"python",
"rust"
] | stackoverflow_0074592062_hashmap_python_rust.txt |
Q:
Simple system to track hours worked
I am a total beginner and I think I underestimated my little project.
I am trying to implement a simple attendance system that will give me the hours worked per day and later per month.
I am using a Raspberry pi 3 b+ and RC522 Rfid reader plus 16x2 lcd display.
The data ist stor... | Simple system to track hours worked | I am a total beginner and I think I underestimated my little project.
I am trying to implement a simple attendance system that will give me the hours worked per day and later per month.
I am using a Raspberry pi 3 b+ and RC522 Rfid reader plus 16x2 lcd display.
The data ist stored in a database using MariaDB.
The idea ... | [
"I would expect the database would only store events. These events would be from when they touched the RFID. The card would have an ID/employee number.\nProcessing the database information would allow the calculation of who is on shift and the length of shifts worked etc.\n\nIf there was an odd number of entries fo... | [
0
] | [] | [] | [
"mariadb",
"python",
"raspberry_pi",
"raspberry_pi3",
"rfid"
] | stackoverflow_0074591121_mariadb_python_raspberry_pi_raspberry_pi3_rfid.txt |
Q:
Python Dataframe find the file type, choose the correct pd.read_ and merge them
I have a list of files to be imported into the data frame
cdoe:
# list contains the dataset name followed by the column name to match all the datasets; this list keeps changing and even the file formats. These dataset file names are pr... | Python Dataframe find the file type, choose the correct pd.read_ and merge them | I have a list of files to be imported into the data frame
cdoe:
# list contains the dataset name followed by the column name to match all the datasets; this list keeps changing and even the file formats. These dataset file names are provided by the user, and they are unique.
# First: find the file extension format and... | [
"The file type is just the three or four letters at the end of the file name, so the simplest way to do this would just be:\nif file_list[i].endswith('csv'):\n\netc.\nOther commons options would be os.path.splitext or the suffix attribute of a Path object from the built-in os and pathlib libraries respectively.\nTh... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074591735_dataframe_pandas_python.txt |
Q:
group DataFrame and increment group id if the number of rows have 3 consecutives same value
I have a data frame that looks as follows:
import pandas as pd
max_skip=2
data = {'col1':['NT', 'NT', 'NT', 'T','T','T','NT', 'NT', 'T','T','T','NT', 'NT', 'NT',"T",'T','T','T','NT','NT']}
# Create DataFrame
df = pd.DataF... | group DataFrame and increment group id if the number of rows have 3 consecutives same value | I have a data frame that looks as follows:
import pandas as pd
max_skip=2
data = {'col1':['NT', 'NT', 'NT', 'T','T','T','NT', 'NT', 'T','T','T','NT', 'NT', 'NT',"T",'T','T','T','NT','NT']}
# Create DataFrame
df = pd.DataFrame(data)
df
I would like to group those data with the following rule:
If the number of co... | [
"I believe this can be done with one line, but it works.\ndf['lenghts'] = df.groupby(((df.col1 != df.col1.shift())).cumsum()).transform('size')\ndf['group']=df.groupby(np.where((df['col1']=='NT') & (df['lenghts']>max_skip),0,1)).ngroup()\ndf['cumsum_']=df.groupby(['group'])['group'].cumsum()\ndf['group']=np.where((... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074587652_dataframe_pandas_python.txt |
Q:
How do I click on an item on my google search page with Selenium Python?
Good time of the day!
Faced with a seemingly simple problem,
But it’s been a while, and I’m asking for your help.
I work with Selenium on Python and I need to curse about
20 items on google search page by random request.
And I’ll give you an ... | How do I click on an item on my google search page with Selenium Python? | Good time of the day!
Faced with a seemingly simple problem,
But it’s been a while, and I’m asking for your help.
I work with Selenium on Python and I need to curse about
20 items on google search page by random request.
And I’ll give you an example of the elements below, and the bottom line is, once the elements are r... | [
"In case iDjcJe IX9Lgd wwB5gf are a fixed class name values of that element all you need is to use CSS_SELECTOR instead of CLASS_NAME with a correct syntax of CSS Selectors.\nSo, instead of driver.find_element(By.CLASS_NAME, \"iDjcJe IX9Lgd wwB5gf\") try using this:\ndriver.find_element(By.CSS_SELECTOR, \".iDjcJe.I... | [
0
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074585644_css_selectors_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
Pandas for-loop with a list of columns
I'm trying to open links in my dataframe using selenium webdriver, the dataframe 'df1' looks like this:
user
repo1
repo2
repo3
0
breed
cs149-f22
kattis2canvas
grpc-maven-skeleton
1
GrahamDumpleton
mod_wsgi
wrapt
NaN
The links I want to open include the content in column '... | Pandas for-loop with a list of columns | I'm trying to open links in my dataframe using selenium webdriver, the dataframe 'df1' looks like this:
user
repo1
repo2
repo3
0
breed
cs149-f22
kattis2canvas
grpc-maven-skeleton
1
GrahamDumpleton
mod_wsgi
wrapt
NaN
The links I want to open include the content in column 'user' and one of 3 'repo' columns... | [
"You're getting the KeyError because there is no column named repro_name.\nYou need to replace row['repo_name'] with row[repo_name].\nTry this :\nimport pandas as pd\nfrom selenium import webdriver\n\ndf1= pd.DataFrame({'user': ['breed', 'GrahamDumpleton'],\n 'repo1': ['cs149-f22', 'mod_wsgi'],\n 'repo2': ['kattis2... | [
0,
0
] | [] | [] | [
"for_loop",
"pandas",
"python",
"selenium_webdriver"
] | stackoverflow_0074592293_for_loop_pandas_python_selenium_webdriver.txt |
Q:
zip file and avoid directory structure
I have a Python script that zips a file (new.txt):
tofile = "/root/files/result/"+file
targetzipfile = new.zip # This is how I want my zip to look like
zf = zipfile.ZipFile(targetzipfile, mode='w')
try:
#adding to archive
zf.write(tofile)
finally:
zf.close()
Whe... | zip file and avoid directory structure | I have a Python script that zips a file (new.txt):
tofile = "/root/files/result/"+file
targetzipfile = new.zip # This is how I want my zip to look like
zf = zipfile.ZipFile(targetzipfile, mode='w')
try:
#adding to archive
zf.write(tofile)
finally:
zf.close()
When I do this I get the zip file. But when I ... | [
"The zipfile.write() method takes an optional arcname argument that specifies what the name of the file should be inside the zipfile\nI think you need to do a modification for the destination, otherwise it will duplicate the directory. Use :arcname to avoid it. try like this:\nimport os\nimport zipfile\n\ndef zip(s... | [
79,
20,
14,
9,
6,
6,
4,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0027991745_python_zip.txt |
Q:
Don't use empty/none variables in method/class
I have a class that looks something like:
@dataclass
class MyClass:
df1: pd.Series = None
df2: pd.Series = None
df3: pd.Series = None
df4: pd.Series = None
df5: pd.Series = None
@property
def series_mean(self) -> pd.Series:
ser... | Don't use empty/none variables in method/class | I have a class that looks something like:
@dataclass
class MyClass:
df1: pd.Series = None
df2: pd.Series = None
df3: pd.Series = None
df4: pd.Series = None
df5: pd.Series = None
@property
def series_mean(self) -> pd.Series:
series_mean = (
self.df1
+ self... | [
"Put them in a tuple instead and filter on None. Then you can easily both sum and and query len from the filtered tuple.\nfrom typing import Tuple\n\n@dataclass\nclass MyClass:\n dfs: Tuple[pd.Series, pd.Series, pd.Series, pd.Series, pd.Series] = (None, None, None, None, None)\n\n @property\n def series_me... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074592371_python.txt |
Q:
bytes representation to string object while read with PyPDF2
I read some PDF files and unfortunately, I am using only PyPDF2.
with open(filename1, 'rb') as pdfFileObj:
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
print(pdfReader.numPages)
pageObj = pd... | bytes representation to string object while read with PyPDF2 | I read some PDF files and unfortunately, I am using only PyPDF2.
with open(filename1, 'rb') as pdfFileObj:
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
print(pdfReader.numPages)
pageObj = pdfReader.getPage(0)
gg = pageObj.extractText()
prin... | [
"A solution would be to replace all \\x00 with \"\" by using re.sub('\\x00','',gg) so I have only the text. If there is another more efficient way, I would like to have a look.\n"
] | [
0
] | [] | [] | [
"pypdf2",
"python"
] | stackoverflow_0074592019_pypdf2_python.txt |
Q:
Adding Multiple Columns in Single groupby in Pandas
Dataset image
Please help, I have a dataset in which I have columns Country, Gas and Year from 2019 to 1991. Also attaching the snapshot of the dataset. I want to answer a question that I want to add all the values of a country column wise? For example, for Afgha... | Adding Multiple Columns in Single groupby in Pandas | Dataset image
Please help, I have a dataset in which I have columns Country, Gas and Year from 2019 to 1991. Also attaching the snapshot of the dataset. I want to answer a question that I want to add all the values of a country column wise? For example, for Afghanistan, value should come 56.4 under 2019 (adding 28.79 +... | [
"If you don't specify the column, it will sum all the numeric column.\ndf.groupby(by='Country').sum() \n\n 2019 2020 ...\nCountry\nAfghanistan 56.40 32.4 ...\nAlbania 17.31 12.5 ...\nAlgeria 558.67 241.5 ...\nAndorra 1.18 1.5 ...\nAngola 256.10... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074589124_dataframe_pandas_python.txt |
Q:
How do I split a file into lines by spaces using the Tkinter library in Python?
I need to split a file into lines by spaces, using Tkinter's Text widget and I tried this:
Text = Text.split(sep='\n'),
but I get the error "type object 'Text' has no attribute 'split'" please, tell me how to solve this
I tried to con... | How do I split a file into lines by spaces using the Tkinter library in Python? | I need to split a file into lines by spaces, using Tkinter's Text widget and I tried this:
Text = Text.split(sep='\n'),
but I get the error "type object 'Text' has no attribute 'split'" please, tell me how to solve this
I tried to convert Text to string but no result
| [
"You need to get the data out of the text widget with the get method, and then call split on what is returned.\ndata = the_text_widget.get(\"1.0\", \"end-1c\")\nText = data.split(sep=\"\\n\")\n\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074591782_python_tkinter.txt |
Q:
How to check whether string a is a substring of but not equal to string b?
I know that if we would like to know whether string a is contained in b we can use:
a in b
When a equals to b, the above express still returns True. I would like an expression that would return False when a == b and return True when a is a... | How to check whether string a is a substring of but not equal to string b? | I know that if we would like to know whether string a is contained in b we can use:
a in b
When a equals to b, the above express still returns True. I would like an expression that would return False when a == b and return True when a is a substring of b. So I used the following expression:
a in b and a != b
I just w... | [
"Not sure how efficient direct string comparisons are in Python, but assuming they are O(n) this should be reasonably efficient and still readable :\nlen(a) < len(b) and a in b\n\nLikes the other answers it's also O(n), but the length operation should be O(1). It should also be better suited for edge cases (e.g. a ... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0044393537_python.txt |
Q:
How can I make a discord bot take a message and turn it into a varable?
Please be forgivable with my code, this is my first ever project with py. I'd like it to turn a message user like "/channel http://youtube.com@youtube" to a variable like "channelID" that can be used later in the py.
I'm working with this so f... | How can I make a discord bot take a message and turn it into a varable? | Please be forgivable with my code, this is my first ever project with py. I'd like it to turn a message user like "/channel http://youtube.com@youtube" to a variable like "channelID" that can be used later in the py.
I'm working with this so far.
import discord
import re
import easygui
from easygui import *
from re im... | [
"discord.Message.content is a str and can't be called like a function i.e., message.content().\nUse channelURL = message.content instead.\nRemember to enable message content intents.\n"
] | [
2
] | [] | [] | [
"bots",
"discord.py",
"python"
] | stackoverflow_0074592407_bots_discord.py_python.txt |
Q:
Failing: Duplicates issues while looking for a smallest value with .idxmin()
Sample Data:
Fitness Value MSU Locations MSU Range
1.045426 {13, 38, 15} 2.213424
1.096542 {9, 38, 39} 2.226205
1.226040 {1, 22, 30} 1.871269
1.045426 {13, 38, 15} 2.213424
1.096542 {9... | Failing: Duplicates issues while looking for a smallest value with .idxmin() | Sample Data:
Fitness Value MSU Locations MSU Range
1.045426 {13, 38, 15} 2.213424
1.096542 {9, 38, 39} 2.226205
1.226040 {1, 22, 30} 1.871269
1.045426 {13, 38, 15} 2.213424
1.096542 {9, 38, 39} 2.226205
1.143814 {26, 19, 20} 2.223852
1.045426 {1... | [
"Try to use the following code, it handles duplicates.\nWATT = df_min_value_in_each_generation.loc[df_min_value_in_each_generation['Fitness Value'].eq(df['Fitness Value'].min())]\n\nWATT\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"genetic_algorithm",
"genetic_programming",
"pandas",
"python"
] | stackoverflow_0074592409_dataframe_genetic_algorithm_genetic_programming_pandas_python.txt |
Q:
how I can change whitespaces between words of a string in print order?
i was writing a code to input a sentence of user then change its whitespaces to ... and print the sentence.
hi rocks
I intended to input a sentence and change its whitespaces to "..."
I wrote this code:
a=input("inter your sentence: ")
... | how I can change whitespaces between words of a string in print order? | i was writing a code to input a sentence of user then change its whitespaces to ... and print the sentence.
hi rocks
I intended to input a sentence and change its whitespaces to "..."
I wrote this code:
a=input("inter your sentence: ")
#split in to n str
#print every str with ... as whitespace
a=a.split... | [
"str.replace can be used to replace one or multiple characters of same ASCII value to another. In your case, it would be:\na=input(\"inter your sentence: \")\na=a.replace(' ', '...')\nprint(a)\n\n",
"do this.\na=input(\"inter your sentence: \")\n#split in to n str\n#print every str with ... as whitespace\na=a.spl... | [
0,
0,
0
] | [] | [] | [
"printf",
"python",
"string"
] | stackoverflow_0074592503_printf_python_string.txt |
Q:
Execute python script at launch time on Amazon Linux 2
I am trying to execute a python script on an Amazon Linux 2 instance. In my user-data section I have a script which copies the python script from an S3 bucket to the instance and executes it like so:
#!/bin/bash
# e - stops the script if there is an error
# x... | Execute python script at launch time on Amazon Linux 2 | I am trying to execute a python script on an Amazon Linux 2 instance. In my user-data section I have a script which copies the python script from an S3 bucket to the instance and executes it like so:
#!/bin/bash
# e - stops the script if there is an error
# x - output every command in /var/log/syslog
set -e -x
# set ... | [
"You can redirect output to a file and read it to see the error: did you have python3, did your instance have credentianl/role to access this bucket, did you script requires any third party, can you try to run the script above as root in local first, the run command should be python3 /home/ec2-user/my_python_script... | [
1,
0
] | [] | [] | [
"amazon_web_services",
"python"
] | stackoverflow_0065237455_amazon_web_services_python.txt |
Q:
Count issue due to variable not operating properly, subtracting or adding wrong
This is the setup for a calendar, is there a better way to create a count?
for k,v in months.items():
print(k) # print the month name
print(month_header)
while month_daycount > 7:
month_daycount -= 7
count = mon... | Count issue due to variable not operating properly, subtracting or adding wrong | This is the setup for a calendar, is there a better way to create a count?
for k,v in months.items():
print(k) # print the month name
print(month_header)
while month_daycount > 7:
month_daycount -= 7
count = month_daycount
| [
"I'm not sure about your code specifically, but I feel that your code could be greatly simplified by using the datetime library of Python. You could then simply use the delta function to iterate over the days and as you already have the formatting defined, your problem would be solved!\n",
"You are in desperate n... | [
0,
0
] | [] | [] | [
"count",
"modulo",
"python"
] | stackoverflow_0074592406_count_modulo_python.txt |
Q:
Why is df.drop dropping more rows than it should
I have a data frame (other_team_df) of premier league teams and I want to drop rows where the home team is either: Arsenal, Chelsea, Liverpool, Tottenham, Man City or Man United.
When I run the code below, del_row_index has length=1596 and other_team_df has 5321 row... | Why is df.drop dropping more rows than it should | I have a data frame (other_team_df) of premier league teams and I want to drop rows where the home team is either: Arsenal, Chelsea, Liverpool, Tottenham, Man City or Man United.
When I run the code below, del_row_index has length=1596 and other_team_df has 5321 rows. So im expecting 3725 rows to be left after the drop... | [
"Use isin and boolean indexing:\nto_drop = ['Arsenal', 'Chelsea', 'Liverpool', 'Tottenham', 'Man City', 'Man United']\n\nout = other_team_df.loc[~other_team_df['HomeTeam'].isin(to_drop)]\n\n"
] | [
0
] | [] | [] | [
"delete_row",
"drop",
"pandas",
"python",
"row"
] | stackoverflow_0074592646_delete_row_drop_pandas_python_row.txt |
Q:
Laravel's dd() equivalent in django
I am new in Django and having a hard time figuring out how to print what an object have inside. I mean type and value of the variable with its members inside. Just like Laravel's dd(object) function. Laravel's dd() is a handy tool for debugging the application.
I have searched f... | Laravel's dd() equivalent in django | I am new in Django and having a hard time figuring out how to print what an object have inside. I mean type and value of the variable with its members inside. Just like Laravel's dd(object) function. Laravel's dd() is a handy tool for debugging the application.
I have searched for it. But found nothing useful. I have t... | [
"You are looking for __dict__ property or dir()\nprint(object.__dict__)\n\nUse pprint for beautified output\nfrom pprint import pprint\npprint(dir(object))\n\n",
"Raise an exception. Assuming you've got debug on you'll see the exception message. It's crude but it's helped me in the past. \nJust:\n raise Exception... | [
6,
3,
3,
0,
0
] | [] | [] | [
"debugging",
"django",
"flask",
"laravel",
"python"
] | stackoverflow_0050553820_debugging_django_flask_laravel_python.txt |
Q:
How to make only one expected value in Pydantic dataclass
I'm trying to make one or more expected values non-literal. But I get error TypeError: non-default argument 'breakdownAccount' follows default argument.
This example raised error:
@dataclass
class DataInclude:
currencyAccount: Literal["CNY счет", "AMD с... | How to make only one expected value in Pydantic dataclass | I'm trying to make one or more expected values non-literal. But I get error TypeError: non-default argument 'breakdownAccount' follows default argument.
This example raised error:
@dataclass
class DataInclude:
currencyAccount: Literal["CNY счет", "AMD счет", "RUB счет", "USD счет", "EUR счет", "GBP счет", "CHF счет... | [
"Fields without default values cannot appear after fields with default values.\nDeclare the open field as the last one.\nfrom typing import Literal\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass DataInclude:\n currencyAccount: Literal[\n \"CNY счет\",\n \"AMD счет\",\n \"RUB счет\... | [
1
] | [] | [] | [
"automated_tests",
"pydantic",
"python"
] | stackoverflow_0074592440_automated_tests_pydantic_python.txt |
Q:
How to Construct Method and Attributes using Dictionaries in Python
class print_values:
def __init__(self,username,user_email,displayname):
self.name= username
self.email=user_email
self.DisplayName=displayname
def printing_content(self):
print(f"UserName: {self.name}\n"
... | How to Construct Method and Attributes using Dictionaries in Python | class print_values:
def __init__(self,username,user_email,displayname):
self.name= username
self.email=user_email
self.DisplayName=displayname
def printing_content(self):
print(f"UserName: {self.name}\n"
f"UserEmail: {self.email}\n"
f"UserDisplayName:{... | [
"This is because in users_list=['user_one', 'user_two', 'user_three'] you enter the variable name as a string.\nclass print_values:\n def __init__(self,username,user_email,displayname):\n self.name= username\n self.email=user_email\n self.DisplayName=displayname\n def printing_content(sel... | [
1
] | [] | [] | [
"dictionary",
"list",
"loops",
"python",
"python_3.x"
] | stackoverflow_0074592665_dictionary_list_loops_python_python_3.x.txt |
Q:
Python crashes without errors
My python code crashes without providing any exceptions. The code uses Tkinter, socket programming, pyvisa, thread, and modules. It is an automated sensor calibration system using python. The code runs on a Windows 10 machine with python version 2.7.16
It is not crashing at a fixed po... | Python crashes without errors | My python code crashes without providing any exceptions. The code uses Tkinter, socket programming, pyvisa, thread, and modules. It is an automated sensor calibration system using python. The code runs on a Windows 10 machine with python version 2.7.16
It is not crashing at a fixed point. The crash is random. 6/10 time... | [
"maybe you forgot to add tkinter.mainloop() at the end of your code, cause tkinter.mainloop() tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses\n"
] | [
0
] | [
"Have you tried the --debug option when using auto-py-to-exe?\nSee the blog post about tool usage, especially the debug section\nhttps://nitratine.net/blog/post/issues-when-using-auto-py-to-exe/?utm_source=auto_py_to_exe&utm_medium=readme_link&utm_campaign=auto_py_to_exe_help\n"
] | [
-1
] | [
"crash",
"python",
"trace"
] | stackoverflow_0062421601_crash_python_trace.txt |
Q:
How can I convert an object to float?
code
dataframe
I tried making a boxplot for 'horsepower', but it shows up as an object type, so I tried converting it to float but it displays that error.
A:
The column horsepower seems to hold some non numeric values. I suggest you, in this case, to use pandas.to_numeric in... | How can I convert an object to float? | code
dataframe
I tried making a boxplot for 'horsepower', but it shows up as an object type, so I tried converting it to float but it displays that error.
| [
"The column horsepower seems to hold some non numeric values. I suggest you, in this case, to use pandas.to_numeric instead of pandas.Series.astype.\nReplace this :\ndf_T['horsepower']= df_T['horsepower'].astype(float)\n\nBy this :\ndf_T['horsepower']= pd.to_numeric(df_T['horsepower'], errors= 'coerce')\n\n\nIf ‘co... | [
0
] | [] | [] | [
"dataframe",
"object",
"pandas",
"python",
"type_conversion"
] | stackoverflow_0074592693_dataframe_object_pandas_python_type_conversion.txt |
Q:
How to add multiprocessing into my script
I wrote a pentest script? but dont know how to add multiprocessing there, can smb hrlp me?
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
def usage():
print("Eg: \n python3 CVE-2022-1388.py -u https://127.0.0.1")
print(" python3 CVE-2022-1388.py -u httts://... | How to add multiprocessing into my script | I wrote a pentest script? but dont know how to add multiprocessing there, can smb hrlp me?
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
def usage():
print("Eg: \n python3 CVE-2022-1388.py -u https://127.0.0.1")
print(" python3 CVE-2022-1388.py -u httts://127.0.0.1 -c 'cat /etc/passwd'")
print(" ... | [
"It appears that you are doing network requests and writing to a file. For this multithreading should be suitable. You need the following import:\nfrom multiprocessing.dummy import Pool\n\nIf you wish to use multiprocessing instead, then:\nfrom multiprocessing import Pool\n\nIt would appear that the only place wher... | [
0
] | [] | [] | [
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0074564993_multiprocessing_multithreading_python.txt |
Q:
Process files then modify filenames
I am processing files in a directory and after processing a file I want to save it using the original name but also add xx to the file name. My purpose is to identify which files have been processed.
Basic suggestions as to how to proceed are appreciated
A:
If the only purpos... | Process files then modify filenames | I am processing files in a directory and after processing a file I want to save it using the original name but also add xx to the file name. My purpose is to identify which files have been processed.
Basic suggestions as to how to proceed are appreciated
| [
"If the only purpose is flag the file in order to know which files have been processed I would try another strategy (adding file metadata or something). But from your question, I infer the only thing you need is a rename of the file after being processed... You can use os.rename:\nimport os\n\nfilename = \"example.... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074592573_python.txt |
Q:
i was asked to plot a sinus function in Python. Instead of using np.sin we are supposed to import a file called mdt
the code on the file looks like this:
import numpy as np
import math
from scipy.fftpack import fft
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
sd_found = False
try:... | i was asked to plot a sinus function in Python. Instead of using np.sin we are supposed to import a file called mdt | the code on the file looks like this:
import numpy as np
import math
from scipy.fftpack import fft
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
sd_found = False
try:
import sounddevice as sd
sd_found = True
except:
print('Das Modul "sounddevice" fehlt. Es lässt sich per "pi... | [
"I figured it out. I will leave the correct code to this task below if interested check it out.\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport mdt\ndata =read=mdt.dataRead(**{'amplitude': 5,'samplingRate':48000,'duration':0.2,'channels':[0],'resolution':14,'outType':'volt'})\ndata1 = data[0]\nnp.save... | [
0
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074586925_matplotlib_numpy_python.txt |
Q:
How to use the ChEMBL API to download the chembldescriptors?
I have a .csv with Molecule ChEMBL IDs, and I can't find the code to download the chembldescriptors of that set of molecules. Specifically, I want to download: 'TPSA', 'NumHAcceptors', 'NumHDonors', 'CX Acidic pKa', 'CX Basic pKa', 'qed'.
A:
the starti... | How to use the ChEMBL API to download the chembldescriptors? | I have a .csv with Molecule ChEMBL IDs, and I can't find the code to download the chembldescriptors of that set of molecules. Specifically, I want to download: 'TPSA', 'NumHAcceptors', 'NumHDonors', 'CX Acidic pKa', 'CX Basic pKa', 'qed'.
| [
"the starting point is not a .csv, but I can get all the information through the API (for python)\nfrom chembl_webresource_client.new_client import new_client\nimport pandas as pd\n#activity API:\nactivities = new_client.activity.filter(target_chembl_id__in = ['CHEMBL1824'] #erbB-2\n ... | [
0
] | [] | [] | [
"api",
"cheminformatics",
"python"
] | stackoverflow_0074562889_api_cheminformatics_python.txt |
Q:
Cannot assign int in Dask array
I'm having trouble doing a simple operation: assigning a value to a dask array. I get the error:
"Item assignment with <class 'int'> not supported"
Does anybody know why ?
This should normally be doable according to the dask documentation...
Here's the (elementary) "chunk" of code t... | Cannot assign int in Dask array | I'm having trouble doing a simple operation: assigning a value to a dask array. I get the error:
"Item assignment with <class 'int'> not supported"
Does anybody know why ?
This should normally be doable according to the dask documentation...
Here's the (elementary) "chunk" of code that I'm having trouble with. Problem ... | [
"Works for me - so this is probably an issue with the version of Dask that you are using.\n$ python\nPython 3.10.8 (main, Nov 24 2022, 14:13:03) [GCC 11.2.0] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import dask\n>>> import dask.array as da\n>>> x = da.zeros(10)\n... | [
0
] | [] | [] | [
"arrays",
"assign",
"dask",
"python"
] | stackoverflow_0074592681_arrays_assign_dask_python.txt |
Q:
INPUT FORMAT COMPLIANCE: a date prompt with 3 mutable input fields separated by 2 static forward slashes, with set ranges for each feild
I am trying to create a prompt that is either separated by hard slashes or slashes appear after specified input range, all on a single line.
i want:
Enter your age (M/D/Y): int /... | INPUT FORMAT COMPLIANCE: a date prompt with 3 mutable input fields separated by 2 static forward slashes, with set ranges for each feild | I am trying to create a prompt that is either separated by hard slashes or slashes appear after specified input range, all on a single line.
i want:
Enter your age (M/D/Y): int / int / int #where the slashes are fixed and part of the prompt
not: M:
D:
Y:
example:
Enter the date M/D/Y: '12'**/**'12'**/**'1234... | [
"#A solution was provided elsewhere, posting with Author's permission.\n\n\"\"\"PINPUT, AN INPUT FORMAT COMPLIANCE MODULE FOR DATE/TIME ENTRY\"\"\"\n\" AUTHOR: INDRAJIT MAJUMDAR \"\n\n import sys\n \ntry:\n #for windows platform.\n from msvcrt import getwch as getch\ne... | [
0
] | [] | [] | [
"datetime",
"input",
"python"
] | stackoverflow_0074506956_datetime_input_python.txt |
Q:
Does the results indicate that the list(position) is not updated or there is something wrong with the equation?
I am writing a code to update a position of a ball after it being kicked at a given angle and velocity after a certain time passed. Does the results indicate that the list(position) is not updated or the... | Does the results indicate that the list(position) is not updated or there is something wrong with the equation? | I am writing a code to update a position of a ball after it being kicked at a given angle and velocity after a certain time passed. Does the results indicate that the list(position) is not updated or there is something wrong with the equation?
import numpy as np
class Ball():
def __init__(self, theta, v):
... | [
"There were a few bugs in your code, I've altered it to do what I believe you intend it to do below:\nimport numpy as np\n\nclass Ball():\n def __init__(self, theta, v):\n self.position = [0, 0] # Position at ground is (0,0)\n self.theta = theta\n self.v = v\n \n def step(self, del... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074592731_python.txt |
Q:
Tkinter python not terminating the program
import tkinter
global win1,win2, win3
def win1_open():
global win1
win1 = tkinter.Tk()
win1.geometry('500x500')
button_next = tkinter.Button(win1, text='Next', width=8, command=win2_open)
button_next.place(x=100 * 2 + 80, y = 100)
win1.mainloop()... | Tkinter python not terminating the program | import tkinter
global win1,win2, win3
def win1_open():
global win1
win1 = tkinter.Tk()
win1.geometry('500x500')
button_next = tkinter.Button(win1, text='Next', width=8, command=win2_open)
button_next.place(x=100 * 2 + 80, y = 100)
win1.mainloop()
def win2_open():
global win2
win2 = tk... | [
"Instead of using quit(), you should use destory()\ndef exit_program():\n global win1, win2, win3\n win1.destroy()\n win2.destroy()\n win3.destroy()\n\nTo learn more about the difference between these 2 function, you can refer to this:\nHow do I close a tkinter Window?\n",
"Change the calls in exit_pr... | [
1,
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074588453_python_tkinter_user_interface.txt |
Q:
Deque to keep last few minutes in Python
I'd like to keep the last 10 minutes of a time series in memory with some sort of deque system in Python.
Right now I'm using deque but I may receive 100 data points in few seconds and then nothing for few seconds.
Any idea ?
I read something about FastRBTree in a post but ... | Deque to keep last few minutes in Python | I'd like to keep the last 10 minutes of a time series in memory with some sort of deque system in Python.
Right now I'm using deque but I may receive 100 data points in few seconds and then nothing for few seconds.
Any idea ?
I read something about FastRBTree in a post but it dated back to 2014. Is there any better sol... | [
"If you are concerned about container size, \"simplest\" thing might be to use the deque and just set a maxlen argument and then as it overflows, the oldest adds are just lost, but that does not guarantee 10 minutes worth obviously. But it is an efficient data structure for this.\nIf you want to \"trim by time in ... | [
0
] | [] | [] | [
"deque",
"python",
"python_3.x"
] | stackoverflow_0074585486_deque_python_python_3.x.txt |
Q:
How to insert every nth charts in string? PYTHON
I have a code, but I don't really know python, so I have a problem. I know that the insert isn't right for strings but I don't know how can I insert?
original_string = input("What's yout sentence?")
add_character = input("What char do you want to add?")
slice = int(... | How to insert every nth charts in string? PYTHON | I have a code, but I don't really know python, so I have a problem. I know that the insert isn't right for strings but I don't know how can I insert?
original_string = input("What's yout sentence?")
add_character = input("What char do you want to add?")
slice = int(input("What's the step?"))
for i in original_string[:... | [
"Also I try to use .join, but now it prints original string, how can I print the string with joined chars?\n original_string = input(\"What's yout sentence?\")\n add_character = input(\"What char do you want to add?\")\n slice = int(input(\"What's the step?\"))\n \n for i in original_string[::slice]:... | [
0,
0
] | [] | [] | [
"insert",
"python",
"string"
] | stackoverflow_0074592740_insert_python_string.txt |
Q:
using django, i want to show the user options to pick from with 'select' and a TextChoices model
in my html template i have a select box where the user chooses the desired size of clothing like this
<select>
<option> Small </option>
<option> Medium </option>
<option> Large </option>
</select>
i want t... | using django, i want to show the user options to pick from with 'select' and a TextChoices model | in my html template i have a select box where the user chooses the desired size of clothing like this
<select>
<option> Small </option>
<option> Medium </option>
<option> Large </option>
</select>
i want to display the options for the user to see.
because i want to save the input in the database, to grab i... | [
"So... i found a way to do it...\nusing django forms\nfrom django import forms\nfrom .models import Product\n\nclass ClothingForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = ['size']\n\nviews.py\nfrom .forms import ClothingForm\n\ndef product(request, slug):\n product = get_obje... | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python",
"user_interface"
] | stackoverflow_0074587095_django_django_models_django_views_python_user_interface.txt |
Q:
Tkinter Button behaviour after matplotlib plt.show()
I am writing a python tkinter-based GUI that should show Matplotlib-Plots in new Windows whenever I hit a button. Plots shall be non-exclusive, I want to be able to bring up as many Plots as I would like. (Original App has more than one button, I shortened it be... | Tkinter Button behaviour after matplotlib plt.show() | I am writing a python tkinter-based GUI that should show Matplotlib-Plots in new Windows whenever I hit a button. Plots shall be non-exclusive, I want to be able to bring up as many Plots as I would like. (Original App has more than one button, I shortened it below)
The Problem is: When I click one of my buttons the pl... | [
"An example with many windows without plt.show(). Sample taken from here.\nimport tkinter as tk\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\ni = 0\nnew_windows = []\n\ndata1 = {'country': ['A', 'B', 'C', 'D', 'E'],\n 'gdp_per_capit... | [
1
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0074590539_matplotlib_python_tkinter.txt |
Q:
Web-Scraping using "requests" does not scrape the names/leaves out important information
I tried following this approach to webscraping names of this specific website containing names I am interested in.:
import requests
URL = "https://bair.berkeley.edu/students.html"
page = requests.get(URL)
print(page.text)
W... | Web-Scraping using "requests" does not scrape the names/leaves out important information | I tried following this approach to webscraping names of this specific website containing names I am interested in.:
import requests
URL = "https://bair.berkeley.edu/students.html"
page = requests.get(URL)
print(page.text)
When executing, I however only get:
The first of the people listed on that website in my pri... | [
"As the name list of the webpage is populated by JavaScript, So you can use selenium with bs4.\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nimport time\n\nwebdriver_service = Service(\"./chromedriver\") #Your chromedriver... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074588610_beautifulsoup_html_python_python_requests_web_scraping.txt |
Q:
Incorrectly Reading a Column Containing Lists in Pandas
I have a pandas data frame containing a column with a list that I am reading from a CSV. For example, the column in the CSV appears like so:
ColName2007
=============
['org1', 'org2']
['org2', 'org3']
...
So, when I read this column into Pandas, each entry o... | Incorrectly Reading a Column Containing Lists in Pandas | I have a pandas data frame containing a column with a list that I am reading from a CSV. For example, the column in the CSV appears like so:
ColName2007
=============
['org1', 'org2']
['org2', 'org3']
...
So, when I read this column into Pandas, each entry of the columns is treated as a string, rather than a list of s... | [
"I would use a strip/split :\ndf['ColName2007']= df['ColName2007'].str.strip(\"[]\").str.split(\",\")\n\nOtherwise, you can apply an ast.literal_eval as suggested by @Bjay Regmi in the comments.\nimport ast\n\ndf[\"ColName2007\"] = df[\"ColName2007\"].apply(ast.literal_eval)\n\n"
] | [
1
] | [] | [] | [
"list",
"pandas",
"python",
"python_3.x",
"string"
] | stackoverflow_0074592771_list_pandas_python_python_3.x_string.txt |
Q:
How to sort multiple columns' values from min to max, and put in new columns in pandas dataframe?
I have a dataframe with datetime objects in columns 'start' . I want to sort these dates into new columns : evry time ID start to a new location with order
df = pd.DataFrame(data={'ID':['a1','a2','a1','a1','a2','a2'],... | How to sort multiple columns' values from min to max, and put in new columns in pandas dataframe? | I have a dataframe with datetime objects in columns 'start' . I want to sort these dates into new columns : evry time ID start to a new location with order
df = pd.DataFrame(data={'ID':['a1','a2','a1','a1','a2','a2'],
'location':['bali','mosta','road','joha','alabama','vinice'],
... | [
"Try:\ndf[\"tmp\"] = df.groupby(\"ID\").cumcount() + 1\ndf = df.pivot(index=\"ID\", columns=\"tmp\")\ndf.columns = [f\"{t}_{n}\" for t, n in df.columns]\ndf = df[sorted(df, key=lambda k: ((int((i := k.split(\"_\"))[1])), i[0]))]\nprint(df.reset_index())\n\nPrints:\n ID location_1 start_1 location_2 ... | [
0
] | [] | [] | [
"group_by",
"numpy",
"python",
"sorteddictionary",
"sorting"
] | stackoverflow_0074592822_group_by_numpy_python_sorteddictionary_sorting.txt |
Q:
Using One-Hot Encoding vector as a feature for machine learning models
I have a categorical column ('session', than can get one of these values: [2,4,8]), that I want to use while training a machine learning model (like RandomForest or MLP).
In order to do that, I encoded this feature using the One-Hot Encode meth... | Using One-Hot Encoding vector as a feature for machine learning models | I have a categorical column ('session', than can get one of these values: [2,4,8]), that I want to use while training a machine learning model (like RandomForest or MLP).
In order to do that, I encoded this feature using the One-Hot Encode method:
df= pd.get_dummies(df, columns=["session"], prefix="Sessions")
and I go... | [
"Your data frame already contains the one-hot encoding of the categorical feature, which literally is the combination of three existing columns, Session_2,4,8. No need of including that session column (object-type) as it is redundant and invalid.\n"
] | [
2
] | [] | [] | [
"machine_learning",
"one_hot_encoding",
"python"
] | stackoverflow_0074592788_machine_learning_one_hot_encoding_python.txt |
Q:
Python: If input == variable is correct but result is incorrect
I'm now currently learning Python because of school projects and I'm trying to make an element guessing game based on the info given. Sorry if my English is bad cause I'm not native English speaker. Also first time using this platform lol.
This is the... | Python: If input == variable is correct but result is incorrect | I'm now currently learning Python because of school projects and I'm trying to make an element guessing game based on the info given. Sorry if my English is bad cause I'm not native English speaker. Also first time using this platform lol.
This is the code
import random
#Element and description
astatine = "Rarest natu... | [
"You have several misunderstandings here. You can't use the name of a variable as a string. What you need is a dictionary, where both key and value are strings. Next, you were using ...).lower, but without the parentheses, so the result was the lower function object, not the result of calling the function.\nThis... | [
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074592947_if_statement_python.txt |
Q:
flask template rendering weird
Looking at this, it should work right?
It seems like the get request is overwriting the post request return because it only renders no error.
Why is that?
index.html
{% if error %}
<p>{{ error }}</p>
{% else %}
<p>no error</p>
{% endif %}
main.py
@app.route('/', methods=['G... | flask template rendering weird | Looking at this, it should work right?
It seems like the get request is overwriting the post request return because it only renders no error.
Why is that?
index.html
{% if error %}
<p>{{ error }}</p>
{% else %}
<p>no error</p>
{% endif %}
main.py
@app.route('/', methods=['GET', 'POST'])
def index():
if re... | [
"Look closely at post_data['message']. Are you absolutely sure it's False? If it's the string 'False', the code falls through and won't render an error.\n",
"Try using else or elif.\nelse:\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n post_data = request.get_js... | [
0,
0
] | [] | [] | [
"flask",
"post",
"python"
] | stackoverflow_0074587480_flask_post_python.txt |
Q:
Need help to create signature in python
I have sample code from golang,
here is some sample values to run the code:
app_secret = 777, path = /api/orders, app_key = 12345, timestamp = 1623812664
or you guys can refer this link to get more info https://developers.tiktok-shops.com/documents/document/234136#3.Signatur... | Need help to create signature in python | I have sample code from golang,
here is some sample values to run the code:
app_secret = 777, path = /api/orders, app_key = 12345, timestamp = 1623812664
or you guys can refer this link to get more info https://developers.tiktok-shops.com/documents/document/234136#3.Signature%20Algorithm
import (
"crypto/hmac"
... | [
"Found the issue, i was trying to digest with out digestmod\nWorking Example:\n sign = hmac.new(\n app_secret.encode(),\n sign_string.encode(),\n digestmod = hashlib.sha256\n ).hexdigest()\n\n"
] | [
0
] | [] | [] | [
"hash",
"python",
"python_3.x",
"sign"
] | stackoverflow_0074592357_hash_python_python_3.x_sign.txt |
Q:
how to UPDATE SQL database dynamically using python?
import mysql.connector
db = mysql.connector.connect(host="localhost", user="1234", passwd="1234", database="books1")
mycursor = db.cursor()
label = '202'
position = 'A1'
sql2 = """INSERT INTO info (label, position) VALUES (%s, %s)"""
db2 = (label, position... | how to UPDATE SQL database dynamically using python? | import mysql.connector
db = mysql.connector.connect(host="localhost", user="1234", passwd="1234", database="books1")
mycursor = db.cursor()
label = '202'
position = 'A1'
sql2 = """INSERT INTO info (label, position) VALUES (%s, %s)"""
db2 = (label, position)
mycursor.execute(sql2, db2)
print("Updated")
When I r... | [
"You have to commit the transaction.\nAdd db.commit() after mycursor.execute()\n"
] | [
2
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0074592976_python_sql.txt |
Q:
how to get captcha numbers separately using python
I have this specific 3-digit of captcha, like:
I am trying to slice the 3 digits, I tried to use pytesseract module to recognize text
in images but it's not so accurate. so I researched about it and fount out that I could make the background completely white so t... | how to get captcha numbers separately using python | I have this specific 3-digit of captcha, like:
I am trying to slice the 3 digits, I tried to use pytesseract module to recognize text
in images but it's not so accurate. so I researched about it and fount out that I could make the background completely white so that I could crop all the extra space from the picture an... | [
"so I have found this library called cv2 with this method called threshold\nFor every pixel, the same threshold value is applied. If the pixel value is smaller than the threshold, it is set to 0, otherwise it is set to a maximum value.\nimg = cv.imread('gradient.png',0)\nret,thresh1 = cv.threshold(img,127,255,cv.TH... | [
0
] | [] | [] | [
"captcha",
"python",
"text_recognition"
] | stackoverflow_0074592679_captcha_python_text_recognition.txt |
Q:
How to take out the quotation marks(start & end) and convert into bytes - Python 3.7.9
I'm receiving from an input this,
"b'-----BEGIN RSA PUBLIC KEY-----\\nMBgCEQCZ0e8OKi/eLXMXxPrhdFc3AgMBAAE=\\n-----END RSA PUBLIC KEY-----\\n'"
and i'm struggling to make it become a bytes, and not string, and be able to load th... | How to take out the quotation marks(start & end) and convert into bytes - Python 3.7.9 | I'm receiving from an input this,
"b'-----BEGIN RSA PUBLIC KEY-----\\nMBgCEQCZ0e8OKi/eLXMXxPrhdFc3AgMBAAE=\\n-----END RSA PUBLIC KEY-----\\n'"
and i'm struggling to make it become a bytes, and not string, and be able to load the keys without problems - ValueError: No PEM start marker "b'-----BEGIN RSA PUBLIC KEY-----'... | [
"Python 3.9+ : You have .removesuffix() and .removeprefix() options.\nIn lower versions, You can simply slice the string from character two, until before the last one.\nThen you can use .encode() to convert your string to byte:\nold_string = \"b'-----BEGIN RSA PUBLIC KEY-----\\\\nMBgCEQCZ0e8OKi/eLXMXxPrhdFc3AgMBAAE... | [
1
] | [] | [] | [
"python",
"python_3.7"
] | stackoverflow_0074593012_python_python_3.7.txt |
Q:
I am trying to implement binary search but i dont know whats wrong with my code?
This is binary search algorithm that is showing output as None. I dont know why. And if you know any free course to learn data sctrucures and algorithm in python please let me know .
import random
def binary_search(list,target):
st... | I am trying to implement binary search but i dont know whats wrong with my code? | This is binary search algorithm that is showing output as None. I dont know why. And if you know any free course to learn data sctrucures and algorithm in python please let me know .
import random
def binary_search(list,target):
start_index=0
end_index=len(list)-1
while start_index<=end_index:
midpoint=(star... | [
"You're using < wrong. It should be >\ndef binary_search(list, target):\n start_index = 0\n end_index = len(list)-1\n while start_index <= end_index:\n midpoint = (start_index+end_index)//2\n midpoint_value = list[midpoint]\n if midpoint_value == target:\n return midpoint+1\... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074592392_python.txt |
Q:
How to choose one smallest values among multiple duplicates values in a data frame?
Sample Data:
Fitness Value MSU Locations MSU Range
13 1.045426 {13, 38, 15} 2.213424
13 1.045426 {13, 38, 15} 2.213424
13 1.045426 {13, 38, 15} 2.213424
Sample Code 1
WA... | How to choose one smallest values among multiple duplicates values in a data frame? | Sample Data:
Fitness Value MSU Locations MSU Range
13 1.045426 {13, 38, 15} 2.213424
13 1.045426 {13, 38, 15} 2.213424
13 1.045426 {13, 38, 15} 2.213424
Sample Code 1
WATT1 = WATTx.loc[WATTx['Fitness Value'].eq(df['Fitness Value'].min())]
WATT1
Sample Code ... | [
"I suppose that your dataframe WATTx has a non unique index values.\nTry to reset_index before using boolean indexing with idxmin :\nWATTy= WATTx.reset_index().loc[WATTx['Fitness Value'].idxmin()]\n\n# Output :\nprint(WATTy)\n\nidx 1\nFitness Value 1.045426\nMSU Locations {13,38,15}\nM... | [
1
] | [] | [] | [
"dataframe",
"genetic_algorithm",
"genetic_programming",
"pandas",
"python"
] | stackoverflow_0074592779_dataframe_genetic_algorithm_genetic_programming_pandas_python.txt |
Q:
How to convert prices in one dataframe with exchange rates in another one?
I have a dataframe of amount bought like this:
import pandas as pd
amounts = pd.DataFrame({
'symbol': ['EUR/USD', 'EUR/USD', 'GBP/USD', 'GBP/USD', 'EUR/GBP', 'EUR/GBP'],
'time': [1, 2, 1, 2, 1, 2],
'amount': [1, 1, 2, 2, 3, 3]
... | How to convert prices in one dataframe with exchange rates in another one? | I have a dataframe of amount bought like this:
import pandas as pd
amounts = pd.DataFrame({
'symbol': ['EUR/USD', 'EUR/USD', 'GBP/USD', 'GBP/USD', 'EUR/GBP', 'EUR/GBP'],
'time': [1, 2, 1, 2, 1, 2],
'amount': [1, 1, 2, 2, 3, 3]
})
amounts.set_index('symbol', inplace=True)
prices = pd.DataFrame({
's... | [
"Here is one way to do it with Pandas merge method:\n# Setup\namounts = amounts.set_index(\"symbol\")\n\n# Convert all prices in EUR\nprices[\"price_eur\"] = prices[\"price\"]\nprices.loc[prices[\"symbol\"] == \"GBP/USD\", \"price_eur\"] = (\n prices.loc[prices[\"symbol\"] == \"EUR/USD\", \"price\"].values[0]\n ... | [
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074538466_pandas_python_python_3.x.txt |
Q:
Python - Combine text data from group of file by filename
I have below list of text files , I wanted to combine group of files like below
Inv030001.txt - should have all data of files starting with Inv030001
Inv030002.txt - should have all data of files starting with Inv030002
I tried below code but it's not work... | Python - Combine text data from group of file by filename | I have below list of text files , I wanted to combine group of files like below
Inv030001.txt - should have all data of files starting with Inv030001
Inv030002.txt - should have all data of files starting with Inv030002
I tried below code but it's not working
filenames = glob(textfile_dir+'*.txt')
for fname in filenam... | [
"Does this answer your question? My version will append the data from \"like\" invoice numbers to a .txt file named with just the invoice number. In other words, anything that starts with \"Inv030001\" will have it's contents appended to \"Inv030001.txt\". The idea being that you likely don't want to overwrite file... | [
1,
0,
0
] | [] | [] | [
"python",
"text_files"
] | stackoverflow_0074592543_python_text_files.txt |
Q:
Spacy, Strange similarity between two sentences
I have downloaded en_core_web_lg model and trying to find similarity between two sentences:
nlp = spacy.load('en_core_web_lg')
search_doc = nlp("This was very strange argument between american and british person")
main_doc = nlp("He was from Japan, but a true Engli... | Spacy, Strange similarity between two sentences | I have downloaded en_core_web_lg model and trying to find similarity between two sentences:
nlp = spacy.load('en_core_web_lg')
search_doc = nlp("This was very strange argument between american and british person")
main_doc = nlp("He was from Japan, but a true English gentleman in my eyes, and another one of the reaso... | [
"Spacy constructs sentence embedding by averaging the word embeddings. Since, in an ordinary sentence, there are a lot of meaningless words (called stop words), you get poor results. You can remove them like this: \nsearch_doc = nlp(\"This was very strange argument between american and british person\")\nmain_doc =... | [
31,
15,
10,
5,
3
] | [] | [] | [
"nlp",
"python",
"spacy"
] | stackoverflow_0052113939_nlp_python_spacy.txt |
Q:
fixture 'page' not found - pytest playwright
I started learning playwright and from documentation (https://playwright.dev/python/docs/intro) tried to to run the following sample code:
import re
from playwright.sync_api import Page, expect
def test_pp(page: Page):
page.goto("https://playwright.dev/")
# E... | fixture 'page' not found - pytest playwright | I started learning playwright and from documentation (https://playwright.dev/python/docs/intro) tried to to run the following sample code:
import re
from playwright.sync_api import Page, expect
def test_pp(page: Page):
page.goto("https://playwright.dev/")
# Expect a title "to contain" a substring.
expec... | [
"Try the following:\n\npy.test test_.py\n\n"
] | [
1
] | [] | [] | [
"playwright",
"playwright_python",
"pytest",
"python"
] | stackoverflow_0074135518_playwright_playwright_python_pytest_python.txt |
Q:
Parse and Query Large XML File Using Python
I am working on a project for which I have to parse and query a relatively large xml file in python. I am using a dataset with data about scientific articles. The dataset can be found via this link (https://dblp.uni-trier.de/xml/dblp.xml.gz). There are 7 types of entries... | Parse and Query Large XML File Using Python | I am working on a project for which I have to parse and query a relatively large xml file in python. I am using a dataset with data about scientific articles. The dataset can be found via this link (https://dblp.uni-trier.de/xml/dblp.xml.gz). There are 7 types of entries in the dataset: article, inproceedings, proceedi... | [
"If the file is large, and you want to perform multiple queries, then you don't want to be parsing the file and building a tree in memory every time you do a query. You also don't want to be writing the queries in low-level Python, you need a proper query language.\nYou should be loading the data into an XML databa... | [
0,
0
] | [] | [] | [
"data_mining",
"python",
"xml"
] | stackoverflow_0074467660_data_mining_python_xml.txt |
Q:
Convert multiple multipage PDFs to JPGs in subfolders
Simple use case:
A folder with many (mostly multipage) PDF files.
A script should convert each PDF page to JPG and store it in a subfolder named after the PDF filename. (e.g. #33.pdf to folder #33)
Single JPG files should also have this filename plus a counter... | Convert multiple multipage PDFs to JPGs in subfolders | Simple use case:
A folder with many (mostly multipage) PDF files.
A script should convert each PDF page to JPG and store it in a subfolder named after the PDF filename. (e.g. #33.pdf to folder #33)
Single JPG files should also have this filename plus a counter mirroring the sequential page number in the PDF. (e.g. #33... | [
"Your comment requests how a batch can do as required, for simplicity the following only processes a single file so Python will need to loop through a folder and call with each name in turn. That could be done by adding a \"for loop\" in batch but first see where problems arise, as many of my single test files thre... | [
0
] | [] | [] | [
"batch_processing",
"image",
"imagemagick",
"pdf",
"python"
] | stackoverflow_0074546533_batch_processing_image_imagemagick_pdf_python.txt |
Q:
VSCode Kernel Selector when clicked does not display any options
Despite having multiple interpreters available (3.10.8, 3.9.13 from anaconda), whenever I click "Select Kernel" in my ipynb notebook, nothing comes up except for "Install suggested extensions Python + Jupyter," none of which are helpful since I alrea... | VSCode Kernel Selector when clicked does not display any options | Despite having multiple interpreters available (3.10.8, 3.9.13 from anaconda), whenever I click "Select Kernel" in my ipynb notebook, nothing comes up except for "Install suggested extensions Python + Jupyter," none of which are helpful since I already have the suggested extensions installed. Does anyone know how I can... | [
"I uninstalled, then reinstalled VSCode. base (Python 3.9.13) was instantly selected for me upon opening the reinstalled version of VSC.\n"
] | [
0
] | [] | [] | [
"anaconda",
"jupyter_notebook",
"kernel",
"python",
"visual_studio_code"
] | stackoverflow_0074592584_anaconda_jupyter_notebook_kernel_python_visual_studio_code.txt |
Q:
How to find an element under located header using python selenium
With selenium in python, I want to collect data about a user called "Graham" on the website below: https://github.com/GrahamDumpleton/wrapt/graphs/contributors
Following the previous question, I located the header including the name "Graham" by find... | How to find an element under located header using python selenium | With selenium in python, I want to collect data about a user called "Graham" on the website below: https://github.com/GrahamDumpleton/wrapt/graphs/contributors
Following the previous question, I located the header including the name "Graham" by finding XPath:
driver.find_elements(By.XPATH, "//h3[contains(@class,'border... | [
"The element you looking for can be uniquely located by the following XPath: //a[contains(.,'commit')].\nSo, if you want to locate directly all the commit amounts of users on the page this can be done as following:\ncommits = driver.find_elements(By.XPATH, \"//a[contains(.,'commit')]\")\nfor commit in commits:\n ... | [
1,
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping",
"xpath"
] | stackoverflow_0074593047_python_selenium_selenium_webdriver_web_scraping_xpath.txt |
Q:
How to gather all chats a Telegram bot is an admin of?
How is it possible to get all chats in the form of a iterabale object (list-like) or iterate over all possible chats the bot is an admin/participant of (using python-telegram-bot)? Is there a python-telegram-bot method for getting all chats a bot is a admin/pa... | How to gather all chats a Telegram bot is an admin of? | How is it possible to get all chats in the form of a iterabale object (list-like) or iterate over all possible chats the bot is an admin/participant of (using python-telegram-bot)? Is there a python-telegram-bot method for getting all chats a bot is a admin/participant of?
| [
"No, there is not, because the Telegram Bot API does not provide such a method. You can use the Update.my_chat_member updates to keep track of that. See here for an example on how that can be done using python-telgeram-bot.\n\nDisclaimer: I'm currently the maintainer of python-telegram-bot.\n"
] | [
1
] | [] | [] | [
"iterable",
"python",
"python_3.x",
"python_telegram_bot",
"telegram_bot"
] | stackoverflow_0074591204_iterable_python_python_3.x_python_telegram_bot_telegram_bot.txt |
Q:
Two functions, One generator
I have two functions which both take iterators as inputs. Is there a way to write a generator which I can supply to both functions as input, which would not require a reset or a second pass through? I want to do one pass over the data, but supply the output to two functions: Example:... | Two functions, One generator | I have two functions which both take iterators as inputs. Is there a way to write a generator which I can supply to both functions as input, which would not require a reset or a second pass through? I want to do one pass over the data, but supply the output to two functions: Example:
def my_generator(data):
for r... | [
"Python has an amazing catalog of handy functions. You find the ones related to iterators in itertools:\nimport itertools\n\ndef my_generator(data):\n for row in data:\n yield row\n\ngen = my_generator(data)\ngen1, gen2 = itertools.tee(gen)\nfunc1(gen1)\nfunc2(gen2)\n\nHowever, this only makes sense if fu... | [
3,
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0035395429_python.txt |
Q:
what chages to make to get the question from dictionary
what changes to make to get the question form dictionary and then get the answer at the same time and check weather it is right or wrong
from random import *
print("""Welcom to the quiz game
would you like to play? """)
consent = input("-----> ")
consent = ... | what chages to make to get the question from dictionary | what changes to make to get the question form dictionary and then get the answer at the same time and check weather it is right or wrong
from random import *
print("""Welcom to the quiz game
would you like to play? """)
consent = input("-----> ")
consent = consent.lower()
if consent == "no":
print("The game ends"... | [
"Make a dictionary where the key is a question and the value is the answer:\nquiz = {\n 'This is a true question': 'true',\n 'This is a false question': 'false',\n # and so on\n}\n\nThen choose a random question from the dictionary like this:\nquestion = choice(list(quiz))\nprint(question)\n\nAnd the corre... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074593096_python.txt |
Q:
line collision detector with circles
not long ago I am in python and I decided to make a path planning program, the truth cost me a lot since I am a beginner, but good to the point, is to generate circles of random size and position that do not collide with each other and then generate lines that do not collide wi... | line collision detector with circles | not long ago I am in python and I decided to make a path planning program, the truth cost me a lot since I am a beginner, but good to the point, is to generate circles of random size and position that do not collide with each other and then generate lines that do not collide with the circles, with much help and I manag... | [
"Your algorithm that detects the intersection of a line and a circle is wrong.A correct algorithm can be found all over the web. e.g. Circle-Line Intersection. A function that implements such an algorithm and finds the intersection points of a line and a circle could look like the following:\ndef sign(x):\n retu... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074592905_pygame_python.txt |
Q:
How can I use different pipelines for different spiders in a single Scrapy project
I have a scrapy project which contains multiple spiders.
Is there any way I can define which pipelines to use for which spider? Not all the pipelines i have defined are applicable for every spider.
Thanks
A:
Just remove all pipeli... | How can I use different pipelines for different spiders in a single Scrapy project | I have a scrapy project which contains multiple spiders.
Is there any way I can define which pipelines to use for which spider? Not all the pipelines i have defined are applicable for every spider.
Thanks
| [
"Just remove all pipelines from main settings and use this inside spider.\nThis will define the pipeline to user per spider\nclass testSpider(InitSpider):\n name = 'test'\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'app.MyPipeline': 400\n }\n }\n\n",
"Building on the solution f... | [
169,
39,
17,
15,
12,
10,
6,
1,
1,
0,
0
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0008372703_python_scrapy_web_crawler.txt |
Q:
unexpected "None" in list
i wanted to make a game where you guess the letter. and add a function that will show you all you incorrect guesses, so i made the list:
incorrectguesses = []
and then i made it so it asks the user to guess the letter:
while True:
guess = input("what do you think the letter is?? ")... | unexpected "None" in list | i wanted to make a game where you guess the letter. and add a function that will show you all you incorrect guesses, so i made the list:
incorrectguesses = []
and then i made it so it asks the user to guess the letter:
while True:
guess = input("what do you think the letter is?? ")
if guess == secret_letter:... | [
"print(print_all_items(incorrectguesses))\n\nYou're printing the result of the print_all_items() function.\nHowever, that function has no return statement, so it returns None by default.\nSo, the result of the function is None, and that gets printed.\nSince the function itself prints the results, I think you actual... | [
3,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074593024_python_python_3.x.txt |
Q:
Producing probability of wins in Python craps game
I have the logic down for this game of craps. My only problem right now is that I can't seem to get any output for finding the probability of wins for the game. Here is the code:
from random import seed, randint
def simulate():
die1 = randint(1, 6)
die2 = ran... | Producing probability of wins in Python craps game | I have the logic down for this game of craps. My only problem right now is that I can't seem to get any output for finding the probability of wins for the game. Here is the code:
from random import seed, randint
def simulate():
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
first_roll = roll
... | [
"I am sorry for my latest answer, I didn't read that its craps game.\nfrom random import seed, randint\n\ndef simulate():\n die1 = randint(1, 6)\n die2 = randint(1, 6)\n roll = die1 + die2\n\n first_roll = roll\n\n if first_roll == 7 or first_roll == 11:\n return True\n elif first_roll == 2... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074592980_python.txt |
Q:
How would I put a API's output into different variables in Python?
So I am using a riddle API and whenever it is ran it outputs it data like this:
[
{
"title": "The Magic House",
"question": "There is a house,if it rains ,there is water in it and if it doesn't rain,there is water in it.what kind of hou... | How would I put a API's output into different variables in Python? | So I am using a riddle API and whenever it is ran it outputs it data like this:
[
{
"title": "The Magic House",
"question": "There is a house,if it rains ,there is water in it and if it doesn't rain,there is water in it.what kind of house is that?",
"answer": "bathroom"
}
]
How could I convert the ... | [
"The response you received from the server looks like JSON so use json module to parse it. When you parse the response, you access the items like normal python list/dict:\nimport json\n\nresponse_text = \"\"\"[\n {\n \"title\": \"The Magic House\",\n \"question\": \"There is a house,if it rains ,there is wat... | [
1
] | [] | [] | [
"api",
"python",
"python_3.9",
"python_requests"
] | stackoverflow_0074592338_api_python_python_3.9_python_requests.txt |
Q:
Selenium clicking a specific button object from a list of objects with python
I am grabbing a list of buttons, then I am attempting to click a specific button object, I collect all buttons (which contain details such as a name). I check the name, if I have already clicked on this button, pass, or else click this b... | Selenium clicking a specific button object from a list of objects with python | I am grabbing a list of buttons, then I am attempting to click a specific button object, I collect all buttons (which contain details such as a name). I check the name, if I have already clicked on this button, pass, or else click this button object.
The problem I am having is that the button doesn't have an ID so I am... | [
"I solved this by identifying a unique variable in each button, in this instance an IMG URL then dynamically located each with selenium.\nimg_src = button_soup.find('img')['src']\npath_location = \"//img[contains(@src,'{}')]\".format(img_src)\nbrowser.find_element(By.XPATH, path_location).click()\n\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium"
] | stackoverflow_0074586418_beautifulsoup_python_selenium.txt |
Q:
Using custom yolov7 trained model on my screen
What I know
I have already trained a custom model using yolov7-tiny
I am now trying to use it for object detection on screen
The script I have:
import mss
import numpy as np
import cv2
import time
import keyboard
import torch
from hubconf import custom
model = custom... | Using custom yolov7 trained model on my screen | What I know
I have already trained a custom model using yolov7-tiny
I am now trying to use it for object detection on screen
The script I have:
import mss
import numpy as np
import cv2
import time
import keyboard
import torch
from hubconf import custom
model = custom(path_or_model='yolov7-tiny-custom.pt')
with mss.ms... | [
"I tried to reproduce your issue and combined your code with an available yolo-demo, but I couldn't find any issue that would return an error message like that in your question. You can check it in your environment:\nimport mss\nimport numpy as np\nimport cv2\nimport torch\nimport time\n\n\nmodel = torch.hub.load('... | [
1
] | [] | [] | [
"object_detection",
"opencv",
"python",
"yolo"
] | stackoverflow_0074590208_object_detection_opencv_python_yolo.txt |
Q:
Select some columns from PCollection (Apache Beam, Python)
I have the following PCollection:
And I want to select only 2 columns from that PCollection. I tried to do:
def cut_data(data):
return data[["WebSpeedRef", "WebSpeedAct"]]
data_min = data_json | 'min' >> beam.Map(cut_data)
but got an error. What is ... | Select some columns from PCollection (Apache Beam, Python) | I have the following PCollection:
And I want to select only 2 columns from that PCollection. I tried to do:
def cut_data(data):
return data[["WebSpeedRef", "WebSpeedAct"]]
data_min = data_json | 'min' >> beam.Map(cut_data)
but got an error. What is the simplest way to accomplish this.
| [
"You could do this:\ndisired_columns = (\n dataset\n | beam.Map(lambda x: [x[\"column1\"], x[\"column2\"]])\n)\n\n"
] | [
0
] | [] | [] | [
"apache_beam",
"python"
] | stackoverflow_0061873428_apache_beam_python.txt |
Q:
How to fix 'NoneType' has no attribute 'key', when trying to compare a key value to a string
I am writing a program where the user inputs a postfix expression and it outputs the answer. Current I am stuck when Using my 'evaluate' function within my for loop.
Inside my For loop Main.py:
else:
# Debug Code
... | How to fix 'NoneType' has no attribute 'key', when trying to compare a key value to a string | I am writing a program where the user inputs a postfix expression and it outputs the answer. Current I am stuck when Using my 'evaluate' function within my for loop.
Inside my For loop Main.py:
else:
# Debug Code
print('{}: Else'.format(i))
print('{}: Length'.format(len(stack)))
Node.right = stack.pop... | [
"There are several issues:\n\nNode is the name of a class, yet you use the same name for a TreeNode instance, shadowing the class name. This is not the main problem, but certainly not advised. Related: Don't use PascalCase for instances, but camelCase. So node, not Node.\n\nYou assign to Node.right when you have no... | [
1
] | [] | [] | [
"linked_list",
"nodes",
"postfix_notation",
"python",
"stack"
] | stackoverflow_0074593287_linked_list_nodes_postfix_notation_python_stack.txt |
Q:
Is there a way to list all the available Windows' drives?
Is there a way in Python to list all the currently in-use drive letters in a Windows system?
(My Google-fu seems to have let me down on this one)
A C++ equivalent: Enumerating all available drive letters in Windows
A:
import win32api
drives = win32api.Ge... | Is there a way to list all the available Windows' drives? | Is there a way in Python to list all the currently in-use drive letters in a Windows system?
(My Google-fu seems to have let me down on this one)
A C++ equivalent: Enumerating all available drive letters in Windows
| [
"import win32api\n\ndrives = win32api.GetLogicalDriveStrings()\ndrives = drives.split('\\000')[:-1]\nprint drives\n\nAdapted from:\nhttp://www.faqts.com/knowledge_base/view.phtml/aid/4670\n",
"Without using any external libraries, if that matters to you:\nimport string\nfrom ctypes import windll\n\ndef get_drives... | [
75,
73,
24,
19,
14,
10,
7,
4,
3,
3,
1,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0000827371_python_windows.txt |
Q:
Convert between hh:mm:ss time and a float that is a fraction of 24 hours
I get as input times (hh:mm:ss) as float - e.g. 18:52:18 is a float 0.786331018518518.
I achieved to calculate the time from a float value with this code:
val = 0.786331018518518
hour = int(val*24)
minute = int((val*24-hour)*60)
seconds = int... | Convert between hh:mm:ss time and a float that is a fraction of 24 hours | I get as input times (hh:mm:ss) as float - e.g. 18:52:18 is a float 0.786331018518518.
I achieved to calculate the time from a float value with this code:
val = 0.786331018518518
hour = int(val*24)
minute = int((val*24-hour)*60)
seconds = int(((val*24-hour)*60-minute)*60)
print(f"{hour}:{minute}:{seconds}")
How is it ... | [
"What you have is an amount of time, in day unit\nYou can use datetime.timedelta that represents a duration\nval = 0.786331018518518\nd = timedelta(days=val)\nprint(d) # 18:52:19\n\nval = d.total_seconds() / 86400\nprint(val) # 0.7863310185185185\n\n\nFrom your hour/minute/seconds variables it would be\nprint(hou... | [
3,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0074593414_datetime_python.txt |
Q:
Python Version Creates Different Dictionaries
I have a script which needs to be compatible with both Python 2 and 3. The code utilizes a dictionary with is generated using the following line of code:
x = {2**x-1: 1-1/8*x if x>0 else -1 for x in range(0,9)}
In Python 3.6.8, the dictionary is:
>>> x
{0: -1, 1: 0.87... | Python Version Creates Different Dictionaries | I have a script which needs to be compatible with both Python 2 and 3. The code utilizes a dictionary with is generated using the following line of code:
x = {2**x-1: 1-1/8*x if x>0 else -1 for x in range(0,9)}
In Python 3.6.8, the dictionary is:
>>> x
{0: -1, 1: 0.875, 3: 0.75, 7: 0.625, 15: 0.5, 31: 0.375, 63: 0.25,... | [
"The solution I found that is compatible for both versions of Python is:\nx = {2**x-1: 1-float(x)/8 if x>0 else -1 for x in range(0,9)}\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"floating_point",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074593472_dictionary_floating_point_python_python_2.7_python_3.x.txt |
Q:
scrape the overview
I wonder why I cannot scrape this company overview. An example is that I want to scrape Walmart's size, which is 10000+ employees. Below is my code, not sure why the info I am looking for is not there...
import requests
from bs4 import BeautifulSoup
import pandas as pd
headers = {'user-agent'... | scrape the overview | I wonder why I cannot scrape this company overview. An example is that I want to scrape Walmart's size, which is 10000+ employees. Below is my code, not sure why the info I am looking for is not there...
import requests
from bs4 import BeautifulSoup
import pandas as pd
headers = {'user-agent' : 'Mozilla/5.0 (Windows... | [
"Here is one possible solution:\nimport re\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nheaders = {\n 'user-agent': 'Mozilla/5.0'\n}\n\nwith requests.Session() as session:\n session.headers.update(headers)\n raw_data = session.get(f'https://www.glassdoor.com/Overview/Working-at-Walmart... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074588025_beautifulsoup_python_selenium_web_scraping.txt |
Q:
How to resize / rescale a SVG graphic in an iPython / Jupyter Notebook?
I've a large SVG (.svg graphic) object to display in a iPython / Jupyter Notebook. In fact, I've a large neural network model graphic created with Keras to display.
from IPython.display import SVG
from keras.utils.vis_utils import model_to_do... | How to resize / rescale a SVG graphic in an iPython / Jupyter Notebook? | I've a large SVG (.svg graphic) object to display in a iPython / Jupyter Notebook. In fact, I've a large neural network model graphic created with Keras to display.
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
SVG(model_to_dot(model,show_shapes=True).create(prog='dot', format='svg'))... | [
"Another option is to use the \"dpi\" (dots per inch) property. A little hacky but this allowed me to shrink my SVG. \nTensorflow: model_to_doc\n from IPython.display import SVG\n from keras.utils import model_to_dot\n\n SVG(model_to_dot(model, show_shapes= True, show_layer_names=True, dpi=65).create(prog=... | [
12,
5,
3,
0,
0,
0,
0
] | [] | [] | [
"jupyter_notebook",
"keras",
"python",
"svg"
] | stackoverflow_0051452569_jupyter_notebook_keras_python_svg.txt |
Q:
List of the first item in a sublist
I want a list that displays the first element of the sublists I input.
def firstelements(w):
return [item[0] for item in w]
Which works, but when I try doing
firstelements([[10,10],[3,5],[]])
there's an error because of the []. How can I fix this?
A:
Add a condition to y... | List of the first item in a sublist | I want a list that displays the first element of the sublists I input.
def firstelements(w):
return [item[0] for item in w]
Which works, but when I try doing
firstelements([[10,10],[3,5],[]])
there's an error because of the []. How can I fix this?
| [
"Add a condition to your list comprehension so that empty lists are skipped.\ndef firstelements(w):\n return [item[0] for item in w if item != []]\n\nIf you wish to represent that empty list with something but don't want an error you might use a conditional expression in your list comprehension.\ndef firstelemen... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0074593459_python.txt |
Q:
Retrieving specific matches from a list in python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from selenium.w... | Retrieving specific matches from a list in python | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from time import sleep
fro... | [
"Instead of collecting all a elements on the page where will be a lot of irrelevant results you can use more precise locator.\nSo, instead of\ndriver.find_elements(By.TAG_NAME,\"a\")\n\nUse this:\ndriver.find_elements(By.XPATH,\"//a[contains(@href,'https://www.sportingindex.com/spread-betting/football/international... | [
2,
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping",
"xpath"
] | stackoverflow_0074593151_python_selenium_selenium_webdriver_web_scraping_xpath.txt |
Q:
Turning strings into integers from a mixed, nested list
I need to turn certain values from a nested list of strings into integers and find the average of them for a programming assignment.
The list looks like this:
[['Ty', 'Cobb', '178', '65', '934'], ['Chipper', 'Jones', '4532', '873', '32']]
I've tried using fo... | Turning strings into integers from a mixed, nested list | I need to turn certain values from a nested list of strings into integers and find the average of them for a programming assignment.
The list looks like this:
[['Ty', 'Cobb', '178', '65', '934'], ['Chipper', 'Jones', '4532', '873', '32']]
I've tried using for loops to turn them into integers but it returns TypeErrors ... | [
"The format of the data suggests to me that it's something like a CSV where the first two columns are the player names and the remaining columns are scores, and that the ultimately desired result might be to preserve the names along with the average of the associated scores.\nOperating under that assumption, I migh... | [
1
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0074593519_for_loop_list_python.txt |
Q:
Function - encrypt key
I'm trying to create a function that encrypts a number of 4 digits insert by the user.
I was able to reach this:
while True:
num = int(input('Insira um valor entre 1000 e 9999: '))
if num<1000 or num>9999:
print('Insira um valor válido.')
else:
break
num_str = st... | Function - encrypt key | I'm trying to create a function that encrypts a number of 4 digits insert by the user.
I was able to reach this:
while True:
num = int(input('Insira um valor entre 1000 e 9999: '))
if num<1000 or num>9999:
print('Insira um valor válido.')
else:
break
num_str = str(num)
def encrypt(num):
... | [
"With the 2 list, I'd suggest making a mapping from the numbers to the chars\nnums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]\nchars = ['a', '*', 'I', 'D', '+', 'h', '@', 'c', 'Y', 'm']\ncorrespondances = dict(zip(nums, chars))\n\ndef encrip2(value):\n num_encrip = ''\n for c in value:\n num_encrip += correspond... | [
1
] | [] | [] | [
"encryption",
"function",
"python"
] | stackoverflow_0074593536_encryption_function_python.txt |
Q:
Convert a dynamically sized list to a f string
I'm trying to take a list that can be size 1 or greater and convert it to a string with formatting "val1, val2, val3 and val4" where you can have different list lengths and the last value will be formatted with an and before it instead of a comma.
My current code:
inp... | Convert a dynamically sized list to a f string | I'm trying to take a list that can be size 1 or greater and convert it to a string with formatting "val1, val2, val3 and val4" where you can have different list lengths and the last value will be formatted with an and before it instead of a comma.
My current code:
inputlist = ["val1", "val2", "val3"]
outputstr = ""
... | [
"join handles most.\nfor inputlist in [[\"1\"], [\"one\", \"two\"], [\"val1\", \"val2\", \"val3\"]]:\n if len(inputlist) <= 1:\n outputstr = \"\".join(inputlist)\n else:\n outputstr = \" and \".join([\", \".join(inputlist[:-1]), inputlist[-1]])\n print(f\"Formatted list is: {outputstr}\")\n\n... | [
1,
0,
0
] | [] | [] | [
"f_string",
"list",
"python"
] | stackoverflow_0074587672_f_string_list_python.txt |
Q:
Python convert switch data (text) to dict
I have the following data, which I recieve via a ssh session to a switch. I wish to convert the input which is text to a dict for easy access and the possiblity to monitor certain values.
I cannot get the data extracted without a ton of splits and regexes and still get stu... | Python convert switch data (text) to dict | I have the following data, which I recieve via a ssh session to a switch. I wish to convert the input which is text to a dict for easy access and the possiblity to monitor certain values.
I cannot get the data extracted without a ton of splits and regexes and still get stuck.
Port : 1
Media Type : SF+_... | [
"Updated (Complete rewrite and simplification).\nHere are some ideas for you -- adjust to taste.\nThe solution herein tries to avoid using \"domain specific knowledge\" as much as possible. The only assumptions are:\n\nEmpty lines don't matter.\nIndentation is meaningful.\nKeys are transformed to lowercase, and som... | [
2
] | [] | [] | [
"data_conversion",
"python"
] | stackoverflow_0074591658_data_conversion_python.txt |
Q:
Frame border disappears when focus is lost on window
I have a tkinter window from which I open another window. This window contains a Frame which is located inside a Canvas. I'm going to make a picture from the window contents but the problem is that the frame border deactivates itself when the focus isn't on the ... | Frame border disappears when focus is lost on window | I have a tkinter window from which I open another window. This window contains a Frame which is located inside a Canvas. I'm going to make a picture from the window contents but the problem is that the frame border deactivates itself when the focus isn't on the window or I click the meant button for that and therefore ... | [
"The highlightthickness and highlightcolor options are doing exactly what they are designed to do: they only appear when the frame has the focus. It is not designed to be the border of the frame, but rather an indicator of when the frame has focus.\nIf you want a permanent border then you should use borderwidth an... | [
1
] | [] | [] | [
"frame",
"python",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074593595_frame_python_tkinter_tkinter_canvas.txt |
Q:
Where is the actual "sorted" method being implemented in CPython and what is it doing here?
Viewing the source code of CPython on GitHub, I saw the method here:
https://github.com/python/cpython/blob/main/Python/bltinmodule.c
And more specifically:
static PyObject *
builtin_sorted(PyObject *self, PyObject *const *... | Where is the actual "sorted" method being implemented in CPython and what is it doing here? | Viewing the source code of CPython on GitHub, I saw the method here:
https://github.com/python/cpython/blob/main/Python/bltinmodule.c
And more specifically:
static PyObject *
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *newlist, *v, *seq, *callable;
/* ... | [
"The actual sorting is done by list.sort. sorted simply creates a new list from whatever iterable argument it is given, sorts that list in-place, then returns it. A pure Python implementation of sorted might look like\ndef sorted(itr, *, key=None):\n newlist = list(itr)\n newlist.sort(key=key)\n return new... | [
1,
0
] | [] | [] | [
"c",
"cpython",
"python"
] | stackoverflow_0074593461_c_cpython_python.txt |
Q:
pyTesseract recognize a pattern of text
I'm trying to do a simple license plate recognizer. Currently my problem comes from Tesseract messing some readings (for example 5 as S). I know the images are always going to be three uppercase characters, followed by three digits, in the form AAA 999 or so. Is there any wa... | pyTesseract recognize a pattern of text | I'm trying to do a simple license plate recognizer. Currently my problem comes from Tesseract messing some readings (for example 5 as S). I know the images are always going to be three uppercase characters, followed by three digits, in the form AAA 999 or so. Is there any way I can give this info to the OCR?
| [
"Tesseract allows to whitelist specific characters using the tessedit_char_whitelist parameter.\nA way to address your license plate identification problem would be to split your detection window in two \"subwindows\", and:\n\nwhitelist letters for the first subwindow (tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUV... | [
1
] | [] | [] | [
"python",
"python_tesseract",
"tesseract"
] | stackoverflow_0074593614_python_python_tesseract_tesseract.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.