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 convert any expression into list comprehension in python
I have simple question. I want to learn how to write any expression into list comprehension of python.
Here's the minimal code i want to convert into `list
words = ['I', ' ', 'd', 'o', 'n', "'", 't',' ']
temp = ""
templist = []
for i in words:
if... | How to convert any expression into list comprehension in python | I have simple question. I want to learn how to write any expression into list comprehension of python.
Here's the minimal code i want to convert into `list
words = ['I', ' ', 'd', 'o', 'n', "'", 't',' ']
temp = ""
templist = []
for i in words:
if i == " ":
templist.append(temp)
temp = ""
else:
... | [
"You can use list-comprehension with itertools.groupby:\nfrom itertools import groupby\n\nout = [\"\".join(g) for v, g in groupby(words, \" \".__eq__) if not v]\nprint(out)\n\nPrints:\n['I', \"don't\"]\n\n\nOther solution:\nout = \"\".join(words).strip().split(\" \")\nprint(out)\n\n"
] | [
5
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0074326810_list_list_comprehension_python.txt |
Q:
How to create a list of lists by combining lists of strings of a column with python?
I have a column in my dataset consisting of lists of strings like below:
column
['tablet', 'mobile', 'man']
['people', 'house']
. . .
['people', 'computer']
['computer', 'laptop']
How can I get a list of lists with the elements of... | How to create a list of lists by combining lists of strings of a column with python? | I have a column in my dataset consisting of lists of strings like below:
column
['tablet', 'mobile', 'man']
['people', 'house']
. . .
['people', 'computer']
['computer', 'laptop']
How can I get a list of lists with the elements of this column? I want the output like this:
[['tablet', 'mobile', 'man'],['people', 'house'... | [
"Use ast.literal_eval for convert strings lists in list comprehension:\nimport ast\n\nL = [ast.literal_eval(x) for x in df[\"column\"]]\nprint (L)\n[['tablet', 'mobile', 'man'], ['people', 'house'], \n ['people', 'computer'], ['computer', 'laptop']]\n\n",
"If you df is like\n column\n0 ['tab... | [
2,
0,
0
] | [] | [] | [
"list",
"nested_lists",
"pandas",
"python",
"string"
] | stackoverflow_0074312504_list_nested_lists_pandas_python_string.txt |
Q:
Python django cant activate virtual enviroment
I can't activate virtual enviroment and get 'cannot be loaded because running scripts is disabled on this system'
I tried to write 'activate' and './activate' but both dont work
A:
To solve this error:
Simply you can open powershell as admin and then execute below ... | Python django cant activate virtual enviroment | I can't activate virtual enviroment and get 'cannot be loaded because running scripts is disabled on this system'
I tried to write 'activate' and './activate' but both dont work
| [
"To solve this error:\nSimply you can open powershell as admin and then execute below command:\nset-executionpolicy remotesigned\n\nYou will be prompted to accept the change, type A(Yes to all), and press ENTER on your keyboard to allow the change.\nClose the PowerShell admin window, and go back to the PowerShell W... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074326766_django_python.txt |
Q:
Color correction using least square method
I have tried color correcting an image using the least square method. I don't understand why it doesn't work, this is supposed to be the standard way of color calibration.
First I pull in the above image in CR3 format, convert it to RGB space then crop out the four color ... | Color correction using least square method | I have tried color correcting an image using the least square method. I don't understand why it doesn't work, this is supposed to be the standard way of color calibration.
First I pull in the above image in CR3 format, convert it to RGB space then crop out the four color patches using the OpenCV boundingRect and inRang... | [
"Ignoring the fact that the image ICC profile is not properly decoded here, this is the expected result given your reference RGB values and using Colour:\nimport colour\nimport numpy as np\n\n\n# Reference values a likely non-linear 8-bit sRGB values.\n# \"colour.cctf_decoding\" uses the sRGB EOTF by default.\nREFE... | [
4
] | [] | [] | [
"colors",
"computer_vision",
"numpy",
"opencv",
"python"
] | stackoverflow_0074316151_colors_computer_vision_numpy_opencv_python.txt |
Q:
Using temporary files and folders in Web2py app
I am relatively new to web development and very new to using Web2py. The application I am currently working on is intended to take in a CSV upload from a user, then generate a PDF file based on the contents of the CSV, then allow the user to download that PDF. As par... | Using temporary files and folders in Web2py app | I am relatively new to web development and very new to using Web2py. The application I am currently working on is intended to take in a CSV upload from a user, then generate a PDF file based on the contents of the CSV, then allow the user to download that PDF. As part of this process I need to generate and access sever... | [
"I was having this error \"TypeError: expected string or Unicode object, NoneType found\" and I had to store just a link in the session to the uploaded document in the db or maybe the upload folder in your case. I would store it to upload to proceed normally, and then clear out the values and the file if not 'appr... | [
0,
0
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0074292386_python_web2py.txt |
Q:
Why the scrapping data from a somewebsite is difficult?
I have beed trying to learn a little bit about python automation, in which i'm trying to learn web-scrapping.
i have chosen to made a discord bot which accepts a user id of player of a game called "brawlhalla" and show the details of the player from some live... | Why the scrapping data from a somewebsite is difficult? | I have beed trying to learn a little bit about python automation, in which i'm trying to learn web-scrapping.
i have chosen to made a discord bot which accepts a user id of player of a game called "brawlhalla" and show the details of the player from some live tracking websites
and my approach was to accept a playercode... | [
"The data you see on the page is loaded with JavaScript, so beautifulsoup doesn't see it. Solution could be using their Ajax URL and request the Json data using requests:\nimport json\nimport requests\n\nplayer_id = 65340087\napi_url = (\n \"https://brawlhallastats.herokuapp.com/api/submit-form3-by-id?player={}\... | [
0
] | [] | [] | [
"automation",
"beautifulsoup",
"python"
] | stackoverflow_0074326857_automation_beautifulsoup_python.txt |
Q:
Bokeh DataTable compare cells between rows & highlight if different
I have a Bokeh DataTable and would like to to compare each cell from row 1 with the cells from all other rows and highlight cells with differing values. This is what I came up with so far:
import pandas as pd
from bokeh.models import HTMLTemplate... | Bokeh DataTable compare cells between rows & highlight if different | I have a Bokeh DataTable and would like to to compare each cell from row 1 with the cells from all other rows and highlight cells with differing values. This is what I came up with so far:
import pandas as pd
from bokeh.models import HTMLTemplateFormatter, DataTable, TableColumn
from bokeh.plotting import show, output... | [
"I hope I did understand you and you want to format each column by the first value of the column.\nIn that case you are very close to a working solution. You only have to pass one value instead a list to the formatter, which is created by column.\nimport pandas as pd\n\nfrom bokeh.models import HTMLTemplateFormatte... | [
0
] | [] | [] | [
"bokeh",
"datatable",
"python"
] | stackoverflow_0074321565_bokeh_datatable_python.txt |
Q:
Access values from multiple dictionaries within a list
I was making a scraper for my school website, which automatically gets the homework for today.
[
{
"id": "1523958",
"studentId": "8326",
"assignmentId": "35074",
"diaryType": "cw",
"diaryId": "35074",
"subjec... | Access values from multiple dictionaries within a list | I was making a scraper for my school website, which automatically gets the homework for today.
[
{
"id": "1523958",
"studentId": "8326",
"assignmentId": "35074",
"diaryType": "cw",
"diaryId": "35074",
"subject": "URDU",
"title": "اچھے آداب و اطوار",
"d... | [
"According the comments, you can iterate over the list and check for your condition. For example (lst is your list from question):\nfor d in lst:\n if d[\"studentId\"] == \"8426\" and d[\"date\"] == \"Fri, 04/11/2022\":\n print(d[\"assignmentId\"])\n\nPrints:\n35013\n35007\n35005\n\n",
"diaries = [\n{\n... | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074326899_dictionary_list_python.txt |
Q:
Getting index of list within a dictionary
I have created a key:value pair from a csv, where the value is actually a list of all the rows of data, i.e
has now become:
Date ['04-Nov-22', '05-Nov-22']
USD [0.9872, 2.9872]
JPY [145.19, 11115.19]
I get the above results by doing:
for key,value in df.items()
print(... | Getting index of list within a dictionary | I have created a key:value pair from a csv, where the value is actually a list of all the rows of data, i.e
has now become:
Date ['04-Nov-22', '05-Nov-22']
USD [0.9872, 2.9872]
JPY [145.19, 11115.19]
I get the above results by doing:
for key,value in df.items()
print(key,value)
I know this works because, if I sel... | [
"I wouldn't use a loop but pre-process the DataFrame:\ns = df.reset_index().set_index('Date')['index']\n\nThen, access the index per date using get with a default value if missing:\nuser_input = '04-Nov-22'\nout = s.get(user_input, 'date not found')\n\nOutput: 0\n"
] | [
1
] | [] | [] | [
"csv",
"key_value",
"list",
"pandas",
"python"
] | stackoverflow_0074326778_csv_key_value_list_pandas_python.txt |
Q:
is there any way to get position of the RECT in pygame?
I want to know is there any way I can have the position of the Rect I create and stored in variable name "rect" in pygame
A:
A pygame.Rect object has a lot of virtual attributes:
The Rect object has several virtual attributes which can be used to move and ... | is there any way to get position of the RECT in pygame? | I want to know is there any way I can have the position of the Rect I create and stored in variable name "rect" in pygame
| [
"A pygame.Rect object has a lot of virtual attributes:\n\nThe Rect object has several virtual attributes which can be used to move and align the Rect:\nx,y\ntop, left, bottom, right\ntopleft, bottomleft, topright, bottomright\nmidtop, midleft, midbottom, midright\ncenter, centerx, centery\nsize, width, height\nw,h\... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074327017_pygame_python.txt |
Q:
random numbers (using random.randint) returning None
I'm trying to get a random number that is not used (already printed).
here's my code:
import random
used_numbers = []
def generate_random_number():
num = random.randint(1, 90)
if num not in used_numbers:
used_numbers.append(num)
return n... | random numbers (using random.randint) returning None | I'm trying to get a random number that is not used (already printed).
here's my code:
import random
used_numbers = []
def generate_random_number():
num = random.randint(1, 90)
if num not in used_numbers:
used_numbers.append(num)
return num
elif num in used_numbers and num == generate_random... | [
"You can use sets to guarantee the uniqueness of numbers and a while loop to iterate until you have a previously unseen number.\nSo, your function becomes:\nimport random\nused_numbers = set()\n\ndef generate_random_number():\n num = random.randint(1, 90)\n while num in used_numbers:\n num = random.ran... | [
0
] | [] | [] | [
"list",
"python",
"random",
"variables"
] | stackoverflow_0074327029_list_python_random_variables.txt |
Q:
How to check if table exists?
I'm using this function :
def checker(name,s)
MY_T = "SELECT count(*) FROM `"+session.SessionInfo.Name where EventName='"+name+"'"
I want to check if the table exists, how can I do it?
I saw some examples using XXXX.execute(). What does it mean?
Here is what I saw:
query = cu... | How to check if table exists? | I'm using this function :
def checker(name,s)
MY_T = "SELECT count(*) FROM `"+session.SessionInfo.Name where EventName='"+name+"'"
I want to check if the table exists, how can I do it?
I saw some examples using XXXX.execute(). What does it mean?
Here is what I saw:
query = cursor.execute("""SELECT count(*) FRO... | [
"Use the \"TABLES\" information schema view.\nhttp://dev.mysql.com/doc/refman/5.0/en/information-schema.html\nSELECT * FROM information_schema.tables\nWHERE table_name = 'YOUR TABLE'\n\nYou can apply this view to your code by doing something like the following:\ndef checkTableExists(dbcon, tablename):\n dbcur = ... | [
33,
22,
2,
1,
1,
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0017044259_python_sql.txt |
Q:
How to Group by without aggregation and keep all values as new columns
I have dataset like this below.
What i want to do is I want to groupby the data based on date column but do not want aggregation on avg_wind_speed_kts column, instead, i want all the values in avg_wind_speed_kts for one particular date to be a... | How to Group by without aggregation and keep all values as new columns | I have dataset like this below.
What i want to do is I want to groupby the data based on date column but do not want aggregation on avg_wind_speed_kts column, instead, i want all the values in avg_wind_speed_kts for one particular date to be added as new columns. Like below for example
| | date | s1 | s2 | s3 | ....... | [
"Sample data:\ndf=pd.DataFrame(data={'day':['2018-01-01','2018-01-01','2018-01-01','2018-01-01','2018-01-02','2018-01-02','2018-01-02','2018-01-02'],'avg_wind_speed_kts':[6.0434785,6.652174,4.0869565,3.2608695,6.652174,3.2608695,5.5652175,5.9130435]})\ndf\n day avg_wind_speed_kts\n0 2018-01-01 6.04347... | [
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074326050_dataframe_group_by_pandas_python.txt |
Q:
Deletion in queue from front in Python
I have written a program for implementaion of queue using Python. Insertion and display of the queue works fine. But I can't delete element from front of queue. I have tried del keyword as well as pop method. In both the ways, the element is deleted from fron of the queue, in... | Deletion in queue from front in Python | I have written a program for implementaion of queue using Python. Insertion and display of the queue works fine. But I can't delete element from front of queue. I have tried del keyword as well as pop method. In both the ways, the element is deleted from fron of the queue, insted it deleted from front+1. For example, t... | [
"Look at below. You don't need front index. When you popped front item. it will remove that item completely from queue. That is why you don't need it. But in your code you every dequeue increased front.\nBut python will automatically removes it from queue.\nfront=0 always. So just use queue.pop(0).\nLook at below.\... | [
0
] | [] | [] | [
"data_structures",
"python",
"python_3.x",
"queue"
] | stackoverflow_0074326964_data_structures_python_python_3.x_queue.txt |
Q:
python setter setting two variables doesnt work for list
i have a beginner question (my oop is terrible) about how to achieve a feature in python where i have an instance of a class (Line) where setting one attribute to a value automatically updates another attribute and vice versa.
I believe i did achieve that wh... | python setter setting two variables doesnt work for list | i have a beginner question (my oop is terrible) about how to achieve a feature in python where i have an instance of a class (Line) where setting one attribute to a value automatically updates another attribute and vice versa.
I believe i did achieve that when my attributes are integers:
class Line:
def __init__(se... | [
"TLDR: In first case, you are just assigning the value without trying to read it, in second case with list, you are trying to read it with indexing while assigning the value of coordinates attribute which doesn't exist yet.\nIn the constructor when you are initializing variable x0 it calls setter to basically set t... | [
2
] | [] | [] | [
"getter_setter",
"oop",
"python"
] | stackoverflow_0074327068_getter_setter_oop_python.txt |
Q:
Is it possible to edit the text stored at the top of the page and just insert a variable name where I want the text pasted in html for a blog website
I am trying to make a blog but without a complex backend using HTML
How can I store the article using a variable and just use that variable name where I want the tex... | Is it possible to edit the text stored at the top of the page and just insert a variable name where I want the text pasted in html for a blog website | I am trying to make a blog but without a complex backend using HTML
How can I store the article using a variable and just use that variable name where I want the text pasted, instead of every time I want to post/ edit having to scroll all the way to find it.
something like in python where you can have a variable and ed... | [
"Do you mean something like this - where you just pre-write your template, and then get python to dynamically add the text you want into the template like this:\ndynamic_text = \"Here is my new title\"\n\nhtml = f\"<div><h1>{dynamic_text}</h1></div>\"\nprint(html)\n\nOUTPUT:\n<div><h1>Here is my new title</h1></div... | [
0
] | [] | [] | [
"css",
"html",
"python"
] | stackoverflow_0074326937_css_html_python.txt |
Q:
Calculating statistics across slices of 3D NumPy array
Sorry if this has been answered already but I can't find a good solution.
I have a large 3D numpy array with dimensions (1e5, 1e3, 1e3) and I need to calculate a SciPy statistic (Weibull parameters) across each slice of the 1st dimension. A nested for loop wou... | Calculating statistics across slices of 3D NumPy array | Sorry if this has been answered already but I can't find a good solution.
I have a large 3D numpy array with dimensions (1e5, 1e3, 1e3) and I need to calculate a SciPy statistic (Weibull parameters) across each slice of the 1st dimension. A nested for loop would get the job done but obviously not ideal. I've looked at ... | [
"In theory this should work:\nimport numpy as np\n\na = np.ones((1000, 100, 100)) # fill with your input\nstat = np.empty((100, 100)) # result\n\ndef calculate_statistic(array1d): # 1D array as the parameter\n return sum(array1d) # example function\n\nstat = calculate_statistic(a)\n\nprint(stat.shape) # ret... | [
0
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074226297_numpy_numpy_ndarray_python.txt |
Q:
please help me with this python exercise
input = [[0,1,2,3,4,5], [0,1,2,3,4,5], [0,1,2,3,4,5]]
output = [0****0, *1**1*, **22**]
This is what I've tried so far:
for x in input:
for y in x:
if int(x.index(y)) == int(input.index(x)):
And I got stuck. I don't know how to make the value of the [0] index... | please help me with this python exercise | input = [[0,1,2,3,4,5], [0,1,2,3,4,5], [0,1,2,3,4,5]]
output = [0****0, *1**1*, **22**]
This is what I've tried so far:
for x in input:
for y in x:
if int(x.index(y)) == int(input.index(x)):
And I got stuck. I don't know how to make the value of the [0] index == that of the last index (and the [1] index ... | [
"inp = [[0,1,2,3,4,5], [0,1,2,3,4,5], [0,1,2,3,4,5]]\n# out = [0****0, *1**1*, **22**] \n\nout = [] # here we create a list for finale output, now it's empty \n\ncount = 0 #this variable count we use for knowing what is the index iterable element\nfor i in inp: # ordinary for loop, we eterate inp. on first ... | [
-1
] | [] | [] | [
"python"
] | stackoverflow_0074327070_python.txt |
Q:
Spliting pandas dataframe by date
I have dataset df with dates:
tpep_dropoff_datetime
2020-01-01 00:33:03 (first date)
2020-02-01 00:16:35 (last date)
Desired output should look like this:
tpep_dropoff_datetime
2020-01-01
2020-01-02
2020-01-03
2020-01-04
...
Is there a way to split this dataframe to... | Spliting pandas dataframe by date | I have dataset df with dates:
tpep_dropoff_datetime
2020-01-01 00:33:03 (first date)
2020-02-01 00:16:35 (last date)
Desired output should look like this:
tpep_dropoff_datetime
2020-01-01
2020-01-02
2020-01-03
2020-01-04
...
Is there a way to split this dataframe to seperate ones by this field. Thanks.
| [
"Difficult to give a complete answer with so few details.\nIf you really want to split you can use:\ndfs = [g for _,g in df.groupby(pd.to_datetime(df['tpep_dropoff_datetime']).dt.normalize())]\n\nOr as a dictionary with the date as key:\ndfs = {date: g for date, g in df.groupby(pd.to_datetime(df['tpep_dropoff_datet... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074327071_pandas_python.txt |
Q:
Custom Download folder for chromedriver in python
I want to save the files I get with a scraper into custom folders. I looked around and none of the solutions I found worked for me. Here is my configuration:
options = webdriver.ChromeOptions()
prefs = {
'profile.default_content_settings.popups': 0,
... | Custom Download folder for chromedriver in python | I want to save the files I get with a scraper into custom folders. I looked around and none of the solutions I found worked for me. Here is my configuration:
options = webdriver.ChromeOptions()
prefs = {
'profile.default_content_settings.popups': 0,
'download.default_directory': my_data_folder,
... | [
"Have you thought about using shutil to move the file after the download ?\nHere's how I had that implemented in another project I was working on\nfilename = max([\n download_folder + \"\\\\\" + f for f in os.listdir(download_folder)],\n key=os.path.getctime)\n\nshutil.move(\n filename,\n os.path.join(d... | [
1
] | [] | [] | [
"python",
"selenium_chromedriver"
] | stackoverflow_0074327136_python_selenium_chromedriver.txt |
Q:
Django - How to redirect users without hard-coding URLS
I am creating Django Application. We want user to be redirected to new screen on button click, but we don't want to have to hardcode URL.
We have a top level screen, and we want to redirect user to screens after they click a button on the Level screen, Howeve... | Django - How to redirect users without hard-coding URLS | I am creating Django Application. We want user to be redirected to new screen on button click, but we don't want to have to hardcode URL.
We have a top level screen, and we want to redirect user to screens after they click a button on the Level screen, However, we have multiple level screens so it would't make sense to... | [
"Django has a \"parser\" which allows you to define dynamic links within the urls.py\nA dynamic url can for example be a way to access different pictures in the /media folder. For example: host/media/{?}. This isn't how you write it in django, but this is just to explain the logic behind dynamic urls. The {?} in th... | [
0
] | [] | [] | [
"django",
"python",
"url",
"view"
] | stackoverflow_0074322414_django_python_url_view.txt |
Q:
I can't convert string type to dictionary using json.loads in python
The target is to extract a MP4 video link on MLB website.
url ="https://www.mlb.com/video/jeremy-pena-s-solo-homer?t=most-popular"
content = requests.get(url).text
I have found the target dict.
soup = BeautifulSoup(content,"lxml")
all_script_la... | I can't convert string type to dictionary using json.loads in python | The target is to extract a MP4 video link on MLB website.
url ="https://www.mlb.com/video/jeremy-pena-s-solo-homer?t=most-popular"
content = requests.get(url).text
I have found the target dict.
soup = BeautifulSoup(content,"lxml")
all_script_label = soup.find_all(name ="script")
target = all_script_label[20].text.sp... | [
"You can apply json.loads second time to convert the str to dict:\nimport re\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.mlb.com/video/jeremy-pena-s-solo-homer?t=most-popular\"\ncontent = requests.get(url).text\nsoup = BeautifulSoup(content, \"lxml\")\nall_script_label = soup... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074327152_json_python.txt |
Q:
Adding values from a list into a dictionary
I've created a loop that scrapes website data (Deal ID and destinations) using Chromedriver and adds them to a list. I want to pair the Deal ID with the values taken from the destination table and add them to a dictionary. Each website scrape iteration has a different nu... | Adding values from a list into a dictionary | I've created a loop that scrapes website data (Deal ID and destinations) using Chromedriver and adds them to a list. I want to pair the Deal ID with the values taken from the destination table and add them to a dictionary. Each website scrape iteration has a different number of destinations (sometimes up to 20), but on... | [
"you can use this code:\ndicts['Deal ID #123'] = ['Lisbon, Portugal', Seville, Spain']\ndicts['Deal ID #456'] = ['Monte Carlo, Monaco', 'Marseille, France', 'Istanbul, Turkey', 'Myrina (Limnos), Greece']\n\n"
] | [
2
] | [] | [] | [
"dictionary",
"for_loop",
"list",
"python",
"selenium_chromedriver"
] | stackoverflow_0071945585_dictionary_for_loop_list_python_selenium_chromedriver.txt |
Q:
Change hover text
I have the following code:
x=["a","b","c","d"]
y1=[1,3,7,2]
y2=[3,6,1,2]
y3=[0.25, 0.33, 0.875, 0.5]
y4=[0.75, 0.66, 0.125, 0.5]
fig = go.Figure([
go.Scatter(
name='Data 1',
x=x,
y=y1,
marker=dict(color="red"),
line=dict(width=3),
mode='lines',
... | Change hover text | I have the following code:
x=["a","b","c","d"]
y1=[1,3,7,2]
y2=[3,6,1,2]
y3=[0.25, 0.33, 0.875, 0.5]
y4=[0.75, 0.66, 0.125, 0.5]
fig = go.Figure([
go.Scatter(
name='Data 1',
x=x,
y=y1,
marker=dict(color="red"),
line=dict(width=3),
mode='lines',
line_shape='spl... | [
"If you want to display different data in the hover text, you can use the custom data feature to add it to the display. I simply added the additional data by opening a blank space, as there is no mention of how to display it.\nimport plotly.graph_objects as go\n\nx=[\"a\",\"b\",\"c\",\"d\"]\ny1=[1,3,7,2]\ny2=[3,6,1... | [
1
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074326688_plotly_python.txt |
Q:
Filter Rows If The First Sign Change Is Detected In A Column By Group In Python
I have a dataframe:
col1 col2 group
10 1 A
11 2 A
12 -2 A
13 -3 B
14 3 B
How do I choose rows if there is a first sign change in col2 by group.
For instance, for the first unique value of group ('A'), the f... | Filter Rows If The First Sign Change Is Detected In A Column By Group In Python | I have a dataframe:
col1 col2 group
10 1 A
11 2 A
12 -2 A
13 -3 B
14 3 B
How do I choose rows if there is a first sign change in col2 by group.
For instance, for the first unique value of group ('A'), the first sign change (+ to -) occurs at the third row (col1=12 and col2 = -2).
Desired re... | [
"import pandas as pd\n\nind = []\n\n\ndef my_func(x):\n if x.loc[x.index[0], 'col2'] < 0:\n ind.append(x[x['col2'] >= 0].index[0])\n else:\n ind.append(x[x['col2'] < 0].index[0])\n\n\ndf.groupby('group').apply(my_func)\n\ndf1 = df.loc[ind]\n\nprint(df1)\n\nOutput\n col1 col2 group\n2 12 ... | [
1
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0074323172_lambda_python.txt |
Q:
Using Matplotlib to Plot Sympy Implicit Function
I have an implicit function, say x**2 - y = 0 (to simplify), of which I want to obtain a plot for a certain range of x values.
sympy.plot_implicit usually gives some spreading of the lines that I am not happy with.
I would like to have access to the plotted values, ... | Using Matplotlib to Plot Sympy Implicit Function | I have an implicit function, say x**2 - y = 0 (to simplify), of which I want to obtain a plot for a certain range of x values.
sympy.plot_implicit usually gives some spreading of the lines that I am not happy with.
I would like to have access to the plotted values, and so pyplot.plot is preferable to me. Usually I use ... | [
"The line spread of plot_implicit is caused by the adaptive algorithm. If you set the option adaptive=False the plotting module would use a meshgrid approach. However, due to the implementation, the figure is likely not going to be good (too much \"segmentation\").\nThis is how you can do it with Numpy and Matplotl... | [
2
] | [
"To have access to the plotted values of a sympy function plot, in this case the coordinates of lines2d plot, is simple.\nHere is the code that plots the function.\nimport matplotlib.pyplot as plt\nfrom sympy import symbols\nimport numpy as np\nimport sympy\n\nx, y = symbols('x y', nonnegative=True)\nexp = x**2\n\n... | [
-1
] | [
"matplotlib",
"numpy",
"python",
"python_3.x",
"sympy"
] | stackoverflow_0074326562_matplotlib_numpy_python_python_3.x_sympy.txt |
Q:
Install playwright from a local directory
I need to install playwright from a local directory containing archives without check [PyPI]. I'm using the command:
py -m pip install --no-index --find-links=MY/PATH playwright-1.27.1-py3-none-win_amd64.whl
And I'm getting an error:
ERROR: Could not find a version that s... | Install playwright from a local directory | I need to install playwright from a local directory containing archives without check [PyPI]. I'm using the command:
py -m pip install --no-index --find-links=MY/PATH playwright-1.27.1-py3-none-win_amd64.whl
And I'm getting an error:
ERROR: Could not find a version that satisfies the requirement greenlet==1.1.3 (from ... | [
"https://github.com/microsoft/playwright-python/issues/1622 :\n\nSounds like we need to upgrade to Greenlet v2 for that.\n\n"
] | [
0
] | [] | [] | [
"playwright",
"python"
] | stackoverflow_0074308398_playwright_python.txt |
Q:
app.callback function doesn't work, no error message (dash)
I have a small Dash web app that works nicely, allowing the user to input data & upload data to generate a number of plots. I tried to add a button that would allow people to try out the software and view some sample plots without needing to enter or uplo... | app.callback function doesn't work, no error message (dash) | I have a small Dash web app that works nicely, allowing the user to input data & upload data to generate a number of plots. I tried to add a button that would allow people to try out the software and view some sample plots without needing to enter or upload any data, but the @app.callback I added has broken the web app... | [
"Thank you to Mack Raymond for pointing out that I had debug mode turned off, and when turned on I get the following error;\n\nIn the callback for output(s): \nsplitter.children Output 0 \n(splitter.children) is already in use. Any given output can only have \none callback that sets it. To resolve this situation, t... | [
0
] | [] | [] | [
"plotly_dash",
"python"
] | stackoverflow_0074324052_plotly_dash_python.txt |
Q:
Discord.py does not want to send mistakes to the console
I wrote the code for the output in the error console via utils.setup_logging
Errors were derived correctly when I only used this code:
discord.utils.setup_logging(level = logging.ERROR, root = False)
discord.utils.setup_logging(level = logging.WARN, root = F... | Discord.py does not want to send mistakes to the console | I wrote the code for the output in the error console via utils.setup_logging
Errors were derived correctly when I only used this code:
discord.utils.setup_logging(level = logging.ERROR, root = False)
discord.utils.setup_logging(level = logging.WARN, root = False)
discord.utils.setup_logging(level = logging.WARNING, roo... | [
"I've recently updated my code with logging. First of all, after you have imported library, you should give the basic config of your log.\nimport logging\n\nlogging.basicConfig(filename=\"bot.log\", level=logging.INFO, filemode=\"a\")\n\nAs you saw there are multiple levels of logs, NOTSET, DEBUG, INFO, WARNING, ER... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074326998_discord.py_python.txt |
Q:
Execute Python code in an interactive shell in VS Code
I used to use Pyzo for Python coding and decided to give VS Code a try because it is more feature-rich. I came across one huge annoyance, however. In Pyzo, I am used to code „interactively“ as Pyzo executes code in an interactive shell (https://pyzo.org/featur... | Execute Python code in an interactive shell in VS Code | I used to use Pyzo for Python coding and decided to give VS Code a try because it is more feature-rich. I came across one huge annoyance, however. In Pyzo, I am used to code „interactively“ as Pyzo executes code in an interactive shell (https://pyzo.org/features.html).
I would like to replicate that in VS Code, but so ... | [
"Use Code Runner(extension available in the marketplace of VS Code) or run a bash script in the terminal (python -u [name of the file])\n",
"I use Python Interactive window and find it very useful. It is not an immediate REPL but gives you the time to write a block of code and execute it with a key stroke.\nAt th... | [
0,
0
] | [] | [] | [
"python",
"pyzo",
"visual_studio_code"
] | stackoverflow_0074326678_python_pyzo_visual_studio_code.txt |
Q:
How to join up 2 list with a distinct format?
how do I join these 2 list
suits = ['C','D','H','S']
and
value = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
to A-C, 2-C and so forth until K-S?
i tried doing these format but it didn't work
def options():
i = 13
option1 = []
while ... | How to join up 2 list with a distinct format? | how do I join these 2 list
suits = ['C','D','H','S']
and
value = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
to A-C, 2-C and so forth until K-S?
i tried doing these format but it didn't work
def options():
i = 13
option1 = []
while True:
option = input()
suits = ['C','D'... | [
"already answered it\ni did this instead\n'''suits = ['C','D','H','S']\nvalue = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\nfor i in suits:\nfor j in value:\ncards = print(j+\"-\"+i, end=\",\")'''\n"
] | [
0
] | [] | [] | [
"concatenation",
"join",
"python"
] | stackoverflow_0074327187_concatenation_join_python.txt |
Q:
python AWS boto3 create presigned url for file upload
I'm writing a django backend for an application in which the client will upload a video file to s3. I want to use presigned urls, so the django server will sign a url and pass it back to the client, who will then upload their video to s3. The problem is, the ge... | python AWS boto3 create presigned url for file upload | I'm writing a django backend for an application in which the client will upload a video file to s3. I want to use presigned urls, so the django server will sign a url and pass it back to the client, who will then upload their video to s3. The problem is, the generate_presigned_url method does not seem to know about the... | [
"In addition to the already mentioned usage of:\nboto3.client('s3').generate_presigned_url('put_object', Params={'Bucket':'your-bucket-name', 'Key':'your-object-name'})\n\nYou can also use:\nboto3.client('s3').generate_presigned_post('your-bucket_name', 'your-object_name')\n\nReference: https://boto3.amazonaws.com/... | [
11,
1,
0
] | [] | [] | [
"amazon_s3",
"boto3",
"file_upload",
"pre_signed_url",
"python"
] | stackoverflow_0061488583_amazon_s3_boto3_file_upload_pre_signed_url_python.txt |
Q:
Read USB flow in Python - Windows
I need to read data from a barcode reader in Python. The problem is that the barcode reader is usb-connected to the PC which run a software for item sales. So I will need to run a python software in background and read the input from the usb-barcode reader. How can I implement thi... | Read USB flow in Python - Windows | I need to read data from a barcode reader in Python. The problem is that the barcode reader is usb-connected to the PC which run a software for item sales. So I will need to run a python software in background and read the input from the usb-barcode reader. How can I implement this?
I'm on Windows.
Another idea but I d... | [
"Normally the vendors of the Barcode Scanner (e.g. Zebra) provide an SDK like this one here: https://www.zebra.com/gb/en/products/software/scanning-systems/scanner-drivers-and-utilities/scanner-sdk-for-windows.html\nThis should be the easiest approach if you find one like this. Some devices also provide a virtual C... | [
0
] | [] | [] | [
"barcode",
"barcode_scanner",
"python",
"usb"
] | stackoverflow_0074327160_barcode_barcode_scanner_python_usb.txt |
Q:
How to pop up an alert in Python and at the same time keep the process running?
I have a sample script below. The alert message will pop up but the user will have to acknowledge before the script could continue to run. So how do I pop up an alert in Python and at the same time keep the process running?
import rand... | How to pop up an alert in Python and at the same time keep the process running? | I have a sample script below. The alert message will pop up but the user will have to acknowledge before the script could continue to run. So how do I pop up an alert in Python and at the same time keep the process running?
import random
import time
x = 0
while x <= 20:
a = random.randint(1, 100)
print (a)
... | [
"Use threading.Thread.\nThis launches the alert in a separate thread, so that it does not block the main thread.\nimport random\nimport time\nimport threading\n\ndef alert():\n ctypes.windll.user32.MessageBoxW(0, \"The number generated is less than 10\", \"ALERT\", 1)\n\nfor _ in range(20):\n a = random.randi... | [
0,
0
] | [] | [] | [
"alert",
"popup",
"python"
] | stackoverflow_0044077887_alert_popup_python.txt |
Q:
layoutparser gives error "module layoutparser has no attribute ocr"
I am trying to use the new layoutparser package to do some OCR. However, coming from an R backgroud I have a hard time getting it up and running.
I installed it via (worked fine):
pip install layoutparser
pip install "layoutparser[ocr]"
Now, when... | layoutparser gives error "module layoutparser has no attribute ocr" | I am trying to use the new layoutparser package to do some OCR. However, coming from an R backgroud I have a hard time getting it up and running.
I installed it via (worked fine):
pip install layoutparser
pip install "layoutparser[ocr]"
Now, when I run the following I get an error:
import layoutparser as lp
import ma... | [
"ocr_agent = lp.TesseractAgent()\n\n",
"This worked for me (at least no python error):\nimport layoutparser.ocr as ocr\nocr_agent = ocr.TesseractAgent()\n\nBut need an explaination why the following does not work:\nimport layoutparser as lp\nocr_agent = lp.ocr.TesseractAgent()\n\n",
"The documentation states 'I... | [
4,
0,
0,
0
] | [] | [] | [
"ocr",
"python"
] | stackoverflow_0069705864_ocr_python.txt |
Q:
How can I Orchestrate Python Scripts with different virtual envs
How can I use Rocketry (Python) with multiple virtual environments? I try to use Rocketry as Process Orchestrator (because it's easier than Airflow and I don't need to run on different machines).
But I don't know how to run different processes that u... | How can I Orchestrate Python Scripts with different virtual envs | How can I use Rocketry (Python) with multiple virtual environments? I try to use Rocketry as Process Orchestrator (because it's easier than Airflow and I don't need to run on different machines).
But I don't know how to run different processes that use different virtualenvs.
(doc of rocketry: https://github.com/Miksus/... | [
"Author of Rocketry here. I have thought of at some point making a native virtual env support but at the moment doing that yourself is not difficult either. There are two options:\n\nUse regular function task as a wrapper\nUse a command task\n\nNote that I have Windows now thus the location of your Python interpret... | [
2
] | [] | [] | [
"airflow",
"orchestration",
"python",
"schedule"
] | stackoverflow_0074228559_airflow_orchestration_python_schedule.txt |
Q:
this code isnt creating my site.db file in directory
#main
from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm, LoginForm
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://... | this code isnt creating my site.db file in directory | #main
from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm, LoginForm
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
#users
class User(db.Mod... | [
"sqlite:///site.db is a relative path, it can sometimes be hard to work out what this is relative to.\nIt will probably help to be more specific and use an absolute path.\nAn easy way to do this is by using app.root_path to construct your path.\napp.root_path is the path to the directory of the file containing app ... | [
1
] | [] | [] | [
"flask_sqlalchemy",
"python"
] | stackoverflow_0074297632_flask_sqlalchemy_python.txt |
Q:
PySimpleGUI: is there any way to create a new folder from FileSaveAs?
But I would like for the user, when using a "Save As" function, to also be able to create a new folder in which to put the file.
Is there any way to do this? I've looked through the call reference and the demo programs and don't see anything. Fi... | PySimpleGUI: is there any way to create a new folder from FileSaveAs? | But I would like for the user, when using a "Save As" function, to also be able to create a new folder in which to put the file.
Is there any way to do this? I've looked through the call reference and the demo programs and don't see anything. FileSaveAs works beautifully for existing folders, but there doesn't seem to... | [
"Using the sg.SaveAs() chooser button in PySimpleGUI opens a \"Save As\" dialog box. It has specific options provided for the user to create folders that are not normally shown when browsing for a file to open.\nIf you wish to create them for the user, you can use os.mkdir prior to showing the dialog.\n\n"
] | [
0
] | [] | [] | [
"directory",
"pysimplegui",
"python"
] | stackoverflow_0074321020_directory_pysimplegui_python.txt |
Q:
Applying time.sleep on each element of a python list
I want to independently iterate elements of a list in a marathon-like formation, such that each lane/element can move at a random/varied pace.
In order to still be able to access each element by index, I tried the following code:
cyclists = ['abcde', 'fghij', 'k... | Applying time.sleep on each element of a python list | I want to independently iterate elements of a list in a marathon-like formation, such that each lane/element can move at a random/varied pace.
In order to still be able to access each element by index, I tried the following code:
cyclists = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy'] #each elements represe... | [
"The way this was set up was a bit too confusing to me, so I coded up my own version of how a race could happen using time.sleep. I tried to add lots of comments to explain all the steps:\nimport time\n\nrunners = [\n {'name':'Samantha', 'speed':3.5, 'distance_traveled':0},\n {'name':'Ben', 'speed':2.9, ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074316674_python.txt |
Q:
Timeout on a function call
I'm calling a function in Python which I know may stall and force me to restart the script.
How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
A:
You may use the signal package if you are running ... | Timeout on a function call | I'm calling a function in Python which I know may stall and force me to restart the script.
How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
| [
"You may use the signal package if you are running on UNIX:\nIn [1]: import signal\n\n# Register an handler for the timeout\nIn [2]: def handler(signum, frame):\n ...: print(\"Forever is over!\")\n ...: raise Exception(\"end of time\")\n ...: \n\n# This function *may* run for an indetermined time...\n... | [
310,
218,
110,
65,
40,
34,
21,
21,
20,
18,
9,
6,
6,
5,
3,
2,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"multithreading",
"python",
"python_multithreading",
"timeout"
] | stackoverflow_0000492519_multithreading_python_python_multithreading_timeout.txt |
Q:
how to solve this error while installing dependencies
i want to install these dependencies (streamlit, fbprophet, yfinance, plotly)
i run : pip install streamlit fbprophet yfinance plotly
it is showing this error in the terminal!
Collecting streamlit
Using cached streamlit-1.14.0-py2.py3-none-any.whl (9.2 MB)
Co... | how to solve this error while installing dependencies | i want to install these dependencies (streamlit, fbprophet, yfinance, plotly)
i run : pip install streamlit fbprophet yfinance plotly
it is showing this error in the terminal!
Collecting streamlit
Using cached streamlit-1.14.0-py2.py3-none-any.whl (9.2 MB)
Collecting fbprophet
Using cached fbprophet-0.7.1.tar.gz (6... | [
"ModuleNotFoundError: No module named 'Cython'\nYou need Cython inorder to install pystan\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074327583_python.txt |
Q:
Why does my code do not count last string? (Python)
I need to count non-unique sequences going sequentially. For example: "aabcccjaaa" is "21313". But my code do not count the last string. In checks, it goes to the last "else" and must add the last "a" as a unit to the result. What could be the problem? And maybe ... | Why does my code do not count last string? (Python) | I need to count non-unique sequences going sequentially. For example: "aabcccjaaa" is "21313". But my code do not count the last string. In checks, it goes to the last "else" and must add the last "a" as a unit to the result. What could be the problem? And maybe someone knows a solution instead of mine using standard l... | [
"Your code appends a number to d when the character is different from the previous one. It adds the number associated with the run of previous characters. So the last run never gets added, because there is no character after the last number.\nA simple fix would be to add\nif b != '':\n d.append(c)\n\n... after t... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074327559_python.txt |
Q:
Convert sql query to SQLALCHEMY. Problem in "as" keyword in "join" query
I want to convert this sql query to SQLALCHEMY:
SELECT * FROM dbcloud.client_feedback as a
join (select distinct(max(submitted_on)) sub,pb_channel_id pb, mail_thread_id mail from client_feedback group by pb_channel_id, mail_thread_id) as b
wh... | Convert sql query to SQLALCHEMY. Problem in "as" keyword in "join" query | I want to convert this sql query to SQLALCHEMY:
SELECT * FROM dbcloud.client_feedback as a
join (select distinct(max(submitted_on)) sub,pb_channel_id pb, mail_thread_id mail from client_feedback group by pb_channel_id, mail_thread_id) as b
where (a.submitted_on = b.sub and a.pb_channel_id = b.pb) or ( a.submitted_on = ... | [
"I think that what you may be looking for is .label(name).\nAssuming you have a model\nclass MyModel(db.Model):\n id = db.Column(primary_key=True)\n name = db.Column()\n\nhere is an example of how .label(name) can be used\n query = db.session.query(MyModel.name.label('a'))\n\nwill produce the SQL\n SELECT my_... | [
0
] | [] | [] | [
"flask_sqlalchemy",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0074318931_flask_sqlalchemy_mysql_python_sqlalchemy.txt |
Q:
Python Requests library redirect new url
I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve.
In my script I am setting allow_redirects=True.
I would like to know if the page has been redirected to something else, what is the new URL.
For ... | Python Requests library redirect new url | I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve.
In my script I am setting allow_redirects=True.
I would like to know if the page has been redirected to something else, what is the new URL.
For example, if the start URL was: www.google.com/... | [
"You are looking for the request history.\nThe response.history attribute is a list of responses that led to the final URL, which can be found in response.url.\nresponse = requests.get(someurl)\nif response.history:\n print(\"Request was redirected\")\n for resp in response.history:\n print(resp.status... | [
207,
91,
47,
46,
13,
1,
0,
0
] | [] | [] | [
"http",
"python",
"python_requests",
"redirect"
] | stackoverflow_0020475552_http_python_python_requests_redirect.txt |
Q:
C++ Boost + Python: undefined reference to Py_Dealloc
I'm trying to use the Python module on Boost. However, I'm getting an error that I cannot find what to do with.
It seems a missing switch or something, but I really could not find...
Does anyone have a clue?
Thanks!!!
/usr/include/python3.8/object.h|478|undefin... | C++ Boost + Python: undefined reference to Py_Dealloc | I'm trying to use the Python module on Boost. However, I'm getting an error that I cannot find what to do with.
It seems a missing switch or something, but I really could not find...
Does anyone have a clue?
Thanks!!!
/usr/include/python3.8/object.h|478|undefined reference to `_Py_Dealloc'|
System data:
Using Code::bl... | [
"This is kinda old, but try adding\n$(python3.10-config --ldflags --embed)\n\nto the commands at the linking phase.\nYour link command becomes something like\ng++ -L/usr/lib/x86_64-linux-gnu/ -o bin/Debug/PyOPI obj/Debug/bark.o obj/Debug/main.o -lboost_program_options -lboost_system -lboost_python38\n$(python3.10-... | [
0
] | [] | [] | [
"boost",
"c++",
"linux",
"python"
] | stackoverflow_0069980953_boost_c++_linux_python.txt |
Q:
Send Scapy serialized packets via JSON (api call)
I am struggling with serializing packets from scapy so I can send as JSON objects via an api call.
Right now, my api call looks like so:
def load_points(packet_list, permanent):
print("loading points")
waypoint_url = ''
if(permanent):
waypoint_... | Send Scapy serialized packets via JSON (api call) | I am struggling with serializing packets from scapy so I can send as JSON objects via an api call.
Right now, my api call looks like so:
def load_points(packet_list, permanent):
print("loading points")
waypoint_url = ''
if(permanent):
waypoint_url = "/add_permanent_points_packets"
else:
... | [
"Simply append the packet to the packet list as follows:\npacket_list.append(f\"{packet}\")\n\n"
] | [
2
] | [] | [] | [
"json",
"packet_sniffers",
"python"
] | stackoverflow_0074289718_json_packet_sniffers_python.txt |
Q:
Python print only .jpg url's from json
How can I print only .jpg/.png urls from API using json?
`
import requests
import json
r = requests.get("https://random.dog/woof.json")
print("Kod:", r.status_code)
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
jprint(r.json())
`
Re... | Python print only .jpg url's from json | How can I print only .jpg/.png urls from API using json?
`
import requests
import json
r = requests.get("https://random.dog/woof.json")
print("Kod:", r.status_code)
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
jprint(r.json())
`
Results:
`
{
"fileSizeBytes": 78208,
"... | [
"This example will use str.endswith to check, if dictionary value under the key url contains the string .jpg or .png.\nI'm doing 10 requests and using time.sleep to wait 1 second between each request:\nimport requests\nfrom time import sleep\n\nurl = \"https://random.dog/woof.json\"\n\nfor i in range(10):\n prin... | [
1,
1,
1
] | [] | [] | [
"image",
"json",
"python",
"python_requests"
] | stackoverflow_0074327206_image_json_python_python_requests.txt |
Q:
Combine different length of groupby data into Dataframe and how to solve IndexError: list index out of range?
I would like to restructure groupby data into dataframe.
Because the table has different length of groupbyed data, when I iterate those groupbyed data, IndexError: list index out of range comes up and I do... | Combine different length of groupby data into Dataframe and how to solve IndexError: list index out of range? | I would like to restructure groupby data into dataframe.
Because the table has different length of groupbyed data, when I iterate those groupbyed data, IndexError: list index out of range comes up and I do not know how to ignore this index error.
Background of my data.
I groupbyed by "Worker_id" and "Project_id"
... | [
"Here is what I have so far. As I said in the comments, there are more rows than in your desired output, but I don't know on what conditions I should join them.\n# restructure the df with `pivot_table`\nm1 = df.groupby('Project_ID').cumcount() + 1\nm2 = pd.factorize(df['Worker_ID'])[0] + 1\nout = (\n df\n .pi... | [
0
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074313413_dataframe_group_by_pandas_python.txt |
Q:
Python: get start and finish time of subprocess
I am running many subprocesses from python flask server via subprocess.Popen() and am saving reference to each one into dictionary. Server is not waiting until subprocess finishes.
After some time (5sec, 5min, etc) I try to verify if subprocess finished - via .poll()... | Python: get start and finish time of subprocess | I am running many subprocesses from python flask server via subprocess.Popen() and am saving reference to each one into dictionary. Server is not waiting until subprocess finishes.
After some time (5sec, 5min, etc) I try to verify if subprocess finished - via .poll() function.
Everything works as expected but now I nee... | [
"You can use os.wait() to wait for any child process that created by your process\nos.wait() described as following in the doc\n\nWait for completion of a child process, and return a tuple containing\nits pid and exit status indication: a 16-bit number, whose low byte is\nthe signal number that killed the process, ... | [
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0074304072_python_subprocess.txt |
Q:
how to convert a string of numbers to a list and square up ** and get it printed out back as string
Given a string of the form "3,9,13,4,42". It is necessary to convert it into a list and calculate its square for each element. Then join the squares of those elements back into a string and print it in the console.
... | how to convert a string of numbers to a list and square up ** and get it printed out back as string | Given a string of the form "3,9,13,4,42". It is necessary to convert it into a list and calculate its square for each element. Then join the squares of those elements back into a string and print it in the console.
input
input:
string = "3,9,13,4,42"
output:
string= "9,81,169,16,1764"
Managed to get it squared up, trie... | [
"Hope this answers your question.\n# input\nstr_numbers = \"3,9,13,4,42\"\n\n# string to list\nstr_number_list = str_numbers.split(\",\")\n\n# list of strings to list of ints\nnumber_list = [int(x) for x in str_number_list]\n\n# square all numbers\nsquared_numbers = [x ** 2 for x in number_list]\n\n# squared number... | [
1,
0,
0,
0,
0
] | [] | [] | [
"list",
"python",
"square",
"string",
"tuples"
] | stackoverflow_0074327620_list_python_square_string_tuples.txt |
Q:
Type Error in Sympy Piecwise Python: cannot determine truth value of Relational
i try to create linear function in an interval and the other interval is 0. and add it to an array
so i tried this code
import numpy as np
import sympy as sp
import matplotlib as plt # This is all the library's i need
import mpmath
x ... | Type Error in Sympy Piecwise Python: cannot determine truth value of Relational | i try to create linear function in an interval and the other interval is 0. and add it to an array
so i tried this code
import numpy as np
import sympy as sp
import matplotlib as plt # This is all the library's i need
import mpmath
x = sp.symbols('x')
n = 10
xx = (np.array([np.linspace(0, 1, n+1)]))
i = 0
N = []
N[0] ... | [
"I believe that's a bug.\nYou can work around it by first converting your numerical value to a Float, like this:\nsp.Piecewise(\n ((xx[0, i + 1] - x) / (xx[0, i + 1] - xx[0, i]), sp.Float(xx[0, i]) <= x),\n ((xx[0, i + 1] - x) / (xx[0, i + 1] - xx[0, i]), x <= xx[0, i + 1]),\n (0, True)\n)\n\n",
"This is... | [
0,
0
] | [] | [] | [
"piecewise",
"python",
"sympy",
"typeerror"
] | stackoverflow_0074326008_piecewise_python_sympy_typeerror.txt |
Q:
SQL Alchemy - Flask - Many to One
sorry for such a basic question but i cant get it straight.
I have a many to one relationship with Users can have 1 specific role. That should be enough for my purpose.
I created the models als following:
class User(UserMixin, db.Model):
__tablename__="users"
id = db.Colu... | SQL Alchemy - Flask - Many to One | sorry for such a basic question but i cant get it straight.
I have a many to one relationship with Users can have 1 specific role. That should be enough for my purpose.
I created the models als following:
class User(UserMixin, db.Model):
__tablename__="users"
id = db.Column(db.Integer, primary_key=True)
us... | [
"Since the User only has one role (it is many to one, many users have one role), role is not a list so you don't append to it. You just need to say User.role = role.\nFor example code in the question staff_user.role = role.\n"
] | [
0
] | [] | [] | [
"flask_sqlalchemy",
"python"
] | stackoverflow_0074107398_flask_sqlalchemy_python.txt |
Q:
Sympy dot product does not read dimensions correctly
I want to multiply two matrices in sympy. However, the .dot() function does not seem to work properly, as when using the transpose matrix so that the dimensions match, the same error appears as when not using it.
Code to reproduce:
from sympy import *
x1, x2, x3... | Sympy dot product does not read dimensions correctly | I want to multiply two matrices in sympy. However, the .dot() function does not seem to work properly, as when using the transpose matrix so that the dimensions match, the same error appears as when not using it.
Code to reproduce:
from sympy import *
x1, x2, x3 = symbols('x1 x2 x3')
x = Matrix([x1, x2, x3])
m = Matri... | [
"this seems like a bug in sympy, but using dot is already deprecated, use the @ operator for matrix dot product and it will work\nresult = xmt @ c\n\nyou could post an issue on sympy's github about dot, but you shouldn't be using it anyway, as it is deprecated.\nEdit: according to @hpaulj the correct function to ca... | [
3
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074327683_python_sympy.txt |
Q:
Check if two lists in list have common elements. Connect them if so, without duplicates
I am stuck on how to solve this problem.
Given a set of lists in a list, if any two sets of lists contain a common element, the two lists would be combined into one.
Suppose I have a set of lists in a list [[0, 1], [3, 6], [3, ... | Check if two lists in list have common elements. Connect them if so, without duplicates | I am stuck on how to solve this problem.
Given a set of lists in a list, if any two sets of lists contain a common element, the two lists would be combined into one.
Suppose I have a set of lists in a list [[0, 1], [3, 6], [3, 9]]. Notice that [3, 6] and [3, 9] have a common element 3, so they are combined into [3, 6, ... | [
"Challenging! This is my approach:\ndef combine_commons(input: list) -> list:\n combine_found = False\n for ct_current, item_current in enumerate(input):\n \n # try to find a element that shares item:\n combine_into = None\n for ct_search, item_search in enumerate(input):\n ... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074327140_python.txt |
Q:
How to sort multiple columns under new columns based on row values from another column within the same dataframe pandas?
This is my dataset:
Name
India
Japan
USA
France
Italy
Continent
Foo
1
1
0
0
0
Asia
Baz
0
0
1
0
0
N.America
Bob
0
0
0
1
1
Europe
How I want the result to look like:
| | Asia | N. A... | How to sort multiple columns under new columns based on row values from another column within the same dataframe pandas? | This is my dataset:
Name
India
Japan
USA
France
Italy
Continent
Foo
1
1
0
0
0
Asia
Baz
0
0
1
0
0
N.America
Bob
0
0
0
1
1
Europe
How I want the result to look like:
| | Asia | N. America | Europe |
| Name |India|Japan| USA | France | Italy |
|------|-----|-----|------------|-----... | [
"One option with stack/unstack:\n(df.set_index(['Name', 'Continent'])\n .replace({0: np.nan}).stack()\n .unstack(['Continent', -1], fill_value=0)\n .convert_dtypes()\n)\n\nAnother with pivot_table:\n(df.pivot_table(index='Name', columns='Continent', fill_value=0)\n .loc(axis=1)[lambda d: d.eq(1).any()]\n)\n... | [
0
] | [] | [] | [
"merge",
"multiple_columns",
"pandas",
"python",
"sorting"
] | stackoverflow_0074327785_merge_multiple_columns_pandas_python_sorting.txt |
Q:
how to print two txt files line by line in python using for loop
My codes are listed as following:
import time
f = open("q1", "r")
g = open("q2", "r")
f1 = (f)
f2 =(g)
for y in f1:
for x in f2:
print(y)
sleep(1)
print(x)
The output does not print line by line,but prints the whole file. How to prin... | how to print two txt files line by line in python using for loop | My codes are listed as following:
import time
f = open("q1", "r")
g = open("q2", "r")
f1 = (f)
f2 =(g)
for y in f1:
for x in f2:
print(y)
sleep(1)
print(x)
The output does not print line by line,but prints the whole file. How to print both files line by line?
output
1
2
3
4
5
a
b
c
d
e
desired outpu... | [
"You meant to iterate through both files at the same time which is what zip() gives you:\nfor y,x in zip(f1, f2):\n print(y)\n print(x)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074327778_python.txt |
Q:
How to get the indices of at least two consecutive values that are all greater than a threshold?
For example, let's consider the following numpy array:
[1, 5, 0, 5, 4, 6, 1, -1, 5, 10]
Also, let's suppose that the threshold is equal to 3.
That is to say that we are looking for sequences of at least two consecutiv... | How to get the indices of at least two consecutive values that are all greater than a threshold? | For example, let's consider the following numpy array:
[1, 5, 0, 5, 4, 6, 1, -1, 5, 10]
Also, let's suppose that the threshold is equal to 3.
That is to say that we are looking for sequences of at least two consecutive values that are all above the threshold.
The output would be the indices of those values, which in o... | [
"If you convolve a boolean array with a window full of 1 of size win_size ([1] * win_size), then you will obtain an array where there is the value win_size where the condition held for win_size items:\nimport numpy as np\n\ndef groups(arr, *, threshold, win_size, merge_contiguous=False, flat=False):\n conv = np.... | [
2,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074301529_numpy_python.txt |
Q:
How to prevent NaN in the decision scores of Angle-based Outlier Detector in PyOd
I am getting the nan values as decision scores when using Angle-based Outlier Detector because of which the outliers are not detected.
from pyod.models.abod import ABOD
from sklearn.preprocessing import MinMaxScaler
def outlier_ABOD... | How to prevent NaN in the decision scores of Angle-based Outlier Detector in PyOd | I am getting the nan values as decision scores when using Angle-based Outlier Detector because of which the outliers are not detected.
from pyod.models.abod import ABOD
from sklearn.preprocessing import MinMaxScaler
def outlier_ABOD(data, outliers_fraction=0.1):
data = np.array([data]).reshape(-1, 1)
scaler =... | [
"For some reason, I do not feel ABOD works in your case as all the scores are NaN or zeors (close to 0). I feel there are some other issues rather than NaN. Have you tried other models as well, e.g., Isolation Forest?\nSorry, I do not have enough points to post a comment.\n",
"I reproduce the same result in my co... | [
1,
0,
0
] | [] | [] | [
"anomaly_detection",
"data_science",
"outliers",
"python"
] | stackoverflow_0056017469_anomaly_detection_data_science_outliers_python.txt |
Q:
How to send a message and an embed when streamer is live? | Error | Discord.py
I have written the code to check if Twitch streamer is life, if so send a message, but i can't find a way to check if life notification(message and embed) is already send. So I tried different things of checking embed title: if discord.... | How to send a message and an embed when streamer is live? | Error | Discord.py | I have written the code to check if Twitch streamer is life, if so send a message, but i can't find a way to check if life notification(message and embed) is already send. So I tried different things of checking embed title: if discord.Embed(title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch! \n \n {... | [
"await ctx.send(content = \"some message\", embed = embed)\n\n\nIt was a very stupid question at the time, and it still is to this day\n\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"json",
"python",
"twitch"
] | stackoverflow_0067812183_discord_discord.py_json_python_twitch.txt |
Q:
Find the missing month in given date range then add that missing date in the data with same records as given in the last date
I have a Statement of accounts, where i have Unique ID, Disbursed date, payment date and the balance amount.
Date range for below data = Disbursed date to May-2022
Example of date:
Unique ... | Find the missing month in given date range then add that missing date in the data with same records as given in the last date | I have a Statement of accounts, where i have Unique ID, Disbursed date, payment date and the balance amount.
Date range for below data = Disbursed date to May-2022
Example of date:
Unique Disbursed date payment date balance amount
123 2022-Jan-13 2022-Jan-27 10,000
123 2022-Jan-13 ... | [
"You can use:\n# generate needed month ends\nidx = pd.date_range('2022-01', '2022-06', freq='M')\n\nout = (df\n # compute the month end for existing data\n .assign(month_end=pd.to_datetime(df['payment date'])\n .sub(pd.Timedelta('1d'))\n .add(pd.offsets.MonthEnd()))\n... | [
0
] | [] | [] | [
"dataframe",
"date",
"numpy",
"python",
"range"
] | stackoverflow_0074327690_dataframe_date_numpy_python_range.txt |
Q:
Game Not Functioning Properly
So i tried making a rock paper scissors game but some if statements are not working. code was written in python.
Is there something preventing the if statements ffrom running? or s there another problem
I tried a bunch of little changes but none of them work
code:
import random
moves... | Game Not Functioning Properly | So i tried making a rock paper scissors game but some if statements are not working. code was written in python.
Is there something preventing the if statements ffrom running? or s there another problem
I tried a bunch of little changes but none of them work
code:
import random
moves = ('rock', 'paper', 'scissors')
wh... | [
"Here's my solution to this. I cleaned up the amount of if-else statements in your code as well with a variable outcome_map. I also removed a lot of the typing rarities that come with inputs by introducing your choice to be \"(1, 2, or 3)\":\nimport random\n\nmoves = ('rock', 'paper', 'scissors')\nwhile True:\n ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074327654_python.txt |
Q:
Creating a 2D NumPy array from a binaryfile where the total length is unkown
I'm having trouble with creating a NumPy array from a binary file.
The binary file is made up by many c_int32 containing samples from multiple microphones. The data is written the the file in order starting with:
frequency + sampleCount... | Creating a 2D NumPy array from a binaryfile where the total length is unkown | I'm having trouble with creating a NumPy array from a binary file.
The binary file is made up by many c_int32 containing samples from multiple microphones. The data is written the the file in order starting with:
frequency + sampleCounter + mic1 + mic2 + mic3 + mic4
I sample data for about 2 seconds, so I have a quit... | [
"You can read the complete file with fromfile:\ndata = numpy.fromfile(filename, dtype=numpy.int32)\n\nThis should give you n*6 values. Then just reshape the array:\ndata = data.reshape(-1, 6)\n\n"
] | [
1
] | [] | [] | [
"binaryfiles",
"file",
"numpy",
"python",
"text_files"
] | stackoverflow_0074327377_binaryfiles_file_numpy_python_text_files.txt |
Q:
'Foo' object has no attribute 'myList'
class Foo:
def __init__(self, mylist):
self.mylist =mylist
def myIter(self):
for i in self.myList:
print(i)
first = [1,2,4,3,5,6]
f = Foo(first)
f.myIter()
I am trying to pass List as a parameter to the object of... | 'Foo' object has no attribute 'myList' | class Foo:
def __init__(self, mylist):
self.mylist =mylist
def myIter(self):
for i in self.myList:
print(i)
first = [1,2,4,3,5,6]
f = Foo(first)
f.myIter()
I am trying to pass List as a parameter to the object of the class .
| [
"Best practice is to always use snake_case for functions and variables alike (because remember, in python, functions are variables), and CamelCase for classes.\nSticking to that code of conduct will help you avoid this kind of typo (at least it helped me a lot)\nIn your case, your variable mylist is lowercase but y... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074327800_python.txt |
Q:
lxml is not installing in pycharm ide
lxml not installing in pycharm ide.
this code is not running due to lxml is not installed. How to install lxml package in pycharm
page = urlopen(wiki)
soup = BeautifulSoup(page, 'lxml')
print(soup.title)
[Erro while edding lxml code in pycharm][1]
A:
To install a new pack... | lxml is not installing in pycharm ide | lxml not installing in pycharm ide.
this code is not running due to lxml is not installed. How to install lxml package in pycharm
page = urlopen(wiki)
soup = BeautifulSoup(page, 'lxml')
print(soup.title)
[Erro while edding lxml code in pycharm][1]
| [
"To install a new package directly in PyCharm, you can go to \nSettings->Project->Project Interpreter.\nAfter this you should see the interpreter that PyCharm uses to run your project.\nIf you don't see lxml in the package's table, you can press the plus icon in the right corner of the window and type lxml and proc... | [
6,
0
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0040542032_pycharm_python.txt |
Q:
How to access variables and methods from QMainWindow Class in a QWidget Class - Python PyQt5
I'm building a media player with PyQt5 in python and I want to access variables from my QMainWindow class. Currently I have two classes - one is the main window (QMainWindow) and the other is a QWidget Window so called my ... | How to access variables and methods from QMainWindow Class in a QWidget Class - Python PyQt5 | I'm building a media player with PyQt5 in python and I want to access variables from my QMainWindow class. Currently I have two classes - one is the main window (QMainWindow) and the other is a QWidget Window so called my export manager.
Some basic code of my structure
class MainWindow(QMainWindow):
def __init__(s... | [
"It's a point about Object-Oriented Programming more than about GUI.\nYou could keep track of the filename1 variable by making it a member of the MainWindow class.\nIn MainWindow.init() you could add :\n self.chosen_filename: str = None\n\nThen you assign it at the end of the MainWindow.OpenVideo() method\n s... | [
0
] | [] | [] | [
"class",
"pyqt",
"pyqt5",
"python",
"user_interface"
] | stackoverflow_0074327910_class_pyqt_pyqt5_python_user_interface.txt |
Q:
How do I keep Score in Python?
enter image description hereI don't know how to make python keep score in a game, I saw that I should put score = 0 at the top of code and then after the if statement put score +1 but it comes out blank whenever I run the code:
I tried score +1 and score+=1 after the if statement but... | How do I keep Score in Python? | enter image description hereI don't know how to make python keep score in a game, I saw that I should put score = 0 at the top of code and then after the if statement put score +1 but it comes out blank whenever I run the code:
I tried score +1 and score+=1 after the if statement but when I run it keeps coming out as b... | [
" score = 0\n player_input = input(\"Enter the capital of Greece: \").capitalize()\n if player_input == \"Athens\":\n score += 1\n print(score)\n\n # I hope this helps\n\nEDIT: Your use of .upper() will change a string like \"text\" into \"TEXT\". Instead I used .capitalize() which changes a s... | [
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074327961_if_statement_python.txt |
Q:
How to change the image size for seaborn.objects
The solutions shown in How to change the figure size of a seaborn axes or figure level plot do not work for seaborn.objects. This question is about the new interface added in seaborn v0.12.
Tried different ways to set the plotted image size but no one worked, below ... | How to change the image size for seaborn.objects | The solutions shown in How to change the figure size of a seaborn axes or figure level plot do not work for seaborn.objects. This question is about the new interface added in seaborn v0.12.
Tried different ways to set the plotted image size but no one worked, below is the code, how to set the below image height and wid... | [
"With Plot.layout:\n(\n so.Plot(data=d, x=\"point_x\", y=\"point_y\")\n .add(so.Dot())\n .layout(size=(w, h)) # in inches * (dpi / 100)\n .save(\"output.png\", dpi=dpi) # e.g. dpi=100\n .show()\n)\n\n"
] | [
3
] | [] | [] | [
"python",
"seaborn",
"seaborn_0.12.x"
] | stackoverflow_0074326894_python_seaborn_seaborn_0.12.x.txt |
Q:
AWS Lambda error for connectorx library: No module named 'connectorx.connectorx
I'm new to AWS Lambda service and I'm trying to upload a Python code that uses the "connectorx" library.
I'm aware that I need to create a layer to use an external library or uploading the library files inside a zip folder inside the l... | AWS Lambda error for connectorx library: No module named 'connectorx.connectorx | I'm new to AWS Lambda service and I'm trying to upload a Python code that uses the "connectorx" library.
I'm aware that I need to create a layer to use an external library or uploading the library files inside a zip folder inside the lambda function. I tried both, but I'm still getting the same error:
"errorMessage": "... | [
"I think the issue is due to incorrect zipping.\nFollow the below steps exactly\n\ncreate your lambda function file\ninstall connectorx as shown below\n\npip install --target ./package connectorx\n\n\ncopy your lambda function file to package directory\nNow run below commands to create the deployment package zip.\n... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"python"
] | stackoverflow_0074327495_amazon_web_services_aws_lambda_python.txt |
Q:
Type of `@cached_property` is not correctly recognised by pylint
For me, pylint is giving back an error E1133 (not-an-iterable) for a @cached_property that actually is an iterable. Wondering if this is a bug in pylint or something can be done from my side to prevent this error from popping up.
Functionally the cod... | Type of `@cached_property` is not correctly recognised by pylint | For me, pylint is giving back an error E1133 (not-an-iterable) for a @cached_property that actually is an iterable. Wondering if this is a bug in pylint or something can be done from my side to prevent this error from popping up.
Functionally the code runs without a problem. Meaning I'm able to iterate over this identi... | [] | [] | [
"The not-an-iterable message may be emitted if cached_property is not installed in your environment; I have reproduced this & the message is no longer emitted after installing it with pip install cached_property.\nTested using the following Pylint version:\npylint --version\npylint 2.15.5\nastroid 2.12.12\nPython 3... | [
-2
] | [
"pylint",
"python"
] | stackoverflow_0074275044_pylint_python.txt |
Q:
Django django.urls.exceptions.NoReverseMatch: Reverse for ' new_topic' not found. ' new_topic' is not a valid view function or pattern name
I'm trying to build a topics section, in where you can create a new topic. This exercise is from the python crash course book.
The error I see is the next one:
django.urls.exc... | Django django.urls.exceptions.NoReverseMatch: Reverse for ' new_topic' not found. ' new_topic' is not a valid view function or pattern name | I'm trying to build a topics section, in where you can create a new topic. This exercise is from the python crash course book.
The error I see is the next one:
django.urls.exceptions.NoReverseMatch: Reverse for ' new_topic' not found. ' new_topic' is not a valid view function or pattern name.
views.py
from django.shor... | [
"I believe the issue is in this line:\n< form action =\"{% url 'learning_logs: new_topic' %}\"\n\nThere's a space before new_topic, and it's looking for a url that includes that space. I believe if you remove that space your project will work.\n",
"**Go to your new_topic.html then change the form action wtih stpp... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0064917223_django_python.txt |
Q:
Lowercase the first letter of the first word of each sentence in a paragraph
How to lowercase the first letter of the first word of each sentence in a paragraph? Also, nouns in the middle of sentences will remain capitalized.
How can I do that in Python?
For example: "This is a example sentence. Please help me. I ... | Lowercase the first letter of the first word of each sentence in a paragraph | How to lowercase the first letter of the first word of each sentence in a paragraph? Also, nouns in the middle of sentences will remain capitalized.
How can I do that in Python?
For example: "This is a example sentence. Please help me. I don't want this situation. In Berlin we have a great time." to "this is a example ... | [
"I would use a regex for this:\nimport re\n\ns = \"This is a example sentence. Please help me. I don't want this situation. In Berlin we have a great time.\"\n\nout = re.sub(r'((?:^|\\.)\\s*\\w+)', lambda m: m.group().lower(), s)\n\noutput: \"this is a example sentence. please help me. i don't want this situation. ... | [
3,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074328018_python_string.txt |
Q:
Standardization between float and None types
I have converted the code from Pine Script to Python, but I am facing some problems. I'm not good in Python.
import pandas as pd
import pandas_ta as ta
close = pd.read_csv('close-MATIC.csv')
def Z_4(src, length, smooth):
mean = ta.sma(src, length)
vlo = src - ... | Standardization between float and None types | I have converted the code from Pine Script to Python, but I am facing some problems. I'm not good in Python.
import pandas as pd
import pandas_ta as ta
close = pd.read_csv('close-MATIC.csv')
def Z_4(src, length, smooth):
mean = ta.sma(src, length)
vlo = src - mean
std = ta.stdev(vlo, length)
value = (... | [
"Here is your code fixed, but I'm not sure if the results are valid though:\nimport pandas as pd\nimport pandas_ta as ta\n\n\ndef Z_4(src, length, smooth):\n mean = ta.sma(src, length)\n vlo = src - mean\n std = ta.stdev(vlo, length)\n value = vlo / std\n Wema = ta.ema(\n ta.ema(value, smooth)... | [
0
] | [] | [] | [
"function",
"pine_script",
"python",
"ta_lib",
"tradingview_api"
] | stackoverflow_0074327390_function_pine_script_python_ta_lib_tradingview_api.txt |
Q:
How to solve 'invalid locator' problem during "click a button problem" in Python Selenium?
I have a button that html is below
I tired the following code
Execute_Button = driver.find_element("xPath",'//button[text()="Execute "]')
But Python comes up with this error message. How to solve?
InvalidArgumentException:... | How to solve 'invalid locator' problem during "click a button problem" in Python Selenium? | I have a button that html is below
I tired the following code
Execute_Button = driver.find_element("xPath",'//button[text()="Execute "]')
But Python comes up with this error message. How to solve?
InvalidArgumentException: Message: invalid argument: invalid locator
| [
"According to docs (locating elements), locating by xpath can be done using locator By.XPATH or 'xpath'. In your code you use 'xPath', which is invalid. To fix that simply change it to one of the two I mentioned, i.e.\nExecute_Button = driver.find_element(By.XPATH,'//button[text()=\"Execute \"]')\n\n",
"browser.f... | [
1,
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074327880_python_selenium.txt |
Q:
Understanding time/space complexity for Leetcode 1366
I've solved leetcode 1366 but having some trouble approximating the proper time/space complexity. I've looked at the solutions tab but answers vary and I'm not sure if I buy some of them. Here is my code and the general algorithm -
class Solution:
def rankT... | Understanding time/space complexity for Leetcode 1366 | I've solved leetcode 1366 but having some trouble approximating the proper time/space complexity. I've looked at the solutions tab but answers vary and I'm not sure if I buy some of them. Here is my code and the general algorithm -
class Solution:
def rankTeams(self, votes: List[str]) -> str:
rankings ... | [
"When you determine the asymptotic complexity of the time or space used by actual code, you decide which values to treat as variables or as constants. In this case if you make this determination based on constraints of the leetcode problem\n1 <= votes.length <= 1000\n1 <= votes[i].length <= 26\n\nthen the possible ... | [
1
] | [] | [] | [
"algorithm",
"data_structures",
"python",
"sorting",
"time_complexity"
] | stackoverflow_0074324641_algorithm_data_structures_python_sorting_time_complexity.txt |
Q:
I cant use the objects attribute in django project
I created a Projects model
class Projects(models.Model):
name = models.CharField(max_length=257, unique=True, null=False)
description = models.TextField()
active_issue_count = models.IntegerField(default=0) # functiona bağlanmalı
solved_issue_count = models.Integ... | I cant use the objects attribute in django project | I created a Projects model
class Projects(models.Model):
name = models.CharField(max_length=257, unique=True, null=False)
description = models.TextField()
active_issue_count = models.IntegerField(default=0) # functiona bağlanmalı
solved_issue_count = models.IntegerField(default=0) # functiona bağlanmalı
is_active = m... | [
"PyCharm just don't follow some object's relation. Here it has no clue that this Model class has related Manager, that you can call with objects.\nYou can ignore it in PyCharm so it will not bother you.\nMore actions... => Ignore (...)\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0074328121_django_django_models_python.txt |
Q:
I want to make multiple list of coordinates from a single list of coordinates with can make a close loop
input_list = [(2282.405, -89.9415, 266.1414), (2276.534, -89.9526, 266.9091), (2276.534, -83.9573, 266.9091), (2282.405, -83.9464, 266.1414), (2288.276, -77.9407, 265.3738), (2294.148, -77.9301, 264.6062), (229... | I want to make multiple list of coordinates from a single list of coordinates with can make a close loop | input_list = [(2282.405, -89.9415, 266.1414), (2276.534, -89.9526, 266.9091), (2276.534, -83.9573, 266.9091), (2282.405, -83.9464, 266.1414), (2288.276, -77.9407, 265.3738), (2294.148, -77.9301, 264.6062), (2294.148, -83.9247, 264.6062), (2288.276, -83.9356, 265.3738), (2282.405, -71.9563, 266.1414), (2288.276, -71.945... | [
"Requiring to get \"counterclockwise\" answer, in a 3d assignment is tricky. A leaf has 2 sides, but I can imagine that the actual requirement is to always loop on the same order, and that if an edge is counted once \"a to b\", it will be counted \"b to a\" the next time.\nAlso your example look planar and \"grid l... | [
1
] | [] | [] | [
"point_clouds",
"python"
] | stackoverflow_0074327545_point_clouds_python.txt |
Q:
How to insert values to ListBox in the same as set order
All I want is insert to listbox items in the same order as in the set. I want it to be inserted like: 'damp'->'camp'->'came' and so on. How can I do that?
gui_dict = tk.Listbox(third_task_window, width=10, height=10)
words = {'damp', 'camp', 'came', ... | How to insert values to ListBox in the same as set order | All I want is insert to listbox items in the same order as in the set. I want it to be inserted like: 'damp'->'camp'->'came' and so on. How can I do that?
gui_dict = tk.Listbox(third_task_window, width=10, height=10)
words = {'damp', 'camp', 'came', 'lame', 'lime', 'like',
'cold', 'card', 'cord', '... | [
"you are putting them in a set {}, which sorts based on hash on creation, put them in a list [] instead and they won't be sorted, they will be in the same order you put them in.\nimport tkinter as tk\n\nroot = tk.Tk()\ngui_dict = tk.Listbox(root, width=10, height=10)\nwords = ['damp', 'camp', 'came', 'lame', 'lime'... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074328266_python_tkinter.txt |
Q:
psycopg2.InterfaceError: connection already closed / pgr_astar
I am using psycopg2 to access a postgresql database from python. When I try to run the pgrouting function "pgr_astar" for the shortest path, I receive an error
cur = db.cursor()
psycopg2.InterfaceError: connection already closed
Basically, what happen... | psycopg2.InterfaceError: connection already closed / pgr_astar | I am using psycopg2 to access a postgresql database from python. When I try to run the pgrouting function "pgr_astar" for the shortest path, I receive an error
cur = db.cursor()
psycopg2.InterfaceError: connection already closed
Basically, what happened is: when pgr_astar does not find a path between two points, it cr... | [
"I assume you can check your connection status in python (I don't use python) so you can recover and do something sensible, like reconnect. You might need to sleep for a couple of seconds to let the database recover from the crash before you reconnect.\nRegarding the pgrouting issue, I would like to see a simple te... | [
3,
0
] | [] | [] | [
"a_star",
"pgrouting",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0020217571_a_star_pgrouting_postgresql_psycopg2_python.txt |
Q:
Using OrdinalEncoder to transform categorical values
I have a dataset that has many columns
No Name Sex Blood Grade Height Study
1 Tom M O 56 160 Math
2 Harry M A 76 192 Math
3 John M A 45 178 English
4 Nancy F B 78 157 Biology
5 Mi... | Using OrdinalEncoder to transform categorical values | I have a dataset that has many columns
No Name Sex Blood Grade Height Study
1 Tom M O 56 160 Math
2 Harry M A 76 192 Math
3 John M A 45 178 English
4 Nancy F B 78 157 Biology
5 Mike M O 79 167 Math
6 Kate F AB ... | [
"You were almost there !\nBasically the fit method, prepare the encoder (fit on your data i.e. prepare the mapping) but don't transform the data.\nYou have to call transform to transform the data , or use fit_transform which fit and transform the same data.\nenc = OrdinalEncoder()\nenc.fit(df[[\"Sex\",\"Blood\", \"... | [
31,
23,
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0056502864_python_scikit_learn.txt |
Q:
Python PySimpleGui gives error when closing window with "X", when using "=timeout" and "window.update" in loop
When I use the =timeout argument, I cannot seem to make it work, that if I close the window with the X button, that I don't get a error.
Here is a code snippet from the web, where it was suggested to use
... | Python PySimpleGui gives error when closing window with "X", when using "=timeout" and "window.update" in loop | When I use the =timeout argument, I cannot seem to make it work, that if I close the window with the X button, that I don't get a error.
Here is a code snippet from the web, where it was suggested to use
if event == sg.WIN_CLOSED:
But as soon as I use the =timeout argument, AND window.update it fails.
from io import B... | [
"I just found the answer while making coffee.\nThe solution is to put the image update AFTER the event check!\nBecause after the timeout timer runs out, the first thing the code does, is to update the image, instead it should check if the window was closed...solved.\nShould I delete my question or let it stay for o... | [
1
] | [] | [] | [
"formclosing",
"pysimplegui",
"python"
] | stackoverflow_0074328267_formclosing_pysimplegui_python.txt |
Q:
Date filter in django
Filter dates that have not passed
class Distributor(models.Model):
expire_at = models.DateTimeField()
I want to get the data that has not expired
A:
from datetime import datetime
desired_query = Distributor.objects.filter(expire_at__gt=datetime.now())
The mentioned query in the above... | Date filter in django | Filter dates that have not passed
class Distributor(models.Model):
expire_at = models.DateTimeField()
I want to get the data that has not expired
| [
"from datetime import datetime\n\n\ndesired_query = Distributor.objects.filter(expire_at__gt=datetime.now())\n\nThe mentioned query in the above code snippet will return Distributor objects have not expired yet.\n",
"Here the query would look like if you want the data where expire_at is null\nDistributor.objects.... | [
1,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074328311_django_django_rest_framework_python.txt |
Q:
Python: How to validate an IP Address with a CIDR notation (import socket)
I've got a script which is using argparse to pull flags from the command line and using socket to validate an IP Address. So far it works if I'm just using the standard IPv4 X.X.X.X format. What I want to do is validate an IP Address that i... | Python: How to validate an IP Address with a CIDR notation (import socket) | I've got a script which is using argparse to pull flags from the command line and using socket to validate an IP Address. So far it works if I'm just using the standard IPv4 X.X.X.X format. What I want to do is validate an IP Address that includes a CIDR notation. How can I modify my bit of code to validate the 2-digit... | [
"Python 3\nThere is an ipaddress module that may do the job.\nThe constructor of the class Ip4Network handles both 255.255.255.255 and 255.255.255.255/32 (and also IPv6 format, with Ip6Network)\nSo you may add in your code\nimport ipaddress\n\nand create an Ip4Network with the code:\ntry:\n ip_addr = ipaddress.i... | [
5,
0
] | [] | [] | [
"python",
"sockets",
"validation"
] | stackoverflow_0045988215_python_sockets_validation.txt |
Q:
Setting the value of a class property via method
So, I have been trying to implement the following:
from abc import ABC
from abc import abstractmethod
class parent(ABC):
@property
@abstractmethod
def example_variable(self)->str:
...
@abstractmethod
def example_method(self)->in... | Setting the value of a class property via method | So, I have been trying to implement the following:
from abc import ABC
from abc import abstractmethod
class parent(ABC):
@property
@abstractmethod
def example_variable(self)->str:
...
@abstractmethod
def example_method(self)->int:
...
def __init__(self, foo: in... | [
"The 'self' argument is only recognized within a class method as it is passed as an argument to the method. (By default, the first argument of a Python class method is a pointer to the class) The example_variable in the above case is being defined outside the method, hence, using self.example_method() will be incor... | [
0,
0
] | [] | [] | [
"inheritance",
"instance_variables",
"oop",
"properties",
"python"
] | stackoverflow_0074328078_inheritance_instance_variables_oop_properties_python.txt |
Q:
Conection error (Caused by NewConnectionError) pipreqs
I tried to run a simple pipreqs to see all the packages in my code but this returned:
Traceback (most recent call last):
File "c:\users\gabri\pycharmprojects\pythonproject\venv\lib\site-packages\urllib3\connection.py", line 169, in _new_conn
conn = conne... | Conection error (Caused by NewConnectionError) pipreqs | I tried to run a simple pipreqs to see all the packages in my code but this returned:
Traceback (most recent call last):
File "c:\users\gabri\pycharmprojects\pythonproject\venv\lib\site-packages\urllib3\connection.py", line 169, in _new_conn
conn = connection.create_connection(
File "c:\users\gabri\pycharmproje... | [
"I just run ping google.com and use this part of return [000:0000:0000:000::0000] to run pip --proxy=[000:0000:0000:000::0000] install pipreqs and it works!\n\nI replace my real proxy number to [000:0000:0000:000::0000], in your pc you have to use your number =)\n\n",
"I got the same error while trying to run pip... | [
0,
0
] | [] | [] | [
"package",
"pip",
"python",
"python_3.x"
] | stackoverflow_0068302990_package_pip_python_python_3.x.txt |
Q:
TypeError: Labels in y_true and y_pred should be of the same type. Got y_true=['0' '1'] and y_pred=[0 1] in printing classification report
I try to fit some ML algorithems (SVM, Randome Forst etc). Also, I fit a xgboost model, and I get the 10 most important features already.
But when I print the classification re... | TypeError: Labels in y_true and y_pred should be of the same type. Got y_true=['0' '1'] and y_pred=[0 1] in printing classification report | I try to fit some ML algorithems (SVM, Randome Forst etc). Also, I fit a xgboost model, and I get the 10 most important features already.
But when I print the classification report by :
print(classification_report(y_test,y_predict))
I get:
TypeError: Labels in y_true and y_pred should be of the same type. Got
y_true=... | [
"Looks like your predictions and your outputs are of a different dtype, char and numeric - you can change the type of your numpy array like this:\ny_true = y_true.astype(y_pred.dtype)\n\n"
] | [
1
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn",
"xgboost"
] | stackoverflow_0074328249_machine_learning_python_scikit_learn_xgboost.txt |
Q:
Algorithm Question - How to know which taxi company is always better based on a fixed price and a price that varies with the km traveled
I'm trying to find a way to solve a problem, but not sure how to do it, here it is:
I need to make a function that will receive the taxi fare of two companies and the fare will b... | Algorithm Question - How to know which taxi company is always better based on a fixed price and a price that varies with the km traveled | I'm trying to find a way to solve a problem, but not sure how to do it, here it is:
I need to make a function that will receive the taxi fare of two companies and the fare will be a constant value and a value based on the kilometers traveled by the user, something like this:
company X:
final_value_X = fixed_X + (km_tra... | [
"The kilometers traveled is not necessary information to solve this problem.\nAlso, adding kilometers to the count is not feasible either, since taxi clocks don't jump up suddenly by the per-km fare once a new km is begun - rather, they increase incrementally, in small, pro-rated jumps (i.e. += 1 is not feasible).\... | [
0
] | [] | [] | [
"algorithm",
"compare",
"math",
"python"
] | stackoverflow_0074327978_algorithm_compare_math_python.txt |
Q:
Python CSV: (Master and Detail) Search and Insert Value From Detail File into Specific Column On Master File
I am new in Python actually ):
I have task regarding Python and CSV where I need to add value into specific column on Master file after getting data from Detail file.
Let see sample Master File, Detail File... | Python CSV: (Master and Detail) Search and Insert Value From Detail File into Specific Column On Master File | I am new in Python actually ):
I have task regarding Python and CSV where I need to add value into specific column on Master file after getting data from Detail file.
Let see sample Master File, Detail File and Output expected.
Master File:
Detail File:
Output Expected:
I have a few source-code to run it but not com... | [
"If you want to do this with basic Python you could try the following:\nimport csv\nfrom datetime import datetime as dt\n\nwith open(\"master.csv\", \"r\") as file:\n reader = csv.DictReader(file)\n fieldnames = reader.fieldnames\n master = {(row[\"Name\"], row[\"Key No\"]): row for row in reader}\n\ndef t... | [
0
] | [] | [] | [
"csv",
"pivot",
"python"
] | stackoverflow_0074191482_csv_pivot_python.txt |
Q:
printing shapes in one line in python
I am trying to print 2 circles pattern in one row and two in the next row like this
Here is my Code:
cell = {}
row = 5
col = 5
for i in range(0,row):
for j in range(0,col):
if((j == 0 or j == col-1) and (i!=0 and i!=row-1)) :
cell[(i,j)] = '*'
... | printing shapes in one line in python | I am trying to print 2 circles pattern in one row and two in the next row like this
Here is my Code:
cell = {}
row = 5
col = 5
for i in range(0,row):
for j in range(0,col):
if((j == 0 or j == col-1) and (i!=0 and i!=row-1)) :
cell[(i,j)] = '*'
#end='' so that print statement... | [
"You essentially need a template for top/bottom of a circle and the middle part of a circle.\nThen you need to print enough of them per line:\nnums = 7 # only squares supported\namount = 3 # shapes per line & shape rows in total\nspacer = 2 # space horizontally, vertically it is 1 line\n\n# prepare shapes\ntop_bo... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0070044102_python_python_3.x.txt |
Q:
How can I get href in this a tag?
I want to get the href (https://www.dcard.tw/forum/popular)
from https://www.dcard.tw/
this href is under <a href="/forum/popular">
my code:
from bs4 import BeautifulSoup
import requests
url = "https://www.dcard.tw/"
soup = BeautifulSoup(requests.get(url).text,'lxml')
for link in... | How can I get href in this a tag? | I want to get the href (https://www.dcard.tw/forum/popular)
from https://www.dcard.tw/
this href is under <a href="/forum/popular">
my code:
from bs4 import BeautifulSoup
import requests
url = "https://www.dcard.tw/"
soup = BeautifulSoup(requests.get(url).text,'lxml')
for link in soup.find_all('a'):
print(link.get... | [
"You can try the examples from this thread, they got some successful options.\nHow can I get href links from HTML using Python?\nRegards,\nAlex\n"
] | [
0
] | [] | [] | [
"atag",
"beautifulsoup",
"href",
"python",
"url"
] | stackoverflow_0074328539_atag_beautifulsoup_href_python_url.txt |
Q:
Selecting button in Selenium python using web driver
Can anyone please let me know how to correctly click on the button using Selenium webdriver?
I have the following html element I want to click:
<button type="button" class="btn button_primary" data-bind="click: $parent.handleSsoLogin.bind($parent)"> Sign In
... | Selecting button in Selenium python using web driver | Can anyone please let me know how to correctly click on the button using Selenium webdriver?
I have the following html element I want to click:
<button type="button" class="btn button_primary" data-bind="click: $parent.handleSsoLogin.bind($parent)"> Sign In
</button>
I ... | [
"Here is a complete example of how you can go to login page and login, on terex parts (why you edited out the url, I don't know).\nAssuming you have a working Selenium setup, you will also need the following imports:\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWa... | [
0,
0
] | [] | [] | [
"python",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074321926_python_selenium_webdriver_web_scraping.txt |
Q:
average of dictionary values
I have to create a function that takes a dictionary containing the scores of different rounds as an argument. The function returns the average score for all rounds.
Here's an example of how the function should work:
>>> find_average({'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'r... | average of dictionary values | I have to create a function that takes a dictionary containing the scores of different rounds as an argument. The function returns the average score for all rounds.
Here's an example of how the function should work:
>>> find_average({'round 1': [1, 2, 3, 4], 'round 2': [3, 4, 2, 7], 'round 3': [2, 7, 5, 6]})
4.8
I tri... | [
"You need to find the average of each value in the dictionary and find the average of that list.\ndef find_average(dictionary):\n sums = [sum(lst)/len(lst) for lst in dictionary.values()]\n return sum(sums)/len(sums)\n\nThe result will be 3.8333333333333335 but you can round the result like this round(sum(sum... | [
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074327508_dictionary_python.txt |
Q:
Is there a dark mode for Catboost fitting plot?
It seems there is no darkmode easily accessible for catboost fitting plot.
The documentation does not seem to contain anything on the subject.
I am running my Jupyter Notebook into VS code and I am using these lines to get dark modes with seaborn and matplotlib:
impo... | Is there a dark mode for Catboost fitting plot? | It seems there is no darkmode easily accessible for catboost fitting plot.
The documentation does not seem to contain anything on the subject.
I am running my Jupyter Notebook into VS code and I am using these lines to get dark modes with seaborn and matplotlib:
import seaborn as sns
import matplotlib.pyplot as plt
sn... | [
"A workaround is to add the following code to a Jupyter cell:\n%%html\n<style>\n.catboost {\n color: white;\n background-color: black;\n}\n\n.catboost .main-svg {\n filter: invert(1);\n}\n</style>\n\n",
"No, there is no dark mode specifically for catboost. Giving a look at their Docs it is evident that c... | [
1,
0
] | [] | [] | [
"catboost",
"darkmode",
"plot",
"python"
] | stackoverflow_0074137166_catboost_darkmode_plot_python.txt |
Q:
Making a histogram like summary of the values of a dataframe
I've got the following price df:
datetime
2022-09-07 12:30:00 144.183
2022-09-07 12:35:00 144.184
2022-09-07 12:40:00 144.151
2022-09-07 12:45:00 144.154
2022-09-07 12:50:00 144.144
2022-09-07 12:55:00 144.154
2022-09-07 13:00:00 144... | Making a histogram like summary of the values of a dataframe | I've got the following price df:
datetime
2022-09-07 12:30:00 144.183
2022-09-07 12:35:00 144.184
2022-09-07 12:40:00 144.151
2022-09-07 12:45:00 144.154
2022-09-07 12:50:00 144.144
2022-09-07 12:55:00 144.154
2022-09-07 13:00:00 144.203
Name: High, dtype: float64
With a margin of 0.01 of each pri... | [
"With the dataframe you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"col1\": [\n \"2022-09-07 12:30:00\",\n \"2022-09-07 12:35:00\",\n \"2022-09-07 12:40:00\",\n \"2022-09-07 12:45:00\",\n \"2022-09-07 12:50:00\",\n \"2022-0... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074292102_dataframe_pandas_python.txt |
Q:
cannot import name 'PageCoroutine' from 'scrapy_playwright.page'
I am trying to use scrapy and playwright to scrape dynamic webpages, I installed scrapy and playwright, however, when I try to run my spider, i get this error.
ImportError: cannot import name 'PageCoroutine' from 'scrapy_playwright.page' (C:\Ali\Data... | cannot import name 'PageCoroutine' from 'scrapy_playwright.page' | I am trying to use scrapy and playwright to scrape dynamic webpages, I installed scrapy and playwright, however, when I try to run my spider, i get this error.
ImportError: cannot import name 'PageCoroutine' from 'scrapy_playwright.page' (C:\Ali\DataCamp\Web Scraping in Python\Scrapy\venv\lib\site-packages\scrapy_playw... | [
"PageCoroutine is deprecated/obsolute. Use playwright_page_methods instead.\nWorking code as an example:\nimport scrapy\nfrom scrapy_playwright.page import PageMethod\n\nclass TestSpider(scrapy.Spider):\n name = \"test\"\n def start_requests(self):\n yield scrapy.Request(\n\n url=\"https://s... | [
1
] | [] | [] | [
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0074328303_python_scrapy_web_scraping.txt |
Q:
Python library architecture with two diferent math backend, how to?
I want to build a library in python for scientific computing. Precisely for natural coordinates mechanics. I want to think a bit before jumping into the code. This post asks for any advice, bad or good ideas. I'm not a pro in python, and I'm sure.... | Python library architecture with two diferent math backend, how to? | I want to build a library in python for scientific computing. Precisely for natural coordinates mechanics. I want to think a bit before jumping into the code. This post asks for any advice, bad or good ideas. I'm not a pro in python, and I'm sure. There can be experts around.
First, I want my library to be usable with ... | [
"Maybe you could use an if condition to check the type of the value like this (if the value is a numpy array then use numpy):\nclass HelloWorld:\n def __init__(value):\n if type(value) == np.ndarray:\n numpy = True\n self.value = value\n if numpy:\n self.transpose_value = value.trans... | [
0
] | [] | [] | [
"architecture",
"backend",
"math",
"package",
"python"
] | stackoverflow_0074328627_architecture_backend_math_package_python.txt |
Q:
HackerRank Game of Thrones
I am trying to solve this problem on HackerRank and I am having a issue with my logic. I am confused and not able to think what I'm doing wrong, feels like I'm stuck in logic.
Question link: https://www.hackerrank.com/challenges/game-of-thrones/
I created a dictionary of alphabets with v... | HackerRank Game of Thrones | I am trying to solve this problem on HackerRank and I am having a issue with my logic. I am confused and not able to think what I'm doing wrong, feels like I'm stuck in logic.
Question link: https://www.hackerrank.com/challenges/game-of-thrones/
I created a dictionary of alphabets with value 0. And then counting number... | [
"Explanation\nThe issue is that the code doesn't really look for palindromes. Let's step through it with a sample text based on a valid one that they gave: aaabbbbb (the only difference between this and their example is that there is an extra b).\nYour first for loop counts how many times the letters appear in the ... | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074325524_python_python_3.x.txt |
Q:
Compare images Python PIL
How can I compare two images? I found Python's PIL library, but I do not really understand how it works.
A:
To check does jpg files are exactly the same use pillow library:
from PIL import Image
from PIL import ImageChops
image_one = Image.open(path_one)
image_two = Image.open(path_t... | Compare images Python PIL | How can I compare two images? I found Python's PIL library, but I do not really understand how it works.
| [
"To check does jpg files are exactly the same use pillow library:\nfrom PIL import Image\nfrom PIL import ImageChops\n\nimage_one = Image.open(path_one)\nimage_two = Image.open(path_two)\n\ndiff = ImageChops.difference(image_one, image_two)\n\nif diff.getbbox():\n print(\"images are different\")\nelse:\n pr... | [
35,
14,
5,
4,
2,
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0035176639_python_python_imaging_library.txt |
Q:
Employee hiring function does not hire employee despite a vacant post
I have a class model based on an Employee and Company class. In the following, a company can apply_in_company for the desired role and team. The Company has a function hire_employee that accepts the employee only if the post is not occupied, an... | Employee hiring function does not hire employee despite a vacant post | I have a class model based on an Employee and Company class. In the following, a company can apply_in_company for the desired role and team. The Company has a function hire_employee that accepts the employee only if the post is not occupied, and the other requirements are met. Role and Team are two Enums with some rol... | [
"The issue is that auto is a function, and should be called to create a different instance for each assignment. As you have it now, only the first name in each enum is unique, and all the others are aliases.\nYour class should look like:\nclass CompanyRoles(Enum):\n MANAGER = auto()\n LEAD = auto()\n ...\... | [
0
] | [] | [] | [
"enums",
"python"
] | stackoverflow_0074327694_enums_python.txt |
Q:
How can I find the number of arguments of a Python function?
How can I find the number of arguments of a Python function? I need to know how many normal arguments it has and how many named arguments.
Example:
def someMethod(self, arg1, kwarg1=None):
pass
This method has 2 arguments and 1 named argument.
A:
... | How can I find the number of arguments of a Python function? | How can I find the number of arguments of a Python function? I need to know how many normal arguments it has and how many named arguments.
Example:
def someMethod(self, arg1, kwarg1=None):
pass
This method has 2 arguments and 1 named argument.
| [
"The previously accepted answer has been deprecated as of Python 3.0. Instead of using inspect.getargspec you should now opt for the Signature class which superseded it. \nCreating a Signature for the function is easy via the signature function:\nfrom inspect import signature\n\ndef someMethod(self, arg1, kwarg1=No... | [
208,
120,
33,
32,
16,
7,
5,
3,
3,
3,
0,
0,
0,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0000847936_function_python.txt |
Q:
Python lists and def functions
Hi i am new to python and i have a little problems with my code.
def Sumn(mylist):
i = 0
sum = 0
for i in mylist[1]:
sum += mylist[i]
return sum
i+=1
import myFunctions
mylist = [6, 12, 645, 3, -8]
print(myFunctions.Sumn(mylist))
I was expecting... | Python lists and def functions | Hi i am new to python and i have a little problems with my code.
def Sumn(mylist):
i = 0
sum = 0
for i in mylist[1]:
sum += mylist[i]
return sum
i+=1
import myFunctions
mylist = [6, 12, 645, 3, -8]
print(myFunctions.Sumn(mylist))
I was expecting that the numbers from the list will... | [
"Line by line comments:\ndef Sumn(mylist):\n i = 0 # this variable is unused\n sum = 0 # variable name overrides builtin 'sum' function\n for i in mylist[1]: # this will error because mylist[1] is a single int\n sum += mylist[i] # this only works if i is an index of mylist\n re... | [
3,
2
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074328755_list_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.