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:
* operation in python for 2-d matrix initialization
You init a 2-d matrix like this
board = [[0] * width for _ in range(height)]
Instead of
board = [[0] * width] * height
as it creates the list once and every row references the same list.
Is it not the same in the first case, we still use * so each column in eac... | * operation in python for 2-d matrix initialization | You init a 2-d matrix like this
board = [[0] * width for _ in range(height)]
Instead of
board = [[0] * width] * height
as it creates the list once and every row references the same list.
Is it not the same in the first case, we still use * so each column in each row should reference the same element for a given row. ... | [
"0 is immutable.\nIn itself, it is not the root cause of the seemingly different behavior. The real difference is that you don't intend to change value of 0 (since you can't), so don't really know that it would not have been the same for 0, if you had changed the value of one of them (if it were possible).\nNote th... | [
1,
0
] | [] | [] | [
"python",
"python_2.7",
"python_2.x",
"python_3.5",
"python_3.x"
] | stackoverflow_0074470550_python_python_2.7_python_2.x_python_3.5_python_3.x.txt |
Q:
Using Python Openpyxl to Unmerge Cells and Assign Them Their Previous Value
Doed any one have a way to have python loop through a column, find merged cells, and then assing them their previous merged value? I am currently using Openpyxl.
print(worksheet.merged_cells.ranges)
I only got a way to detect the merged c... | Using Python Openpyxl to Unmerge Cells and Assign Them Their Previous Value | Doed any one have a way to have python loop through a column, find merged cells, and then assing them their previous merged value? I am currently using Openpyxl.
print(worksheet.merged_cells.ranges)
I only got a way to detect the merged cell.
| [
"This is a variation from other answers in the question openPyXL - assign value to range of cells during unmerge. The later answers are more suitable but still needed some modification.\nThis mod creates a list of the merge cells first since if there is more that one set of cells to demerge the coords of later merg... | [
0
] | [] | [] | [
"excel",
"loops",
"openpyxl",
"python"
] | stackoverflow_0074467889_excel_loops_openpyxl_python.txt |
Q:
Django - Contain both register & login views on the same page
I am creating a simple application in Django, where my users can register and login to their accounts.
I have both a signup and a login form on my home page, but it doesn't work for logging in or registering: the form won't let the user's create an acco... | Django - Contain both register & login views on the same page | I am creating a simple application in Django, where my users can register and login to their accounts.
I have both a signup and a login form on my home page, but it doesn't work for logging in or registering: the form won't let the user's create an account or sign into their already existing account.
My Register Form:
... | [
"i would suggest you try using different names for each inputs, in your code you have used same names and i think its conflicting with each other!!!\n"
] | [
0
] | [] | [] | [
"css",
"django",
"html",
"python"
] | stackoverflow_0074470025_css_django_html_python.txt |
Q:
Getting more on each iteration for list.append
I've written a code that lets the user continuously input new members' names for The Beatles, and prints a new list of members' names once the user has done with inputting, but I keep getting repeated names if I enter more than one name.
Could somebody help me out her... | Getting more on each iteration for list.append | I've written a code that lets the user continuously input new members' names for The Beatles, and prints a new list of members' names once the user has done with inputting, but I keep getting repeated names if I enter more than one name.
Could somebody help me out here?
# step 1
beatles = ['John Lennon', 'Paul McCartne... | [
"two solution\n1:\nfor i in new_list:\n if i not in beatles:\n beatles.append(i)\n\nor you don't need new_list at all\n2: after else\nbeatles.append(new_member)\n",
"You should set new_member empty and define new_list each time the code runs you can make some changes as i done in you code and it will ru... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074470679_list_python.txt |
Q:
How to detect keypress in python using keyboard module?
I am making a program in python to detect what key is pressed and based on my keyboard it will make a decision.
I want to implement it using keyboard module in python.
I would do something like this,
import keyboard
while True:
if keyboard.read_key() == ... | How to detect keypress in python using keyboard module? | I am making a program in python to detect what key is pressed and based on my keyboard it will make a decision.
I want to implement it using keyboard module in python.
I would do something like this,
import keyboard
while True:
if keyboard.read_key() == 'enter':
print('Enter is pressed)
if keyboard.rea... | [
"As per Keyboard documentation:\n\nOther applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.\n\nOne way to solve your problem with keyboard module is keyboard.wait('key')\n# Blocks until you press esc\nkeyboard.wait('esc')\n\... | [
0,
0
] | [] | [] | [
"detect",
"keyboard",
"keypress",
"python"
] | stackoverflow_0074326247_detect_keyboard_keypress_python.txt |
Q:
importing numba module shows ImportError
so i am currently using vs code with anaconda, both latest versions. When trying to import jit from numba like so,
from numba import jit
import numpy as np
x = np.arange(100).reshape(10, 10)
@jit(nopython=True) # Set "nopython" mode for best performance, equivalent to @nj... | importing numba module shows ImportError | so i am currently using vs code with anaconda, both latest versions. When trying to import jit from numba like so,
from numba import jit
import numpy as np
x = np.arange(100).reshape(10, 10)
@jit(nopython=True) # Set "nopython" mode for best performance, equivalent to @njit
def go_fast(a): # Function is compiled to m... | [
"Change the name of your python script and see if that works. :P\n"
] | [
0
] | [] | [] | [
"numba",
"python"
] | stackoverflow_0066260963_numba_python.txt |
Q:
Unable to call static method inside another static method
I have a class which has static methods and I want to have another static method within this class to call the method but it returns NameError: name ''method_name' is not defined
Example of what I'm trying to do.
class abc():
@staticmethod
def metho... | Unable to call static method inside another static method | I have a class which has static methods and I want to have another static method within this class to call the method but it returns NameError: name ''method_name' is not defined
Example of what I'm trying to do.
class abc():
@staticmethod
def method1():
print('print from method1')
@staticmethod
... | [
"It doesn't work because method1 is a property of abc class, not something defined in a global scope.\nYou have to access it by directly referring to the class:\n @staticmethod\n def method2():\n abc.method1()\n print('print from method2')\n\nOr using a classmethod instead of staticmethod, which... | [
4,
0
] | [] | [] | [
"methods",
"python",
"static_methods"
] | stackoverflow_0070842483_methods_python_static_methods.txt |
Q:
TemplateDoesNotExist at / Exception Value: index.html django
welcome
i make a new project and i put index.html in templates dirctory and when i runserver i got the message TemplateDoesNotExist at / where the mistake i done
there is the views.py
from django.shortcuts import render, redirect
def index(request):
... | TemplateDoesNotExist at / Exception Value: index.html django | welcome
i make a new project and i put index.html in templates dirctory and when i runserver i got the message TemplateDoesNotExist at / where the mistake i done
there is the views.py
from django.shortcuts import render, redirect
def index(request):
return render(request,'index.html')
there is the urls.py
from dja... | [
"just add TEMPLATES_DIR inside TEMPLATES in settings.py file.\nExample:\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [TEMPLATES_DIR], #Added here\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'd... | [
0
] | [] | [] | [
"django",
"html",
"python",
"settings",
"templates"
] | stackoverflow_0074470740_django_html_python_settings_templates.txt |
Q:
How do I split a string of numbers separated by commas into a list?
I am trying to split a string of numbers separated by commas into a list but it it giving me this error:
TypeError: 'str' object cannot be interpreted as an integer
This is what I've tried:
numbers = "1, 2, 3, 4, 5, 500, 600, 800"
numbers_list = ... | How do I split a string of numbers separated by commas into a list? | I am trying to split a string of numbers separated by commas into a list but it it giving me this error:
TypeError: 'str' object cannot be interpreted as an integer
This is what I've tried:
numbers = "1, 2, 3, 4, 5, 500, 600, 800"
numbers_list = numbers.split(",", " ")
print(numbers_list)
| [
"The .split method only takes one string argument, the second argument is an integer and specifies the maximum number of splits. So, if the second argument was 2, it would only split the string up to 2 times, which would get you a list with a length of 3. But since you don't care about exactly how many times the st... | [
1
] | [
"import re\n \nnumbers = \"1, 2, 3, 4, 5, 500, 600, 800\"\n \nval = re.sub(r'[^\\w]', ' ', numbers)\nli = val.split(\" \") \nli2 = [] \nfor i in li:\n if i == \"\":\n pass\n else:\n li2.append(i)\n \nprint(li2)\n\nimport regex, And try this code\n"
] | [
-1
] | [
"python",
"split"
] | stackoverflow_0074470819_python_split.txt |
Q:
Sum of diagonal elements in a matrix
I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happening here.
n = 3
a = [[11,2,4],[4,5,6],[10,8,-12]]
sum_first_diagonal = sum(a[i][i] for i in range(n))... | Sum of diagonal elements in a matrix | I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happening here.
n = 3
a = [[11,2,4],[4,5,6],[10,8,-12]]
sum_first_diagonal = sum(a[i][i] for i in range(n))
sum_second_diagonal = sum(a[n-i-1][n-i-1]... | [
"Use numpy library which is powerful for any matrix calculations. For your specific case:\nimport numpy as np\na = [[11,2,4],[4,5,6],[10,8,-12]]\nb = np.asarray(a)\nprint('Diagonal (sum): ', np.trace(b))\nprint('Diagonal (elements): ', np.diagonal(b))\n\nYou can easily install numpy with pip or other ways that you ... | [
24,
19,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"Since you know the positions of the diagonal elements for row i, you can write it quite densely like:\nd = sum(row[i] + row[-1-i] for i, row in a)\n\nAnd, for odd sized matrices, you shouldn't add the center element twice:\nif len(a)%2:\n centre = len(a)//2\n d -= a[centre][centre]\n\n",
"def sum_diagnol()... | [
-1,
-1,
-1,
-1,
-1
] | [
"matrix",
"python"
] | stackoverflow_0035252993_matrix_python.txt |
Q:
How do solve this program
sticks_remaining = 13 * "|" sticks = 13 print(f'{sticks_remaining} {sticks} sticks remaining')
player = 1 print("You may pickup between 1 to 4") pickup = input("How many sticks do you want to pickup?:\n")
sticks_remaining1 = sticks_remaining - pickup sticks = sticks - pickup print(f'{stic... | How do solve this program | sticks_remaining = 13 * "|" sticks = 13 print(f'{sticks_remaining} {sticks} sticks remaining')
player = 1 print("You may pickup between 1 to 4") pickup = input("How many sticks do you want to pickup?:\n")
sticks_remaining1 = sticks_remaining - pickup sticks = sticks - pickup print(f'{sticks_remaining1} {sticks} sticks ... | [
"I think we can push the sticks string to array and remove the element based on the input selection.\ndef joinString(array):\n return ' '.join([str(elem) for elem in array])\n\nsticks = list(13 * \"|\")\nsticks_remaining = joinString(sticks)\nprint(f' {sticks_remaining} sticks remaining')\n\nplayer = print(\"You... | [
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0074470049_php_python.txt |
Q:
Plotly 3D surface plot not appearing
Hi I am trying to plot Plotly 3D surface plot, but unfortunately it doesnt appear. When I try with Scatter3D it works though not with Surface3D. Any ideas why?
# Scatter 3D
p = go.Figure()
p.add_trace(go.Scatter3d(
x = df.X1,
y = df.X2,
z = df.Y3,
mode = "marker... | Plotly 3D surface plot not appearing | Hi I am trying to plot Plotly 3D surface plot, but unfortunately it doesnt appear. When I try with Scatter3D it works though not with Surface3D. Any ideas why?
# Scatter 3D
p = go.Figure()
p.add_trace(go.Scatter3d(
x = df.X1,
y = df.X2,
z = df.Y3,
mode = "markers",
marker = dict(size = 3),
name ... | [
"A surface is not just a bunch of points. To draw a surface, Plotly needs to know how to split it in elementary triangles. Sure, you may think that, seeing your scatter plot, it seems obvious how to do so. But, well, it would be way less obvious if your points were not that planar. Plus, even in obvious cases, that... | [
2
] | [] | [] | [
"graph",
"plotly",
"python",
"visualization"
] | stackoverflow_0074470382_graph_plotly_python_visualization.txt |
Q:
How to aggregate rows from a CSV, excluding ones based on a list of values
I have a csv with the following data:
"id","Title","Author(s)","Format","Size","Tags"
"1","Horse","John","KFX","122","Classic"
"1","Horse","John","KFX","122","Drama"
"1","Horse","John","KFX","122","Horror"
"1","Horse","John","AZW3","122","C... | How to aggregate rows from a CSV, excluding ones based on a list of values | I have a csv with the following data:
"id","Title","Author(s)","Format","Size","Tags"
"1","Horse","John","KFX","122","Classic"
"1","Horse","John","KFX","122","Drama"
"1","Horse","John","KFX","122","Horror"
"1","Horse","John","AZW3","122","Classic"
"1","Horse","John","AZW3","122","Drama"
"1","Horse","John","AZW3","122",... | [
"You can use custom functions to aggregate:\ndef uniq_str(l):\n return ', '.join(dict.fromkeys(map(str, l)))\n\ndef agg_format(l):\n s = set(l) # not necessary if only 1 comparison\n if 'KFX' in s:\n return 'KFX'\n else:\n exclude = {'PDF'}\n return next((x for x in l if x not in ex... | [
3,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074092558_pandas_python.txt |
Q:
Need to order column data in CSV files to match the Row 1 header, but only move the row 2 and below data
I am stuck on an issue in which I have a CSV file and need to keep all the headers in row 1 in the specific order I was given, but the row 2 and below data for some of the columns are displaced meaning in Colum... | Need to order column data in CSV files to match the Row 1 header, but only move the row 2 and below data | I am stuck on an issue in which I have a CSV file and need to keep all the headers in row 1 in the specific order I was given, but the row 2 and below data for some of the columns are displaced meaning in Column C I will need to move that column of data excluding row 1 header to Column F. I looked through stackoverflow... | [
"df = pd.read_csv(\"csv file path\")\n\n# swap Col A and Col B \ndf['F'] = df['A']\ndf['A'] = df['B']\ndf['B'] = df['F']\n\n# swap Col C and Col D\ndf['F'] = df['C']\ndf['C'] = df['D']\ndf['D'] = df['F']\n\ndf.drop('F', axis=1) # Delete Temp Col\n\nI guess you mean that?\n"
] | [
0
] | [] | [] | [
"columnsorting",
"csv",
"excel",
"python",
"sorting"
] | stackoverflow_0074470984_columnsorting_csv_excel_python_sorting.txt |
Q:
bmi calculator how do restart the calculator to go back to yes/no at the top
Take_Bmi=(input("Take bmi yes or no "))
if Take_Bmi == "yes":
name1=input(" enter your name")
height_m1=input(" enter your height in m")
weight_kg1=input(" enter your weight")
def bmi_calculator(name1,height_m1,weight_kg1... | bmi calculator how do restart the calculator to go back to yes/no at the top | Take_Bmi=(input("Take bmi yes or no "))
if Take_Bmi == "yes":
name1=input(" enter your name")
height_m1=input(" enter your height in m")
weight_kg1=input(" enter your weight")
def bmi_calculator(name1,height_m1,weight_kg1):
bmi = float(weight_kg1) / (float(height_m1)** 2)
#The input function r... | [
"The input function returns a string.\nSo to get your output you need to use \"float()\" for height and weight:\nbmi = float(weight_kg1) / (float(height_m1)** 2)\n\nAlso, you have to call your function, e.g.\nbmi_calculator(name1,float(height_m1),float(weight_kg1))\n\n",
"After printing the result\nYou can add a ... | [
0,
0
] | [] | [] | [
"function",
"input",
"python"
] | stackoverflow_0061872542_function_input_python.txt |
Q:
mailto link into python-telegram-bot message for letting user send a precompiled email
is there a simple way to show a hyperlink for letting user send an email in python-telegram-bot? I've tried this but the link redirects the user to a web page of the email domain. I would have a redirect into a default mail app.... | mailto link into python-telegram-bot message for letting user send a precompiled email | is there a simple way to show a hyperlink for letting user send an email in python-telegram-bot? I've tried this but the link redirects the user to a web page of the email domain. I would have a redirect into a default mail app.
context.bot.sendMessage(chat_id=update.message.chat_id, text="Contact us <a href='mailto:xx... | [
"The problem is that Telegram doesn't recognize mailto: urls. In order to wrap it into an \"acceptable\" https url, you can use the URL shortening services like TinyUrl. This way, the https url will redirect into a mailto url which is what you want.\nHere's an example:\n$ curl -I https://a-random-url-shortener.com/... | [
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram",
"telegram_bot"
] | stackoverflow_0072642708_python_python_telegram_bot_telegram_telegram_bot.txt |
Q:
How do i write code to handle Input error with BMI calculator?
Enter your height in meters: t
Invalid choice. Try again
Enter your height in meters: 1.7
Enter your weight in kg: g
Invalid choice. Try again
Enter your height in meters:
This is my output.
The first time the user inputs an invalid choice the correct ... | How do i write code to handle Input error with BMI calculator? | Enter your height in meters: t
Invalid choice. Try again
Enter your height in meters: 1.7
Enter your weight in kg: g
Invalid choice. Try again
Enter your height in meters:
This is my output.
The first time the user inputs an invalid choice the correct display is shown and the user is directed to re-enter their height.
... | [
"Like this:-\ndef BMI():\n\nwhile True:\n\n try:\n\n try:\n\n h=float(input(\"Enter your height in meters: \"))\n\n except ValueError:\n\n print(\"Invalid choice. Try again\")\n\n try: \n\n\n\n w=float(input(\"Enter your weight in kg: \"))\n\n except ... | [
1,
0,
0
] | [] | [] | [
"python",
"submenu",
"user_input"
] | stackoverflow_0074470626_python_submenu_user_input.txt |
Q:
Error: command '/usr/bin/gcc' failed with exit code 1
I use visual studion with Windows 10. After adding my runtime.txt (python-3.10.8) and requirements.txt files, I tried to deploy my Flask App to heroku 22 for the first time with 'git push heroku master' but then got the error as above.
I have a txt file with th... | Error: command '/usr/bin/gcc' failed with exit code 1 | I use visual studion with Windows 10. After adding my runtime.txt (python-3.10.8) and requirements.txt files, I tried to deploy my Flask App to heroku 22 for the first time with 'git push heroku master' but then got the error as above.
I have a txt file with the full output from the command. Let me know if I should att... | [
"There were a bunch of missing packages like greenlet and also outdated packages like wheel that I first needed to sort out to resolve this issue.\nNow my program was able to deploy successfully.\n"
] | [
0
] | [] | [] | [
"heroku",
"python"
] | stackoverflow_0074444802_heroku_python.txt |
Q:
How do I make strings in a file get into separate sets when a specific word is mentioned?
I'm trying to check if a certain word is mentioned in a file, then the words under it become a part of a set, which then this set would be put in a tuple.
For instance, the file would say:
COUNTRIES
America
Canada
Russia
Pola... | How do I make strings in a file get into separate sets when a specific word is mentioned? | I'm trying to check if a certain word is mentioned in a file, then the words under it become a part of a set, which then this set would be put in a tuple.
For instance, the file would say:
COUNTRIES
America
Canada
Russia
Poland
PEOPLE
George
John
James
Kenny
Which would then become a list like this:
[{'America', 'Can... | [
"You never change l, so it will ALWAYS start with `\"COUNTRIES\". That's why the loop never ends. Try this:\nheader = None\ntrack = {}\nfor line in open('countries.txt', 'r'):\n line = line.strip()\n if line.isupper():\n header = line\n track[header] = []\n elif line:\n track[header]... | [
0,
0
] | [] | [] | [
"file",
"python",
"python_3.x",
"set"
] | stackoverflow_0074470907_file_python_python_3.x_set.txt |
Q:
How to convert to Python 3
I am in the process of converting Python 2 code into Python 3. Currently I am facing difficulty in converting the following code to Python 3. Please help.
print 'Data cache hit ratio: %4.2f%%' % ratio
Also, what %4.2f%% means?
Tried to rewrite the code with format().
A:
Just put paren... | How to convert to Python 3 | I am in the process of converting Python 2 code into Python 3. Currently I am facing difficulty in converting the following code to Python 3. Please help.
print 'Data cache hit ratio: %4.2f%%' % ratio
Also, what %4.2f%% means?
Tried to rewrite the code with format().
| [
"Just put parens around the parameters.\nprint('Data cache hit ratio: %4.2f%%' % ratio)\n\nThere are fancier ways of doing formatting in Python 3, but that will work.\n%4.2f says \"display this floating point number in a 4-character field with a decimal point and two places after. So, like \"9.99\". %% says \"dis... | [
1,
1
] | [] | [] | [
"python",
"python_2.7",
"python_3.6"
] | stackoverflow_0074471072_python_python_2.7_python_3.6.txt |
Q:
How can I add a number to the x or y coordinate of the Turtle Pen? [PYTHON]
I need to be able to move the turtle cursor to its current coordinates +10y.
For example, if the turtle is at (0.00,0.00) I would need it to read its own coordinates and add 10 to the y value making it (0.00,10.00).
I already know how to f... | How can I add a number to the x or y coordinate of the Turtle Pen? [PYTHON] | I need to be able to move the turtle cursor to its current coordinates +10y.
For example, if the turtle is at (0.00,0.00) I would need it to read its own coordinates and add 10 to the y value making it (0.00,10.00).
I already know how to find the Turtle's current position with turtle.pos() but how would I add an intege... | [
"Wait nevermind I just found out I can use xcor() and ycor() with setx() and sety()\nexample:\ncurrent_y = t.ycor()\nt.sety(current_y + 10)\n\nthis moves the cursor 10 up from its current position\n",
"Use turtle.setpos(), Here is The Documentation from GeeksOfGeeks, Here\nFull Guide!\n"
] | [
1,
0
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074471161_python_python_turtle_turtle_graphics.txt |
Q:
python plotly dash treemap get selected child label
I'm trying to use a plotly treemap within dash. When the user selects a subgroup in the treemap by clicking on it, the treemap zooms in on the selected section. Is there a way for me to get the user's selection and use that as an input into a Dash callback?
For... | python plotly dash treemap get selected child label | I'm trying to use a plotly treemap within dash. When the user selects a subgroup in the treemap by clicking on it, the treemap zooms in on the selected section. Is there a way for me to get the user's selection and use that as an input into a Dash callback?
For example, here is code for a treemap in Dash:
import dash... | [
"You could use the dcc.Graph's clickData property in your callback\n\nclickData (dict; optional): Data from latest click event. Read-only.\n\n@app.callback(\n dash.dependencies.Output(\"output\", \"children\"),\n dash.dependencies.Input(\"graph\", \"clickData\"),\n)\ndef update_other_figure(click_data):\n ... | [
2,
0
] | [] | [] | [
"plotly",
"plotly_dash",
"python",
"treemap"
] | stackoverflow_0070647874_plotly_plotly_dash_python_treemap.txt |
Q:
Get max Value with Distinct Foreign key Django ORM
So this is my Model.
class OrderLine(models.Model):
product = models.ForeignKey(Product, on_delete=models.PROTECT, verbose_name="Product", null=False)
unit_price = models.DecimalField(null=True, max_digits=12, decimal_places=4, blank=True, verbose_nam... | Get max Value with Distinct Foreign key Django ORM | So this is my Model.
class OrderLine(models.Model):
product = models.ForeignKey(Product, on_delete=models.PROTECT, verbose_name="Product", null=False)
unit_price = models.DecimalField(null=True, max_digits=12, decimal_places=4, blank=True, verbose_name="Unit price")
Im trying to filter with Multiple Produ... | [
"You can use a GROUP BY expression as\nfrom django.db.models import Max\n\nresult = OrderLine.objects.values(\"product\").annotate(max_per_prod=Max(\"unit_price\"))\n\nThis is almost similar to the SQL expression\nSELECT product_id, MAX(unit_price) FROM table_name GROUP BY product_id\n\n"
] | [
1
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0074470958_django_django_orm_python.txt |
Q:
How can I determine that the value of column1 in df1 contains in column1 in df2 (python)
I have df1 image link
and
have df2 image link
My question how is it possible to determine if df1['whitelist'] contains df2[blocked].
Desirable result:
Image link
I was trying:
df2['white_list_num']=df2.apply(lambda x: 0 if x['... | How can I determine that the value of column1 in df1 contains in column1 in df2 (python) | I have df1 image link
and
have df2 image link
My question how is it possible to determine if df1['whitelist'] contains df2[blocked].
Desirable result:
Image link
I was trying:
df2['white_list_num']=df2.apply(lambda x: 0 if x['blocked'] in df1['whitelist'] else 'no num',axis=1)
df1['yes/no'] = [df1["whitelist"].str.fin... | [
"According to my understanding and your desired output, you want to check if whitelist contains blocked even if it is partially containing it. This can be used:\nimport pandas as pd\n\ndf1 = pd.DataFrame({'whitelist': [1567891112, 1781305891, 2358911121]})\ndf2 = pd.DataFrame({'blocked': [156789111, 178130, 23589]}... | [
0
] | [] | [] | [
"contains",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074471165_contains_dataframe_pandas_python.txt |
Q:
Python's run_in_executor aspects
There is run_in_executor in Python to perform blocking operations in a thread pool so they don't block the main thread.
What are performance limits for run_in_executor? I didn't find specific information about it. I understand that the answer depends on many factors, but I want to... | Python's run_in_executor aspects | There is run_in_executor in Python to perform blocking operations in a thread pool so they don't block the main thread.
What are performance limits for run_in_executor? I didn't find specific information about it. I understand that the answer depends on many factors, but I want to understand in general. For instance, ... | [
"run_in_executor doesn't decrease the delay of the operations, an operation that takes 0.5 seconds will still take 0.5 seconds, the difference is that the main thread is not blocked and can execute other async tasks, so the throughput of the entire server is increased and it can server more clients concurrently.\nk... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074470990_python.txt |
Q:
Tkinter StringVar not updating
I'm trying to make a program that displays the date automatically. I see a lot of people using a trace to do it, so I tried to follow them. My code is running well but the variable of date won't change according to the existing entries.
It should be :
2022-11-17
2022-11-18
2022-11-... | Tkinter StringVar not updating | I'm trying to make a program that displays the date automatically. I see a lot of people using a trace to do it, so I tried to follow them. My code is running well but the variable of date won't change according to the existing entries.
It should be :
2022-11-17
2022-11-18
2022-11-19
and not
2022-11-19
2022-11-19
... | [
"You need to use a unique StringVar() for each entry that holds the date string. I made a few other minor modifications as well. You can ignore them if you would like.\nFor example:\nimport tkinter as tk\nfrom tkcalendar import DateEntry\nfrom datetime import datetime, date, timedelta\n\nmy_w = tk.Tk()\nmy_w.geo... | [
0
] | [] | [] | [
"date",
"python",
"tkinter"
] | stackoverflow_0074470469_date_python_tkinter.txt |
Q:
Unable to import Scrapy Spider into Script
All my imports are working except for importing class SomeSpider into main/main.py from spider/src.py. The spider itself runs when I call scrapy crawl somespider in the terminal. Does python not recognize modules with scrapy.spider ?
My file structure:
/whiskers
-/venv
--... | Unable to import Scrapy Spider into Script | All my imports are working except for importing class SomeSpider into main/main.py from spider/src.py. The spider itself runs when I call scrapy crawl somespider in the terminal. Does python not recognize modules with scrapy.spider ?
My file structure:
/whiskers
-/venv
--/bin
--/include
--/lib
--/whiskers
---/whiskers
... | [
"Put your main.py script outside a package folder. A package folder is a folder containing an __init__.py. The idea which Guido van Rossum had with this, is that scripts - the starting points, modules where __name__ == '__main__' - should not reside inside but outside of packages. Packages shall just contain librar... | [
2
] | [] | [] | [
"python",
"python_import",
"scrapy"
] | stackoverflow_0074471140_python_python_import_scrapy.txt |
Q:
Kivy BoxLayout align widgets to the top border
I'm using the following Kivy code to create BoxLayout with buttons:
BoxLayout:
orientation: "vertical"
width: 200
size_hint_x: None
Button:
size_hint_y: None
height: 30
text: 'btn1'
Button:
size_hint_y: None
... | Kivy BoxLayout align widgets to the top border | I'm using the following Kivy code to create BoxLayout with buttons:
BoxLayout:
orientation: "vertical"
width: 200
size_hint_x: None
Button:
size_hint_y: None
height: 30
text: 'btn1'
Button:
size_hint_y: None
height: 30
text: 'btn2'
Button:
... | [
"You can also put an empty Widget at the end to take up the space.\nBoxLayout:\n orientation: \"vertical\"\n width: 200\n size_hint_x: None\n\n Button:\n size_hint_y: None\n height: 30\n text: 'btn1'\n\n Button:\n size_hint_y: None\n height: 30\n text: 'btn2'... | [
23,
7,
0
] | [] | [] | [
"kivy",
"python"
] | stackoverflow_0031324557_kivy_python.txt |
Q:
Is there sklearn library with parameter to set max and min, so .fit() is based on that max and min instead of the train set?
My goal is to scale a percentage column to 0 and 1. PS: i am not sure if this is legal or not, should I do this or should I set the min and max based on the train set?
However, the sklearn.p... | Is there sklearn library with parameter to set max and min, so .fit() is based on that max and min instead of the train set? | My goal is to scale a percentage column to 0 and 1. PS: i am not sure if this is legal or not, should I do this or should I set the min and max based on the train set?
However, the sklearn.preprocessing.MinMaxScaler does not let you do that although I already set the feature_range parameter.
The code
from sklearn.prepr... | [
"For model training, in order to have robust performance, we expect to see a similar distribution between train and test data (or even the real data that you will run inference later on). So I would let the Scaler to use the min and max based on the train set.\nOf course, in reality, the values might go out of the ... | [
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0074469426_python_scikit_learn.txt |
Q:
In tkinter, unable put label to the left, It remains in the middle
I mean i am reading a txt file, For every line in txt file i
want a new label.
root = tk.Tk()
#here it opens the file
with open("/file.txt", "r") as openedFile:
allLines = openedFile.readlines()
for line in allLines:
textInLine =... | In tkinter, unable put label to the left, It remains in the middle | I mean i am reading a txt file, For every line in txt file i
want a new label.
root = tk.Tk()
#here it opens the file
with open("/file.txt", "r") as openedFile:
allLines = openedFile.readlines()
for line in allLines:
textInLine = line
testText = Label(root, text=textInLine)
testText.... | [
"you can use anchor attribute:\ntestText.pack(anchor=\"w\")\n\nw means 'west'\n",
"There are 3 ways how you can manage your widgets.\nFirst one is by packing like:\ntestText = Label(root, text=\"Test Text\")\ntestText.pack(anchor=W)\n\nSecond one would be by placing (absolute positioning):\ntestText2 = Label(root... | [
2,
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074471291_python_tkinter.txt |
Q:
Finding the roots of a 4th degree polynomial function in Tensorflow
I'm trying to find a method to find the roots of the following 4th degree polynomial equation in Tensorflow:
k1 = 339.749
k2 = -31.988
k3 = 48.275
k4 = -7.201
r = k1 * x + k2 * x**2 + k3 * x**3 + k4 * x**4
where r is a given tensor and I need to... | Finding the roots of a 4th degree polynomial function in Tensorflow | I'm trying to find a method to find the roots of the following 4th degree polynomial equation in Tensorflow:
k1 = 339.749
k2 = -31.988
k3 = 48.275
k4 = -7.201
r = k1 * x + k2 * x**2 + k3 * x**3 + k4 * x**4
where r is a given tensor and I need to find the roots for every element of r. Specifically I'd need a tensor, ... | [
"You can use newton-raphson method to find the roots of any equation, as long as it is a continuous equation. First, randomly choose a starting point (this point must not be a point where the gradient of your function is zero), and then you can calculate a second approximation using,\nx_new = x - f(x)/f_prime(x)\n\... | [
0
] | [] | [] | [
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0074470394_machine_learning_python_tensorflow.txt |
Q:
how to solve problem error occurs when open setting page or cotacts page in odoo 16 localhost
when i open setting page or Contacts page, an error occurs
UncaughtPromiseError > TypeError
وعد لم يتم رصده > Cannot read properties of undefined (reading 'string')
TypeError: Cannot read properties of undefined (reading ... | how to solve problem error occurs when open setting page or cotacts page in odoo 16 localhost | when i open setting page or Contacts page, an error occurs
UncaughtPromiseError > TypeError
وعد لم يتم رصده > Cannot read properties of undefined (reading 'string')
TypeError: Cannot read properties of undefined (reading 'string')
at web/assets/1771-d8153f9/web.assets_backend.min.js:6521:211
at traverse (web/assets/177... | [
"Try the feature \"Regenerate Assets Bundles\" via the developer tools.\nOften times this solves those kind of issues. If it is not enough, please provide more informations about what you did before this error happened and I will help you further!\n"
] | [
0
] | [] | [] | [
"localhost",
"odoo",
"odoo_16",
"python"
] | stackoverflow_0074467975_localhost_odoo_odoo_16_python.txt |
Q:
Convert a data frame with date and value to a df with one row
I have a dataframe which has two columns. date and value.
import pandas as pd
import numpy as np
df = pd.DataFrame()
df['date'] = ['2020-03-01 00:00:00','2020-03-01 00:00:15', '2020-03-01 00:00:30', '2020-03-02 00:00:00','2020-03-02 00:00:15', '2020-03-... | Convert a data frame with date and value to a df with one row | I have a dataframe which has two columns. date and value.
import pandas as pd
import numpy as np
df = pd.DataFrame()
df['date'] = ['2020-03-01 00:00:00','2020-03-01 00:00:15', '2020-03-01 00:00:30', '2020-03-02 00:00:00','2020-03-02 00:00:15', '2020-03-02 00:00:30' , '2020-03-03 00:00:15', '2020-03-03 00:00:30', '2020-... | [
"you can use resample():\ndf['date']=pd.to_datetime(df['date'])\ndfx=df.set_index('date').resample('15S').first()\n\nWe got the distribution of all hours of the day. But we only need values between 00:00:00 and 00:00:30.\ndfx = dfx.between_time(\"00:00:00\", \"00:00:30\").reset_index()\nprint(dfx)\n'''\n date ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074469995_dataframe_pandas_python.txt |
Q:
UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail
I am trying to return the data list and plot. They do display in the HTML code instead of web page. When I look at the terminal it shows "UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail."
from io i... | UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail | I am trying to return the data list and plot. They do display in the HTML code instead of web page. When I look at the terminal it shows "UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail."
from io import BytesIO
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mp... | [
"It's just warning, it will run but can be a really painful problem. I'm not exactly an expert but I'm having the same warning, and it can be worse if you try to use matplotlib in a Thread besides Main Thread. For some reason matplotlib don't work well on Threads, which can cause your aplication to crash.\n",
"tr... | [
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0069924881_matplotlib_python.txt |
Q:
ipdb stops showing prompt text after carriage return
Recently when setting up a breakpoint using ipdb.set_trace(context=20) I can see the command I'm inputing the first time, after hitting return, next time I write an instruction or command in my ipdb prompt is not showing. When I hit enter it executes it and show... | ipdb stops showing prompt text after carriage return | Recently when setting up a breakpoint using ipdb.set_trace(context=20) I can see the command I'm inputing the first time, after hitting return, next time I write an instruction or command in my ipdb prompt is not showing. When I hit enter it executes it and shows it in the previous lines.
This wasn't happening until ve... | [
"This doesn't seem like a bug in ipdb (nor in IPython for that matter, with which this reproduces as well). The problem is between freezegun and prompt-toolkit, which IPython (and consequently ipdb) rely on. I'm hoping they will accept this PR, but until then this behavior can be resolved by adding prompt_toolkit t... | [
3
] | [] | [] | [
"ipdb",
"pdb",
"python"
] | stackoverflow_0071584885_ipdb_pdb_python.txt |
Q:
How to reshape array to 5d for neural network?
I'm trying to apply 3d CNN Conv3D to my data (images) but I have 3d array that I used when I was testing my data in Conv2D how can I reshape my data to 5D?
trainX shape: (50, 224, 224, 3)
valX shape: (50, 224, 224, 3)
trainY shape: (50, 5)
valY shape: (50, 5)
model =... | How to reshape array to 5d for neural network? | I'm trying to apply 3d CNN Conv3D to my data (images) but I have 3d array that I used when I was testing my data in Conv2D how can I reshape my data to 5D?
trainX shape: (50, 224, 224, 3)
valX shape: (50, 224, 224, 3)
trainY shape: (50, 5)
valY shape: (50, 5)
model = Sequential()
model.add(Conv3D(32, kernel_size=(3, 3... | [
"Assuming your data is images of size (50, 224, 224, 3), that means there are 50 images of size (224, 224, 3), so your model would expect a shape of (None, 224, 224, 3) during training.\nThe fix is most likely in the second line, which needs to be changed into this:\nmodel.add(Conv2D(32, kernel_size=(3, 3), activat... | [
0
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"numpy",
"python"
] | stackoverflow_0074471512_conv_neural_network_deep_learning_numpy_python.txt |
Q:
Recurrence relation for T(n) of Top-Down approach solution of Fibonacci sequence
What is the recurrence for T(n) of this code and the initial conditions of this recurrence? Notice that the code is in python and it is a top-down procedure solution for the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21... where
T(3... | Recurrence relation for T(n) of Top-Down approach solution of Fibonacci sequence |
What is the recurrence for T(n) of this code and the initial conditions of this recurrence? Notice that the code is in python and it is a top-down procedure solution for the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21... where
T(3) = 5 <-- number of calls of Fibonacci (3)
T(4) = 7
T(5) = 9
T(6) = 11
T(7) = 13
T(8)... | [
"\nThis question is to find a recurrence relation of the code above.\n\nThe base case is when is 0 or 1. In those cases totalCalls increments once. So:\n 0 = 1\n 1 = 1\nFor a greater value of , there is the initial increment of totalCalls and a recursive call left = FibHelper(n-1, memo). That recursive c... | [
1
] | [] | [] | [
"algorithm",
"dynamic_programming",
"math",
"python",
"time_complexity"
] | stackoverflow_0074470716_algorithm_dynamic_programming_math_python_time_complexity.txt |
Q:
What is the purpose of this string in this simple exercise?
I'm new to coding so I've been doing exercises. This one is about a car that the user commands to start and stop. My question is that why did the given solution include the first line in the following code?:
command = ""
started = False
while True:
co... | What is the purpose of this string in this simple exercise? | I'm new to coding so I've been doing exercises. This one is about a car that the user commands to start and stop. My question is that why did the given solution include the first line in the following code?:
command = ""
started = False
while True:
command = input("> ").lower()
if command == "start":
if... | [
"The only reason I can see is for readability.\nI don't say it's a good practice, just try to guess why it has been done here.\nWhen opening the source code everyone can see which variables will be used by the program and their type.\nstarted has to be initialized because it has a initial state.\nFor command it doe... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074471514_python.txt |
Q:
How can i read a csv file with python and compare values from yesterday and today?
So basically, I'm writing out statistics.
date,students
2022-11-16,22
2022-11-17,29
I want to read this csv back in and pull the col2 value from "yesterdays" row and compare it to the col2 value from "todays" row and look for a thr... | How can i read a csv file with python and compare values from yesterday and today? | So basically, I'm writing out statistics.
date,students
2022-11-16,22
2022-11-17,29
I want to read this csv back in and pull the col2 value from "yesterdays" row and compare it to the col2 value from "todays" row and look for a threshold difference. Something like a 5% variance. The last part is straightforward but ... | [
"You may consider that pandas is somewhat \"heavyweight\" for something so trivial.\nSo, without pandas how about:\nfrom datetime import datetime, timedelta\n\nnow = datetime.now()\ntoday, *_ = str(now).split()\nyesterday, *_ = str(now - timedelta(days=1)).split()\n\ntv = None\nyv = None\n\nwith open('test.csv') as... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074471008_pandas_python.txt |
Q:
How to call an instance method from a class method of the same class
I have a class as follows:
class MyClass(object):
int = None
def __init__(self, *args, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
def get_params(self):
return {'int': random.randint(0, ... | How to call an instance method from a class method of the same class | I have a class as follows:
class MyClass(object):
int = None
def __init__(self, *args, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
def get_params(self):
return {'int': random.randint(0, 10)}
@classmethod
def new(cls):
params = cls.get_params()... | [
"No, you can't and shouldn't call an instance method from a class without an instance. This would be very bad. You can, however call, a class method from and instance method. Options are\n\nmake get_param a class method and fix references to it\nhave __init__ call get_param, since it is a instance method\n\nAls... | [
17,
2,
0
] | [] | [] | [
"class_method",
"oop",
"python"
] | stackoverflow_0016427379_class_method_oop_python.txt |
Q:
AxisError: axis -1 is out of bounds
I already referred the posts here,here and here
Am trying to run a lassoCV model and fit it on my training dataset.
So, I tried the below code (this works)
from numpy import arange
from sklearn.linear_model import LassoCV
from sklearn.model_selection import RepeatedKFold
# defin... | AxisError: axis -1 is out of bounds | I already referred the posts here,here and here
Am trying to run a lassoCV model and fit it on my training dataset.
So, I tried the below code (this works)
from numpy import arange
from sklearn.linear_model import LassoCV
from sklearn.model_selection import RepeatedKFold
# define model evaluation method
cv = RepeatedKF... | [
"Try this code, give alpha in nump array\nreg = LassoCV(alphas=np.array([0.5]), cv=5, random_state=0).fit(x_train, y_train)\n\n"
] | [
1
] | [] | [] | [
"machine_learning",
"numpy",
"python",
"scikit_learn"
] | stackoverflow_0074471587_machine_learning_numpy_python_scikit_learn.txt |
Q:
Testing a method that uses a global variable
I'm trying to test a method that uses a global settings variable (python). I have these 3 files:
setting_to_test.py:
import os
GLOBAL_VAR = os.environ.get("GLOBAL_VAR", 6)
function_to_test.py:
from setting_to_test import GLOBAL_VAR
def funca():
return GLOBAL_VAR ... | Testing a method that uses a global variable | I'm trying to test a method that uses a global settings variable (python). I have these 3 files:
setting_to_test.py:
import os
GLOBAL_VAR = os.environ.get("GLOBAL_VAR", 6)
function_to_test.py:
from setting_to_test import GLOBAL_VAR
def funca():
return GLOBAL_VAR ** 2
test_module.py:
from unittest.mock import p... | [
"from https://docs.python.org/3/library/unittest.mock.html#id6:\n\nNow we want to test some_function but we want to mock out SomeClass using patch(). The problem is that when we import module b, which we will have to do then it imports SomeClass from module a. If we use patch() to mock out a.SomeClass then it will ... | [
2
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074471773_pytest_python.txt |
Q:
trying to make a very simple calculator and the elif code won't work
I was making a very simple calculator as my first project ever, and when I run the code, it says it wont work. I know this might be really easy to solve for developers, but I really don't know how to do it, so I will be grateful if anyone helps.
... | trying to make a very simple calculator and the elif code won't work | I was making a very simple calculator as my first project ever, and when I run the code, it says it wont work. I know this might be really easy to solve for developers, but I really don't know how to do it, so I will be grateful if anyone helps.
here is the code:
if symbol == "+":
print(int(inputNumber1),"+",int(inpu... | [
"You have missed closing 2 brackets that is why it says error for elif:\nif symbol == \"+\":\n print(int(inputNumber1),\"+\",int(inputNumber2),\"=\",(int(inputNumber1)+(int(inputNumber2))))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074471793_python.txt |
Q:
Folium Marker-Cluster map is not visualized for a large dataset
Im trying to create a Marker-Cluster map using folium for some data, I first tried with a sample dataset where the sample size is 1000 row points, which ran fine with no error. But when im trying to implement the same on the actual dataset which is of... | Folium Marker-Cluster map is not visualized for a large dataset | Im trying to create a Marker-Cluster map using folium for some data, I first tried with a sample dataset where the sample size is 1000 row points, which ran fine with no error. But when im trying to implement the same on the actual dataset which is of size 180000 row points, It is failing to create a map.
Im using Goog... | [
"Fast Marker Cluster has worked for this case. Following is the code:\nmap3 = folium.Map(location=[15, 20], zoom_start=3)\nmap3.add_child(FastMarkerCluster(df2[['latitude', 'longitude']].values.tolist()))\nmap3.save(\"save_file.html\")\n\nmap3\n\n"
] | [
0
] | [] | [] | [
"folium",
"markerclusterer",
"python",
"visualization"
] | stackoverflow_0074385089_folium_markerclusterer_python_visualization.txt |
Q:
Selecting DataFrames in List based on hour
I have a list with 24 DataFrames with hourly prices for two years inside, I want to specify a For Loop so each of these DataFrames only show the price for a single hour per day.
I have come this far:
for i in range(24):
dfs[i] = dfs[i][dfs[i]['hour_0'] == 1]
So this ... | Selecting DataFrames in List based on hour | I have a list with 24 DataFrames with hourly prices for two years inside, I want to specify a For Loop so each of these DataFrames only show the price for a single hour per day.
I have come this far:
for i in range(24):
dfs[i] = dfs[i][dfs[i]['hour_0'] == 1]
So this takes each row in the list and keeps the row if ... | [
"you can try:\nfor i in range(24):\n dfs[i] = dfs[i][dfs[i]['hour_'+str(i)] == 1]\n\nor with f-string, which is a bit cleaner:\nfor i in range(24):\n dfs[i] = dfs[i][dfs[i][f'hour_{i}'] == 1]\n\n"
] | [
1
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074471849_for_loop_python.txt |
Q:
beautiful soup escaping in html
I'm trying to read lines from a file, and try to put it in html by using beautiful soup.
each line will be appended into a list, and using for loop, I appended them in the string, and '\n' in every end of the line.
for example,
lines = [a,b,c,d]
string = ''
for line in lines:
st... | beautiful soup escaping in html | I'm trying to read lines from a file, and try to put it in html by using beautiful soup.
each line will be appended into a list, and using for loop, I appended them in the string, and '\n' in every end of the line.
for example,
lines = [a,b,c,d]
string = ''
for line in lines:
string = string + line + '\n'
and then... | [
"Try\nimport html\n\nsentences.string = html.unescape(string + '<br>')\n\n",
"Instead of building a single string and escaping the HTML for the <br> tag, use the .append method to add each line followed by soup.new_tag('br')\nfrom bs4 import BeautifulSoup\n\nlines = [\"apple\", \"banana\", \"cats\", \"dogs\"]\nso... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074470162_beautifulsoup_python.txt |
Q:
How to find the mean of every element in a python dictionary using for loop
comp_dict = {'ap': {'val': 0.3, 'count': 3}, 'sd': {'val': 0.02, 'count': 1}, 'ao': {'val': 0.01, 'count': 1}}
avg_rate = {}
for value in comp_dict.keys():
avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']
print... | How to find the mean of every element in a python dictionary using for loop | comp_dict = {'ap': {'val': 0.3, 'count': 3}, 'sd': {'val': 0.02, 'count': 1}, 'ao': {'val': 0.01, 'count': 1}}
avg_rate = {}
for value in comp_dict.keys():
avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']
print(avg_rate[value])
It seems like the output I got only generates the average I wa... | [
"You just made a little mistake when you print out the avg_rate value.\nyou can do this:\navg_rate = {}\n for value in comp_dict.keys():\n avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']\n print(avg_rate)\n\ngiven comp_dict = {'ap': {'val': 0.3, 'count': 3}, 'sd': {'val': 0.02, 'count': 1}, ... | [
1,
0
] | [] | [] | [
"average",
"dictionary",
"for_loop",
"list",
"python"
] | stackoverflow_0074470141_average_dictionary_for_loop_list_python.txt |
Q:
indexing a matrix from a vector array
I have two images, one is a RGB image and the other is a mask image that contains 0 and 1 to segment a specified object. (both images are of the same object)
I want to extract the RBG values of the initial image only at the indexes where the second matrix is 1, so that the fi... | indexing a matrix from a vector array | I have two images, one is a RGB image and the other is a mask image that contains 0 and 1 to segment a specified object. (both images are of the same object)
I want to extract the RBG values of the initial image only at the indexes where the second matrix is 1, so that the final value is an image of just the object wi... | [
"You can use numpys built-in broadcasting, and then just straight-out multiply the two in \"pythonic\" form.\nimport numpy as np\n\nimg = np.array([[[ 1, 2, 3],\n [ 4, 5, 6]],\n [[ 7, 8, 9],\n [10, 11, 12]]]) # shape (2, 2, 3)\n\nmask = np.array([[0,1],[0,1]]) # ... | [
1,
0
] | [] | [] | [
"image_processing",
"mask",
"numpy",
"python"
] | stackoverflow_0074468019_image_processing_mask_numpy_python.txt |
Q:
Greenlet runtime error and deployed app in docker keeps booting all the workers
RuntimeWarning: greenlet.greenlet size changed, may indicate binary
incompatibility. Expected 144 from C header, got 152 from PyObject
And all the workers are being booted.
2020-09-28T14:09:41.864089908Z [2020-09-28 14:09:41 +0000] [... | Greenlet runtime error and deployed app in docker keeps booting all the workers |
RuntimeWarning: greenlet.greenlet size changed, may indicate binary
incompatibility. Expected 144 from C header, got 152 from PyObject
And all the workers are being booted.
2020-09-28T14:09:41.864089908Z [2020-09-28 14:09:41 +0000] [31] [INFO]
Booting worker with pid: 31 2020-09-28T14:09:43.933141974Z [2020-09-28
14... | [
"as https://discuss.redash.io/t/binary-compatibility-issue-with-greenlet/7237\nindicates\na workaround is greenlet==0.4.16 or upgrade your gevent to 20.9.0\nfollowing fix is suggested on the greenlet github page\nhttps://github.com/python-greenlet/greenlet/issues/178#issuecomment-697342964\nalso see following issue... | [
19,
0
] | [] | [] | [
"azure_devops",
"devops",
"gevent",
"greenlets",
"python"
] | stackoverflow_0064105616_azure_devops_devops_gevent_greenlets_python.txt |
Q:
How to convert values of a specific dictionary key to uppercase?
I have this simplified dict:
{
{
"birthPlace" : "london"
},
"hello": "hello",
"birthPlace" : "rome"
}
And I want to make the value of birthPlace uppercase: how? I tried
smallalphabetDict={}
for key, value in myjson.items():
... | How to convert values of a specific dictionary key to uppercase? | I have this simplified dict:
{
{
"birthPlace" : "london"
},
"hello": "hello",
"birthPlace" : "rome"
}
And I want to make the value of birthPlace uppercase: how? I tried
smallalphabetDict={}
for key, value in myjson.items():
smallalphabetDict[key.upper()] = value
It doesn't work
| [
"This changes all the values of a dict to uppercase, if the value is a string:\nd = {......}\nfor k in d:\n if type(d[k]) == str: d[k] = d[k].upper()\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074459147_python.txt |
Q:
training scaler with training data
I'm just confused about training scaler model.
For example,
from sklearn.preprocessing import StandardScaler
object_ss = StandardScaler()
x_train_ss = obje_ss.fit_transform(x_train)
x_test_ss = obje_ss.transform(x_test)
is this different with the code below?
object_ss = Standa... | training scaler with training data | I'm just confused about training scaler model.
For example,
from sklearn.preprocessing import StandardScaler
object_ss = StandardScaler()
x_train_ss = obje_ss.fit_transform(x_train)
x_test_ss = obje_ss.transform(x_test)
is this different with the code below?
object_ss = StandardScaler()
object_ss.fit(x_train)
x_tra... | [
"The results will be identical, you can verify but trying both approaches and comparing the results.\nfrom sklearn.preprocessing import StandardScaler\n\nobject_ss = StandardScaler()\nx_train_ss = object_ss.fit_transform(x_train)\nx_test_ss = object_ss.transform(x_test)\n\nobject_ss2 = StandardScaler()\nobject_ss2.... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074471844_python.txt |
Q:
How to Perform GroupBy , Having and Order by together in Pyspark
I am looking for a solution where i am performing GROUP BY, HAVING CLAUSE and ORDER BY Together in a Pyspark Code. Basically we need to shift some data from one dataframe to another with some conditions.
The SQL Query looks like this which i am tryin... | How to Perform GroupBy , Having and Order by together in Pyspark | I am looking for a solution where i am performing GROUP BY, HAVING CLAUSE and ORDER BY Together in a Pyspark Code. Basically we need to shift some data from one dataframe to another with some conditions.
The SQL Query looks like this which i am trying to change into Pyspark
SELECT TABLE1.NAME, Count(TABLE1.NAME) AS COU... | [
"Your code is almost ok, after fixing a few syntax issues it works.\nAlso, I think for \"attendance\" you want to use sum rather than count (otherwise it will be always the same value as of name count).\nFor sorting, simply add orderBy.\ndf.withColumn(\"NAME\", lower(\"NAME\"))\n.groupBy('NAME')\n.agg(count('NAME')... | [
1
] | [] | [] | [
"apache_spark",
"databricks",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074464389_apache_spark_databricks_dataframe_pyspark_python.txt |
Q:
pandas.DatetimeIndex frequency is None and can't be set
I created a DatetimeIndex from a "date" column:
sales.index = pd.DatetimeIndex(sales["date"])
Now the index looks as follows:
DatetimeIndex(['2003-01-02', '2003-01-03', '2003-01-04', '2003-01-06',
'2003-01-07', '2003-01-08', '2003-01-09', ... | pandas.DatetimeIndex frequency is None and can't be set | I created a DatetimeIndex from a "date" column:
sales.index = pd.DatetimeIndex(sales["date"])
Now the index looks as follows:
DatetimeIndex(['2003-01-02', '2003-01-03', '2003-01-04', '2003-01-06',
'2003-01-07', '2003-01-08', '2003-01-09', '2003-01-10',
'2003-01-11', '2003-01-13',
... | [
"You have a couple options here:\n\npd.infer_freq\npd.tseries.frequencies.to_offset\n\n\nI suspect that errors down the road are caused by the missing freq.\n\nYou are absolutely right. Here's what I use often:\ndef add_freq(idx, freq=None):\n \"\"\"Add a frequency attribute to idx, through inference or directl... | [
21,
13,
8,
2,
0,
0,
0
] | [] | [] | [
"indexing",
"pandas",
"python",
"time_series"
] | stackoverflow_0046217529_indexing_pandas_python_time_series.txt |
Q:
best way to export anaconda environment but also include custom made packages?
I am developing a python package at work and intend to make it available to everyone, and it will come along with an environment.yml file that will set up the anaconda environment upon install so everything works out of the box.
I know ... | best way to export anaconda environment but also include custom made packages? | I am developing a python package at work and intend to make it available to everyone, and it will come along with an environment.yml file that will set up the anaconda environment upon install so everything works out of the box.
I know I can export my anaconda like this:
conda env export > environment.yml
I have a num... | [
"Here are some approaches that worked for me:\nFirst of all create wheel files out of the custom python packages using 'python setup.py bdist_wheel' command (Build a wheel/egg and all dependencies for a python project).\nTwo ways you can share the yaml file with the wheel file information:\n\nUpload the wheel file ... | [
0
] | [] | [] | [
"anaconda",
"pip",
"python",
"virtual_environment"
] | stackoverflow_0059665964_anaconda_pip_python_virtual_environment.txt |
Q:
Efficiently using np.where
I am using pandas and np.where to fill a new column if multiple conditions are met.
For this I am using the following database (but then 100 times bigger).
What I am doing now is:
df['new_column'] = np.where((df['year'] == 2018) & (df['price'] > 30000) & (df['fuel description'] == Petro... | Efficiently using np.where | I am using pandas and np.where to fill a new column if multiple conditions are met.
For this I am using the following database (but then 100 times bigger).
What I am doing now is:
df['new_column'] = np.where((df['year'] == 2018) & (df['price'] > 30000) & (df['fuel description'] == Petrol), 12, 10)
df['new_column'] = n... | [
"Try this,\ncondition = (df['year'] >= 2018) & (df['year'] <= 2022) & (df['price'] > 30000) \\\n & (df['fuel description'] == Petrol)\ndf['new_column'] = np.where(condition, 12 + (df['year']-2018)*3, 10)\n\nUpdate:\nIf there is no correlation between the values to be filled, you can construct an array in... | [
3,
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074471962_numpy_pandas_python.txt |
Q:
Failed to read marionette port with EC2 Ubuntu, Python, Selenium, Geckodriver
OS : AWS EC2 Ubuntu 22.04.1 LTS
Python : 3.10.6
Firefox : Mozilla Firefox 107.0
Geckodriver : 0.32.0 (2022-11-10)
UFW(Ubuntu Firewall) : Inactive
Others : latest version
from selenium import webdriver
from selenium.webdriver.firefox... | Failed to read marionette port with EC2 Ubuntu, Python, Selenium, Geckodriver | OS : AWS EC2 Ubuntu 22.04.1 LTS
Python : 3.10.6
Firefox : Mozilla Firefox 107.0
Geckodriver : 0.32.0 (2022-11-10)
UFW(Ubuntu Firewall) : Inactive
Others : latest version
from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.firefox.options i... | [
"I found another way.\nI read this post.\nhttps://github.com/SeleniumHQ/selenium/issues/10813\nI think it is a problem when you install Firefox on Ubuntu Snap package manager.\nIt works on Ubuntu 20.04.\nBecause Snap is not default package manager on that version.\nIt could be another solution to remove Snap on Ubu... | [
0
] | [] | [] | [
"firefox",
"geckodriver",
"python",
"selenium",
"ubuntu"
] | stackoverflow_0074470139_firefox_geckodriver_python_selenium_ubuntu.txt |
Q:
How to sort lines in file by number of words?
I've started a python course for beginners.
I have a file with lines:
"I was angry with my friend
I told my wrath my wrath did end
I was angry with my foe
I told it not my wrath did grow"
I need to sort lines by number of words in line and inside each line, the words n... | How to sort lines in file by number of words? | I've started a python course for beginners.
I have a file with lines:
"I was angry with my friend
I told my wrath my wrath did end
I was angry with my foe
I told it not my wrath did grow"
I need to sort lines by number of words in line and inside each line, the words need to be ordered by the number of letters in them.... | [
"You're trying to read from file_out and write to file_in.\ndef lines(filename):\n with open(filename) as fin:\n for line in fin:\n yield ' '.join(sorted(line.split(), key=len))\n\nwith open('output.txt', 'w') as fout:\n print(*sorted(lines('input.txt'), key=lambda x:len(x.split())), sep='\\... | [
0
] | [] | [] | [
"file",
"python",
"sortedlist"
] | stackoverflow_0074472049_file_python_sortedlist.txt |
Q:
How do I fix maximum recursion depth exceed without import sys
I am trying to do a recursion problem and the code works 3 out of 5 times. The 2 failed tests have the “maximum recursion depth exceeded in comparison error”. I have tried the import sys method but my laptop can only go up to 2000 before stack overflow... | How do I fix maximum recursion depth exceed without import sys | I am trying to do a recursion problem and the code works 3 out of 5 times. The 2 failed tests have the “maximum recursion depth exceeded in comparison error”. I have tried the import sys method but my laptop can only go up to 2000 before stack overflow. The 2 failed tests failed at n=8, m<=8 and n>0 , m=0
Here is what ... | [
"\nfix your code, it's outright broken for m<1 as the code will recurse infinitely (probably other cases as well)\nstop writing deeply recursive code in Python, the language is not designed for that and gets very unhappy\nswitch to Python 3.11, it has stopped using the C stack for the Python callstack, now you can ... | [
1
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074472143_python_recursion.txt |
Q:
Replace character in array list python
I have a python list like the following.
[(0, 0), (1, 1)]
how to convert it to this format??
{{0, 0}, {1, 1}}
A:
you could use the following:
start = [(0, 0), (1, 1)]
result = set()
for element in start:
result.add(element)
print(result)
As everyone said, you can't h... | Replace character in array list python | I have a python list like the following.
[(0, 0), (1, 1)]
how to convert it to this format??
{{0, 0}, {1, 1}}
| [
"you could use the following:\nstart = [(0, 0), (1, 1)]\nresult = set()\n\nfor element in start:\n result.add(element)\n\nprint(result)\n\nAs everyone said, you can't have {1,1} or {0,0} since sets can't have repeated elements, But you can have the tuples as elements (the code I gave).\n"
] | [
0
] | [] | [] | [
"arrays",
"list",
"python"
] | stackoverflow_0074471303_arrays_list_python.txt |
Q:
ValueError: too many values to unpack (expected 2) when doing Djisktras algorithm?
I am getting the error when running the following code, its supposed to be a djikstras algorithm running over certain nodes and edges, with weights. But when trying to run I get an error.
nodes = ['0', '1', '2', '3', '4', '5', '6', ... | ValueError: too many values to unpack (expected 2) when doing Djisktras algorithm? | I am getting the error when running the following code, its supposed to be a djikstras algorithm running over certain nodes and edges, with weights. But when trying to run I get an error.
nodes = ['0', '1', '2', '3', '4', '5', '6', '7']
edges = {('0', '1'): 1, ('0', '4'): 1, ('0', '5'): 1, ('1', '2'): 0, ('2', '3'): 0... | [
"I might be wrong, but your code says\nshortest_path_lenghts, shortest_paths = dijkstra(nodes, edges)\n\nwhich means that it expect the function dijkstra to return two variables (shortest_path_lengths and shortest_paths).\nThe function itself seems to only return a single variable return path_lenghts\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074472201_python.txt |
Q:
Why does printing a tabulator not always print a tabulator but a space?
this might be a simple question but I haven't found a solution or a similar question yet.
When printing
print(str(n) + "\t" + str(abs(moved_nm.value)) + "\t" + str(truncate(diff_2, 2)) + "\t" + str(truncate(diff_abs, 2)))
It prints
3 999937... | Why does printing a tabulator not always print a tabulator but a space? | this might be a simple question but I haven't found a solution or a similar question yet.
When printing
print(str(n) + "\t" + str(abs(moved_nm.value)) + "\t" + str(truncate(diff_2, 2)) + "\t" + str(truncate(diff_abs, 2)))
It prints
3 9999375 9935347.98 64027.01
Why does the first \t print a tabulator while the res... | [
"It actually does print tabulators. The ASCII code of your string is:\n51 9 57 57 57 57 51 55 53 9 57 57 51 53 51 52 55 46 57 56 9 54 52 48 50 55 46 48 49 \n\n(you can check here)\nThe code for tabulator is 9 and your string contains 3 of them, 1 between each word.\nNote that a tabulator does not always appear to h... | [
4
] | [] | [] | [
"python",
"tabulator"
] | stackoverflow_0074472254_python_tabulator.txt |
Q:
Add loss in SRGAN
I want to add loss to SRGAN
https://github.com/leftthomas/SRGAN
in train.py
g_loss = generator_criterion(fake_out, fake_img, real_img)
Can I write a function myself like:
def ContentLoss(a, b):
result = 0
for x, y in zip(a, b):
shape = x.shape
k = np.prod(shape[0:])... | Add loss in SRGAN | I want to add loss to SRGAN
https://github.com/leftthomas/SRGAN
in train.py
g_loss = generator_criterion(fake_out, fake_img, real_img)
Can I write a function myself like:
def ContentLoss(a, b):
result = 0
for x, y in zip(a, b):
shape = x.shape
k = np.prod(shape[0:])
diff = x - y
... | [
"The project you linked uses PyTorch. Assuming that you are also using it, you can just implement your loss using PyTorch instead of numpy and your're covered.\nimport torch\nimport math\n\n\ndef ContentLoss(a, b):\n result = 0\n for x, y in zip(a, b):\n shape = x.shape\n k = math.prod(shape... | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074471691_python_pytorch.txt |
Q:
Is there a way to provide to a function more arguments than it needs?
I want to pass the element of the same dictionary to several functions with kwargs. The problem is that this dictionary contains more than the functions receive in their arguments list.
For example, lets say I have the following dictionary:
d = ... | Is there a way to provide to a function more arguments than it needs? | I want to pass the element of the same dictionary to several functions with kwargs. The problem is that this dictionary contains more than the functions receive in their arguments list.
For example, lets say I have the following dictionary:
d = dict(a=1,b=2,c=3)
Now, I'll use it in a function that receives the paramet... | [
"You can us *args and **kwargs for that.\nJust define your function with\ndef func(a, b, **kwargs):\n return a+b\n\nand it should work. Might be a quick and dirty solution, though... :-)\n"
] | [
2
] | [] | [] | [
"dictionary",
"keyword_argument",
"python"
] | stackoverflow_0074472302_dictionary_keyword_argument_python.txt |
Q:
Reading file and writing its content after replacing strings with new strings in python
I got this code below to test out but it doesn't work the way it's supposed to.
Note that I'm using MacM1 and use vscode as IDE.
fin = open("file.txt", "rt")
#output file to write the result to
fout = open("out.txt", "wt")
#f... | Reading file and writing its content after replacing strings with new strings in python | I got this code below to test out but it doesn't work the way it's supposed to.
Note that I'm using MacM1 and use vscode as IDE.
fin = open("file.txt", "rt")
#output file to write the result to
fout = open("out.txt", "wt")
#for each line in the input file
for line in fin:
#read replace the string and write to ou... | [
"\nYou should always use context manager for IO.\nopen with \"t\" is not necessary since t stands for text mode, which is default.\n\n# main.py\nwith open(\"file.txt\", \"r\") as fin, open(\"out.txt\", \"w\") as fout:\n for line in fin.readlines(): # using for line in fin also works\n fout.write(line.repl... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074471632_python.txt |
Q:
Constructing DataFrame from dict with rows instead of columns
I have a dict with the following setup:
{('CMS', 'LNT'): 0.8500276624334894,
('LNT', 'CMS'): 0.8500276624334894,
('LOW', 'HD'): 0.8502400376842035,
('HD', 'LOW'): 0.8502400376842036,
('SWKS', 'QRVO'): 0.8507993847326996,
('QRVO', 'SWKS'): 0.8507993... | Constructing DataFrame from dict with rows instead of columns | I have a dict with the following setup:
{('CMS', 'LNT'): 0.8500276624334894,
('LNT', 'CMS'): 0.8500276624334894,
('LOW', 'HD'): 0.8502400376842035,
('HD', 'LOW'): 0.8502400376842036,
('SWKS', 'QRVO'): 0.8507993847326996,
('QRVO', 'SWKS'): 0.8507993847326996,
('WFC', 'BAC'): 0.8510581675586776,
.....
Now I want t... | [
"You can use transpose:\ndata_results_1y=data_results_1y.T\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"pandas",
"python"
] | stackoverflow_0074472314_dictionary_pandas_python.txt |
Q:
getting error why scrapping data from twitter using the API
i was trying to use the function below functions for twitter data scrapping.
tweets_copy = []
for tweet in tqdm(tweets):
tweets_copy.append(tweet)
am getting the error below:
TweepError: Failed to send request: Only unicode objects are escapable. Got... | getting error why scrapping data from twitter using the API | i was trying to use the function below functions for twitter data scrapping.
tweets_copy = []
for tweet in tqdm(tweets):
tweets_copy.append(tweet)
am getting the error below:
TweepError: Failed to send request: Only unicode objects are escapable. Got None of type <class 'NoneType'>.
I will appreciate any help.
I t... | [
"Looks like you need to check for None, which the library can't handle\ntweets_copy = []\nfor tweet in tqdm(tweets):\n if tweet:\n tweets_copy.append(tweet)\n\nOr, alternatively, in comprehension style:\ntweets_copy = [t for t in tqdm(tweets) if t] \n\n"
] | [
1
] | [] | [] | [
"api",
"python",
"tweepy",
"twitterapi_python",
"web"
] | stackoverflow_0074472345_api_python_tweepy_twitterapi_python_web.txt |
Q:
Test of the sequence of calling of some methods of a Python class
I need to check the sequence of calling of some methods of a class.
I suppose that my production class A is stored in the following file class_a.py:
class A:
__lock = None
def __init__(self, lock):
self.__lock = lock
def method... | Test of the sequence of calling of some methods of a Python class | I need to check the sequence of calling of some methods of a class.
I suppose that my production class A is stored in the following file class_a.py:
class A:
__lock = None
def __init__(self, lock):
self.__lock = lock
def method_1(self):
self.__lock.acquire()
self.__atomic_method_1(... | [
"In the question's comments they said that it is not what unit tests are for. Yes, that makes for a brittle tests. But they serve a real use : do I correctly implement locking. You may want to refactor your class so that it is easier to test (and that would be another interesting question).\nBut if you really want ... | [
1,
1
] | [] | [] | [
"mocking",
"python",
"unit_testing"
] | stackoverflow_0074448113_mocking_python_unit_testing.txt |
Q:
How do I multiply two matrices in pyhton without numpy?
Implement a function mat_mult_by_transpose(mat) which gets a valid matrix
called mat and returns a new matrix which is the matrix multiplication of and (), i.e. () ⋅ ().
Return a new matrix, without modifying mat2.
You may assume that... | How do I multiply two matrices in pyhton without numpy? | Implement a function mat_mult_by_transpose(mat) which gets a valid matrix
called mat and returns a new matrix which is the matrix multiplication of and (), i.e. () ⋅ ().
Return a new matrix, without modifying mat2.
You may assume that the input matrix is not empty.
Example 1:
mat = [[1,2],[... | [
"Assuming your mat_transpose() works fine. Look at it in terms of dimensions.\nLet mat has dimension MxN \nHence M = len(mat) and N = len(mat[0])\nNow matT will have dimension NxM \nHence N = len(matT) and M = len(matT[0])\nYou need to traverse row of first matrix mat, i.e i ranges [0..M] \nthen column of second ma... | [
0
] | [] | [] | [
"for_loop",
"list",
"matrix_multiplication",
"python",
"transpose"
] | stackoverflow_0074472241_for_loop_list_matrix_multiplication_python_transpose.txt |
Q:
Named tuples existence in a hashset
In [1]: x = set()
In [2]: pos = collections.namedtuple('Position', ['x','y'])
In [4]: x.add(pos(1,1))
In [5]: x
Out[5]: {Position(x=1, y=1)}
In [6]: pos(1,1) in x
Out[6]: True
In [8]: pos(1,2) in x
Out[8]: False
I was not expecting Line 6 pos(1,1) in x to work. Since it does se... | Named tuples existence in a hashset | In [1]: x = set()
In [2]: pos = collections.namedtuple('Position', ['x','y'])
In [4]: x.add(pos(1,1))
In [5]: x
Out[5]: {Position(x=1, y=1)}
In [6]: pos(1,1) in x
Out[6]: True
In [8]: pos(1,2) in x
Out[8]: False
I was not expecting Line 6 pos(1,1) in x to work. Since it does seem that pos(1,1) creates an object with a... | [
"namedtuple is not special. The element should be exactly equal(__eq__) and must have similar hash to pass the containment test.\n>>> hash(pos(1, 1)) == hash(pos(1, 1))\nTrue\n>>> pos(1, 1) == pos(1, 1)\nTrue\n\nIf you are interested see the implementation here, set().__contains__(y) first have to compute the hash ... | [
6,
0
] | [] | [] | [
"python",
"python_2.7",
"python_2.x",
"python_3.6",
"python_3.x"
] | stackoverflow_0074472423_python_python_2.7_python_2.x_python_3.6_python_3.x.txt |
Q:
cannot click load more button with selenium
I'm trying to click load more button several times using selenium, however I cannot click load more button (it is even not a button...)
When I try to click it, it shows error element click intercepted: Element is not clickable at point even after I explicitly code wait.u... | cannot click load more button with selenium | I'm trying to click load more button several times using selenium, however I cannot click load more button (it is even not a button...)
When I try to click it, it shows error element click intercepted: Element is not clickable at point even after I explicitly code wait.until(EC.element_to_be_clickable)
I wonder what ca... | [
"This is somewhat tricky.\nThe \"Load more\" button is initially out of the screen here, so you need to scroll the page in order to click that button. But when you scroll this page it scrolls more than needed so the \"Load more\" button appears out of the screen again, so this time you will have to scroll back :)\n... | [
2,
1
] | [] | [] | [
"html",
"python",
"scroll",
"selenium",
"web_scraping"
] | stackoverflow_0074470419_html_python_scroll_selenium_web_scraping.txt |
Q:
Apply function to multiple columns of a groupby object
I have a dataframe that looks like -
block lat lon
0 0 112 50
1 0 112 50
2 0 112 50
3 1 105 20
4 1 105 20
5 2 130 30
and I want to first groupby block and then apply a function to the lat lon columns. eg
df... | Apply function to multiple columns of a groupby object | I have a dataframe that looks like -
block lat lon
0 0 112 50
1 0 112 50
2 0 112 50
3 1 105 20
4 1 105 20
5 2 130 30
and I want to first groupby block and then apply a function to the lat lon columns. eg
df['location_id'] = df.groupby('block').apply(lambda x: get_lo... | [
"Depending on how \"large\" your \"large\" Dataset is, there might be different solutions... And I'm not 100% certain you can (or should) do what you want with groupby. I'd suggest (and I'm relatively sure that it will work even in distributed environments) to do the following:\n\nCreate a new dataframe with non-du... | [
1
] | [] | [] | [
"group_by",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074471787_group_by_pandas_python_python_3.x.txt |
Q:
Run host machine program from python docker
Actually, I have a little python server (using fastapi but it's not important) that start a program like that:
@app.put("/start_simulation/")
async def start_simulation():
try:
Process = subprocess.Popen("Aimsun_Next.exe")
except Exception as e:
raise HTTPExcepti... | Run host machine program from python docker | Actually, I have a little python server (using fastapi but it's not important) that start a program like that:
@app.put("/start_simulation/")
async def start_simulation():
try:
Process = subprocess.Popen("Aimsun_Next.exe")
except Exception as e:
raise HTTPException(status_code=500, detail="Simulation process fa... | [
"In your dockerfile you should indicate that you want to expose the FastAPI port. Something like EXPOSE 8000. See documentation.\nWhen you start the container you have to publish the port to localhost docker run -p 8000:8080.\nIt's possible to access a file on your local filesystem from your container, by \"mounti... | [
1
] | [] | [] | [
"docker",
"docker_machine",
"dockerfile",
"python"
] | stackoverflow_0074472231_docker_docker_machine_dockerfile_python.txt |
Q:
How to have text next to an arrow in tkinter
I am trying to draw an arrow in python's tkinter package which has text written along the arrow. How does one do this? I haven't found a method online
A:
Here is an example by using a Canvas
import numpy as np
from tkinter import *
# Calculation from https://stackove... | How to have text next to an arrow in tkinter | I am trying to draw an arrow in python's tkinter package which has text written along the arrow. How does one do this? I haven't found a method online
| [
"Here is an example by using a Canvas\nimport numpy as np\nfrom tkinter import *\n\n\n# Calculation from https://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python\ndef calc_angle(x1, y1, x2, y2):\n p0 = [x1, y1]\n p1 = [x2, y2]\n p2 = [0, y2]\n\n ''' \n compute an... | [
1
] | [] | [] | [
"python",
"tkinter",
"tkinter_canvas",
"tkinter_text"
] | stackoverflow_0074471930_python_tkinter_tkinter_canvas_tkinter_text.txt |
Q:
Rewriting a string and removing unwanted elements in python
I use the python library Nvdlib which aims to extract information from Nist. Among these informations, I'm interested in the CPE and especially the api output.
Here is my code :
import nvdlib
r = nvdlib.searchCVE(cveId='CVE-2019-19781')[0]
conf = r.confi... | Rewriting a string and removing unwanted elements in python | I use the python library Nvdlib which aims to extract information from Nist. Among these informations, I'm interested in the CPE and especially the api output.
Here is my code :
import nvdlib
r = nvdlib.searchCVE(cveId='CVE-2019-19781')[0]
conf = r.configurations #list in ouput
for x in conf:
txt = ', '.join(str... | [
"Thanks to everyone for your answers, I managed to make a mix of a bit of everything you sent me and here is the final code that allows me to list all the cpe\nimport nvdlib\nimport re\n\nr = nvdlib.searchCVE(cveId='CVE-2019-19781')[0]\n\nconf = r.configurations #output = list\n\nfor x in conf:\ntxt = ', '.join(str... | [
0,
0
] | [
"I think it's quite hard to delete everything in the string because you can't foresee what's going to be inside the string in future. But then you can spot the pattern which is to find for the cpe substring.\nSimply just add this, for every loop you look for the substring and then do some slicing, splitting and als... | [
-1
] | [
"python",
"python_3.x"
] | stackoverflow_0074471657_python_python_3.x.txt |
Q:
removing nan from the datetime np.array: array extracted from datetime column with unique values
I have following list has two values one is datetime.datetime(2018-06-18) and another NaN. both are extracted from the datetime column unique values . I just want list only contain the date.
# extracting date from date... | removing nan from the datetime np.array: array extracted from datetime column with unique values | I have following list has two values one is datetime.datetime(2018-06-18) and another NaN. both are extracted from the datetime column unique values . I just want list only contain the date.
# extracting date from datetime column
main_df['date'] = main_df.DateTime.dt.date
# getting only unique values from date column... | [
"you can use pd.isnull check instead (borrowing from this answer):\nimport datetime\nimport numpy as np\nimport pandas as pd\n\n# np.isfinite(pd.NaT), np.isnan(pd.NaT)\n# -> TypeError !\n\narr = np.array([datetime.date(2018, 6, 18), pd.NaT])\n\narr = arr[~pd.isnull(arr)]\n# array([datetime.date(2018, 6, 18)], dtype... | [
0
] | [] | [] | [
"arrays",
"datetime",
"pandas",
"python"
] | stackoverflow_0074471513_arrays_datetime_pandas_python.txt |
Q:
Python: take email_list and remove duplicate usernames, append to new update_list?
How do you take an email_list with emails in the format first.last@domain.com and append unique names to a new update_list? I would use this update_list and convert it to CamelCase, but I'm not sure how to take only part of an index... | Python: take email_list and remove duplicate usernames, append to new update_list? | How do you take an email_list with emails in the format first.last@domain.com and append unique names to a new update_list? I would use this update_list and convert it to CamelCase, but I'm not sure how to take only part of an index to search for duplicates. Is there some way to use regex? Keep getting TpeError: expect... | [
"This should work... I actually didn't end up using regex at all and just stuck to string methods to split the email address and convert it to camel case...\nI also did some minor cleanups through the rest of your script as well mostly just removing unnecessary lines.\nemail_list = []\ndup_email_list = []\ndomain_g... | [
0,
0
] | [] | [] | [
"email",
"format",
"input",
"python",
"string"
] | stackoverflow_0074470410_email_format_input_python_string.txt |
Q:
How to set up a waiting point for Tkinter
I try to make a little gui with tkinter to improuve mental calculation. In my program, tkinter ask 10 question and the program should wait the good or bad answer before show the next question but I don't now how to wait properly
here is my code:
class PageAdd1(tk.Frame):
... | How to set up a waiting point for Tkinter | I try to make a little gui with tkinter to improuve mental calculation. In my program, tkinter ask 10 question and the program should wait the good or bad answer before show the next question but I don't now how to wait properly
here is my code:
class PageAdd1(tk.Frame):
def __init__(self, parent, controller):
... | [
"I created a minimum case that fits your needs\nimport tkinter as tk\n\nfrom tkinter import ttk\n\n\nmainwindow = tk.Tk()\nrow = 0\n\n\ndef validation(widget,value,number1,number2):\n result = int(number1) + int(number2)\n if(value.isnumeric() and int(value) == result):\n addLayer(int(number1),int(number2)... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074467479_python_tkinter.txt |
Q:
Optimize string split to get a pandas dataframe
I am extracting data from a large pdf file using regex using python in databricks. This data is in form of a long string and I am using string split function to convert this into a pandas dataframe as I want the final data as csv file. But while doing line.split comm... | Optimize string split to get a pandas dataframe | I am extracting data from a large pdf file using regex using python in databricks. This data is in form of a long string and I am using string split function to convert this into a pandas dataframe as I want the final data as csv file. But while doing line.split command it takes about 5 hours for the command to run and... | [
"There are 2 immediate optimization steps in your code.\n\nPre-compile regex if they are used many times. It may or not be relevant here, because I could not guess how many times table_lines = re.findall(regex_date, extracted_string) is executed. But this if often more efficient:\n # before any loop\n regex_date = ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074472559_python.txt |
Q:
Unable to create Group (no write intent on file)
I got this error everytime I load my model back from an HDF5 file. Below is my error trace.
Traceback (most recent call last):
File "D:\Anaconda3New\Datasets\train.py", line 63, in <module>
model = load_model(args["model"])
File "D:\Anaconda3New\lib\site-pac... | Unable to create Group (no write intent on file) | I got this error everytime I load my model back from an HDF5 file. Below is my error trace.
Traceback (most recent call last):
File "D:\Anaconda3New\Datasets\train.py", line 63, in <module>
model = load_model(args["model"])
File "D:\Anaconda3New\lib\site-packages\keras\engine\saving.py", line 419, in
load_model... | [
"See there are two ways of saving a model. A:-\nmodel.save(\"Model_name.model\")\nand B:-\nmodel_json = model.to_json()\nwith open(file_name + \".json\", \"w\") as json_file:\n json_file.write(model_json)\nmodel.save_weights(file_name + '.h5')\n\nI believe you were saving the model using the first method and... | [
2,
0
] | [] | [] | [
"h5py",
"python"
] | stackoverflow_0057131048_h5py_python.txt |
Q:
ImportError: MemoryLoadLibrary failed loading win32crypt.pyd: The specified module could not be found. (126)
After creating an exe of a script (the script was working on its own) with py2exe I got the following error:
Traceback (most recent call last):
File "script.py", line 3, in <module>
File "zipextimporter... | ImportError: MemoryLoadLibrary failed loading win32crypt.pyd: The specified module could not be found. (126) | After creating an exe of a script (the script was working on its own) with py2exe I got the following error:
Traceback (most recent call last):
File "script.py", line 3, in <module>
File "zipextimporter.pyc", line 167, in exec_module
File "src\import_clixml.pyc", line 1, in <module>
File "zipextimporter.pyc", l... | [
"For some unexplicable reason, adding import pandas to the script makes the created exe work correctly, even though the modules should have no effect on each other.\n",
"same question as Py2exe - win32api.pyc ImportError DLL load failed.\nlook at setup.py, just excludes these dlls which are included in the system... | [
0,
0
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0074472620_py2exe_python.txt |
Q:
Removing line break and writing lists without square brackets and comas to a text file in python
I'm facing a few issues with regard to writing some arguments to a text file. Below are the outputs I need to see in my text file.
I want to write an output like this to the text file.
Input:
Hello
World
Output:
He... | Removing line break and writing lists without square brackets and comas to a text file in python | I'm facing a few issues with regard to writing some arguments to a text file. Below are the outputs I need to see in my text file.
I want to write an output like this to the text file.
Input:
Hello
World
Output:
HelloWorld
2. I want to write an output like this into a text file.
Input:
[1, 2, 3, 4, 5]
Output:
1,2... | [
"1st case would be something like this\n>>> s = '''hello\n... world'''\n>>> ''.join(s.split())\n'helloworld'\n>>>\n\n2nd one is funny\n>>> s = \"[1, 2, 3, 4, 5]\"\n>>> exec ('a = ' + s)\n>>> ','.join([str(i) for i in a])\n'1,2,3,4,5'\n\nhope it helps\n"
] | [
0
] | [] | [] | [
"list",
"python",
"python_3.x",
"writetofile"
] | stackoverflow_0074472553_list_python_python_3.x_writetofile.txt |
Q:
Invalid command 'bdist_msi' when trying to create MSI installer with 'cx_Freeze'
I am trying to create MSI installer for Windows with cx_Freeze package. Anyway, when running command python setup.py bdist_msi I get an error that it is invalid. Is there any options I am missing or maybe I cannot use it on Linux (I a... | Invalid command 'bdist_msi' when trying to create MSI installer with 'cx_Freeze' | I am trying to create MSI installer for Windows with cx_Freeze package. Anyway, when running command python setup.py bdist_msi I get an error that it is invalid. Is there any options I am missing or maybe I cannot use it on Linux (I am using Debian 11)?
import sys
from pathlib import Path
from cx_Freeze import setup, E... | [
"According to this section of cx_Freeze documentation cross compilation is indeed not possible. At least in the usual way.\n\ncx_Freeze works on Windows, Mac and Linux, but on each platform it\nonly makes an executable that runs on that platform. So if you want to\nfreeze your programs for Windows, freeze it on Win... | [
0
] | [] | [] | [
"python",
"windows_installer"
] | stackoverflow_0074375195_python_windows_installer.txt |
Q:
Error loading YOLOv5 in opencv python, how to solve?
I am trying to run people detection from above in opencv with YOLOv5, and I have problems with loading the model. My version of opencv is 4.6.0, and following the tutorial at this link I wrote this code
# hyper parameters
INPUT_WIDTH = 640 # width of the input ... | Error loading YOLOv5 in opencv python, how to solve? | I am trying to run people detection from above in opencv with YOLOv5, and I have problems with loading the model. My version of opencv is 4.6.0, and following the tutorial at this link I wrote this code
# hyper parameters
INPUT_WIDTH = 640 # width of the input for the YOLOv5 network
INPUT_HEIGHT = 640 # height of the... | [
"Taking a close look at the outputs shape, it was found to be [1, 3, 80, 80, 85]. Whereas, it should be [25200x85] for default 640x640 onnx exports. It appears to be a buggy conversion from PyTorch to ONNX. In yolov5s.onnx model has been updated in the article.\nMoreover, torch==1.12 has some bugs. Until it is fixe... | [
3,
1
] | [] | [] | [
"computer_vision",
"opencv",
"python",
"python_3.x",
"yolov5"
] | stackoverflow_0072832585_computer_vision_opencv_python_python_3.x_yolov5.txt |
Q:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your syntax
I am attempting to insert data into a MySQL database.
My error is:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for ... | mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your syntax | I am attempting to insert data into a MySQL database.
My error is:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"(timestamp,machineID,verbrauch)" "VALUES (%s,%s,%s)", (datetim... | [] | [] | [
"replace:\n'''INSERT into verbrauch \"(timestamp,machineID,verbrauch)\" \"VALUES (%s,%s,%s)\", (datetime.datetime.now(), 'ID_machinen[\"machine_1\"]', value)'''\n\nwith:\nf\"\"\"INSERT INTO verbrauch (timestamp, machineID, verbrauch) VALUES ({datetime.datetime.now()}', {ID_machinen[\"machine_1\"]}, {value})\"\"\"\n... | [
-1
] | [
"mysql",
"mysql_connector",
"python"
] | stackoverflow_0074472783_mysql_mysql_connector_python.txt |
Q:
List elements to dictionary based on condition
I have a list that has the keys and values of a dictionary as elements. I want to change it into a dictionary. Any help would be appreciated. I am new to programming.
List=[key1,key2,value2,value2,key3,value3,value3,key4,value4]
I want to change it into:
dict={key1:[... | List elements to dictionary based on condition | I have a list that has the keys and values of a dictionary as elements. I want to change it into a dictionary. Any help would be appreciated. I am new to programming.
List=[key1,key2,value2,value2,key3,value3,value3,key4,value4]
I want to change it into:
dict={key1:[],key2:[value2,value2],key3:[value3,value3],key4:[va... | [
"You must take elements from the initial list one at a time. If an element has the 'key' string inside it, then add a new item to the dictionary with an empty list as value, and retain that current list. Else, add the element to the current list. Possible code:\nlst = ['key1', 'key2', 'value2', 'value2', 'key3', 'v... | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074472578_dictionary_list_python.txt |
Q:
How to print index of for loop in FOLIUM MAP (Python)?
I am writing the following Python code to print numbers beside Folium ICON. I need these indices to be dynamic, meaning, I have a for loop, I want index value to be printed in the HTML line of the code.
for point in range(0, len(coordinates_st)):
# showing... | How to print index of for loop in FOLIUM MAP (Python)? | I am writing the following Python code to print numbers beside Folium ICON. I need these indices to be dynamic, meaning, I have a for loop, I want index value to be printed in the HTML line of the code.
for point in range(0, len(coordinates_st)):
# showing number
folium.Marker(location=[72.89, -124.59+2], icon=... | [
"In this case, the index can be displayed using f-string notation. Since the data is not presented, we can use geopandas data to display the usual markers for the cities of the world, with the index next to them.\ncharacters.\nimport folium\nimport geopandas as gpd\n\ngeo_df = gpd.read_file(gpd.datasets.get_path('n... | [
0
] | [] | [] | [
"folium",
"gis",
"modeling",
"python"
] | stackoverflow_0074471384_folium_gis_modeling_python.txt |
Q:
Difference between ViewSet and GenericViewSet in Django rest framework
I have a Django rest framework GenericViewset for which I am trying to set up pagination as follows:
#settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20... | Difference between ViewSet and GenericViewSet in Django rest framework | I have a Django rest framework GenericViewset for which I am trying to set up pagination as follows:
#settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20
}
#views.py
class PolicyViewSet(viewsets.GenericViewSet):
def list(sel... | [
"\nPagination is only performed automatically if you're using the generic\n views or viewsets\n\nRead the docs\nAnd to answer your second question What is the difference between a GenericViewset and Viewset in DRF\nDRF has two main systems for handling views:\n\nAPIView: This provides some handler methods, to han... | [
25,
1,
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_rest_viewsets",
"python"
] | stackoverflow_0054702823_django_django_rest_framework_django_rest_viewsets_python.txt |
Q:
Argument bottleneck python multiprocessing
I am using pool.apply_async to parallelize my code. One of the arguments I am passing in is a set that I have stored in memory. Given I am passing in a pointer to the set (rather than the set itself) does multiprocessing make copies of the set for each CPU or is the same ... | Argument bottleneck python multiprocessing | I am using pool.apply_async to parallelize my code. One of the arguments I am passing in is a set that I have stored in memory. Given I am passing in a pointer to the set (rather than the set itself) does multiprocessing make copies of the set for each CPU or is the same reference passed to each CPU? I assume that give... | [
"So in principle, if you create tasks for new processes, the data has to be copied over to the new processes, as the processes don't share memory (compared to threads). The details vary a bit from Operating System to Operating System (i.e. fork vs spawn) but in general the data has to be copied over.\nWhether that ... | [
1
] | [] | [] | [
"multiprocessing",
"python",
"python_3.x",
"python_multiprocessing"
] | stackoverflow_0074449967_multiprocessing_python_python_3.x_python_multiprocessing.txt |
Q:
How to save result of for loop in existing input dataframe
My input data frame df is below
external_id
sw_1
sw_2
sw_3
Sw_55
and my output data frame output_df should be
external_id : Status
sw_1 :Hello Sw_1
sw_2 :Hello sw_2
sw_3 :hello sw_3
Sw_55 :Hello sw_55
Till now I have done this. Able to create new df fo... | How to save result of for loop in existing input dataframe | My input data frame df is below
external_id
sw_1
sw_2
sw_3
Sw_55
and my output data frame output_df should be
external_id : Status
sw_1 :Hello Sw_1
sw_2 :Hello sw_2
sw_3 :hello sw_3
Sw_55 :Hello sw_55
Till now I have done this. Able to create new df for for loop output only.
I want to store for loop result in exist... | [
"It is really still not clear to me what you want to achieve or how you get results of your API, since it just doesn't appear in your code example, but maybe this helps.\nYour Input is called df. In your code you make a copy and name it output_df but then you never use it. The new created list will be assigned to d... | [
0
] | [] | [] | [
"api",
"aws_glue",
"python"
] | stackoverflow_0074472110_api_aws_glue_python.txt |
Q:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte. How to fix it
When I run this code I get an error:
print(data.decode("utf-8"))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
My code:
import http.client
import json
from dot... | UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte. How to fix it | When I run this code I get an error:
print(data.decode("utf-8"))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
My code:
import http.client
import json
from dotenv import load_dotenv
import os
load_dotenv()
conn = http.client.HTTPSConnection("api.remove.bg")
apikey = o... | [
"According to their API documentation, the response content is the result image. So you shouldn't try to decode it like it was text.\nJust do with open(\"image.png\", \"w\") as file: file.write(data).\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074460445_python.txt |
Q:
How can I create protobuffer from .proto file in python files using cmake?
I am using python language for my server in gRPC now I need to create the prpto files from cmake as my client in gRPC is written in c++ I have to run this command in CMAkeLISTS.txt file but when I try to run It , no file is created:
python3... | How can I create protobuffer from .proto file in python files using cmake? | I am using python language for my server in gRPC now I need to create the prpto files from cmake as my client in gRPC is written in c++ I have to run this command in CMAkeLISTS.txt file but when I try to run It , no file is created:
python3 -m grpc_tools.protoc -I ../protos --python_out=. --
pyi_out=. --grpc_python_ou... | [
"Removing\nset(_GRPC_PY_TOOL $<TARGET_FILE:gRPC::grpc_tools::protoc>)\n\nand\n\"${_GRPC_PY_TOOL}\" \n\nfrom add_custom_command and write it like :\nadd_custom_command(\nOUTPUT \"${hw_grpc_src_py}\" \"${hw_proto_src_py}\" \"${hw_proto_src_pyi}\"\nCOMMAND python3 \n ARGS -m grpc_tools.protoc\n-I \"${hw_proto_path}\"... | [
1
] | [] | [] | [
"cmake",
"grpc",
"protocol_buffers",
"python"
] | stackoverflow_0074464446_cmake_grpc_protocol_buffers_python.txt |
Q:
Mean value of each element in multiple lists - Python
If I have two lists
a = [2,5,1,9]
b = [4,9,5,10]
How can I find the mean value of each element, so that the resultant list would be:
[3,7,3,9.5]
A:
>>> a = [2,5,1,9]
>>> b = [4,9,5,10]
>>> [(g + h) / 2 for g, h in zip(a, b)]
[3.0, 7.0, 3.0, 9.5]
A:
Referri... | Mean value of each element in multiple lists - Python | If I have two lists
a = [2,5,1,9]
b = [4,9,5,10]
How can I find the mean value of each element, so that the resultant list would be:
[3,7,3,9.5]
| [
">>> a = [2,5,1,9]\n>>> b = [4,9,5,10]\n>>> [(g + h) / 2 for g, h in zip(a, b)]\n[3.0, 7.0, 3.0, 9.5]\n\n",
"Referring to your title of the question, you can achieve this simply with:\nimport numpy as np\n\nmultiple_lists = [[2,5,1,9], [4,9,5,10]]\narrays = [np.array(x) for x in multiple_lists]\n[np.mean(k) for k... | [
15,
10,
6,
1,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0043436044_python_python_2.7.txt |
Q:
writing pandas dataframe with Nested structure to DynamoDB using Python and AWS Lambda
I am trying to write the Pandas dataframe to DynamoDB table. This Frame have nested objects
{
"PK": {
"S": "2"
},
"SK": {
"S": "INFO"
},
"001": {
"M": {
"New_Some": {
"N": "6"
},
"... | writing pandas dataframe with Nested structure to DynamoDB using Python and AWS Lambda | I am trying to write the Pandas dataframe to DynamoDB table. This Frame have nested objects
{
"PK": {
"S": "2"
},
"SK": {
"S": "INFO"
},
"001": {
"M": {
"New_Some": {
"N": "6"
},
"New_Some1": {
"N": "2"
},
"New_Some2": {
"N": "1"
},
... | [
"My suggestion would be to use AWS Glue instead of Lambda which has a built in DynamoDB connector that will allow you to read from S3 and directly write to DynamoDB.\nhttps://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-connect.html#aws-glue-programming-etl-connect-dynamodb\nHowever if you must use L... | [
1
] | [] | [] | [
"amazon_dynamodb",
"amazon_web_services",
"aws_lambda",
"pandas",
"python"
] | stackoverflow_0074469273_amazon_dynamodb_amazon_web_services_aws_lambda_pandas_python.txt |
Q:
Identifying rows with same positive and negative values with particular order in pandas dataframe
I am looking for an efficient way to flag the order as returned when there is both positive and negative entry present in data given negative entry is only present at the same day or later date from positive value.
im... | Identifying rows with same positive and negative values with particular order in pandas dataframe | I am looking for an efficient way to flag the order as returned when there is both positive and negative entry present in data given negative entry is only present at the same day or later date from positive value.
import pandas as pd
import datetime
data = [['US', '100', 'Ven1', datetime.datetime(2020, 5, 17), -100],... | [
"You can create groups with the same absolute qty and then apply your logic:\nimport pandas as pd\nimport datetime\n\ndata = [['US', '100', 'Ven1', datetime.datetime(2020, 5, 17), -100],\n ['US', '100', 'Ven1', datetime.datetime(2020, 5, 19), 100],\n ['US', '100', 'Ven1', datetime.datetime(2020, 5, 25... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074461217_dataframe_pandas_python_python_3.x.txt |
Q:
Kivy pip subprocess to install build dependencies did not run successfully
When I try to pip install kivy on my windows 10 cmd prompt, I get this error
Collecting kivy
Using cached Kivy-2.1.0.tar.gz (23.8 MB)
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to i... | Kivy pip subprocess to install build dependencies did not run successfully | When I try to pip install kivy on my windows 10 cmd prompt, I get this error
Collecting kivy
Using cached Kivy-2.1.0.tar.gz (23.8 MB)
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> [10 l... | [
"Kivy is currently unavailable for python 3.11, it works just fine when using 3.10.8.. use an older version of python while waiting for them to be available.\n"
] | [
0
] | [] | [] | [
"kivy",
"pip",
"python"
] | stackoverflow_0074381525_kivy_pip_python.txt |
Q:
How to verify Shopify webhook in Django?
How can I verify the incoming webhook from Shopify? Shopify provides a python implementation (of Flask), but how can I do it in Django/DRF?
A:
Set these two variables in the settings.py file
# settings.py
SHOPIFY_HMAC_HEADER = "HTTP_X_SHOPIFY_HMAC_SHA256"
SHOPIFY_API_SEC... | How to verify Shopify webhook in Django? | How can I verify the incoming webhook from Shopify? Shopify provides a python implementation (of Flask), but how can I do it in Django/DRF?
| [
"Set these two variables in the settings.py file\n# settings.py\n\nSHOPIFY_HMAC_HEADER = \"HTTP_X_SHOPIFY_HMAC_SHA256\"\nSHOPIFY_API_SECRET = \"5f6b6_my_secret\"\n\nThen, create a verify webhook function that accepts the Django request as it's parameter\n# utils.py\n\nimport base64\nimport hashlib\nimport hmac\n\nf... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"shopify",
"webhooks"
] | stackoverflow_0074473086_django_django_rest_framework_python_shopify_webhooks.txt |
Q:
Unable to perform user registration with Facebook using allauth and django-rest-auth. getting incorrect value error
I am trying to implement social authentication, I am using django-allauth, django-rest-auth for this.
my views
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from al... | Unable to perform user registration with Facebook using allauth and django-rest-auth. getting incorrect value error | I am trying to implement social authentication, I am using django-allauth, django-rest-auth for this.
my views
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
class FacebookLoginView(SocialLoginView):
adapter_cl... | [
"Edited: Most of cases issues should be coming from using a wrong APP ID. Make sure the access_token belong to you app\n"
] | [
1
] | [] | [] | [
"dj_rest_auth",
"django",
"django_allauth",
"django_rest_auth",
"python"
] | stackoverflow_0074472933_dj_rest_auth_django_django_allauth_django_rest_auth_python.txt |
Q:
Splitting Dataset into train and test tensorflow
I have a csv file (280 MB) which I load into tensorflow using the following code:
import tensorflow as tf
data = tf.data.experimental.make_csv_dataset("flight_2018.csv",
batch_size = 1000,
... | Splitting Dataset into train and test tensorflow | I have a csv file (280 MB) which I load into tensorflow using the following code:
import tensorflow as tf
data = tf.data.experimental.make_csv_dataset("flight_2018.csv",
batch_size = 1000,
label_name="Cancelled",
... | [
"As the type of your data is tensorflow.python.data.ops.dataset_ops.PrefetchDataset you can use the take and skip methods to split the data.\ntrain_data=data.take(160)\ntest_data=data.skip(160)\n\nKindly refer to this gist. Thank you!\n"
] | [
0
] | [] | [] | [
"python",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0074329114_python_tensorflow_tensorflow2.0.txt |
Q:
Php exec() python file no error no resspond
I run test.php on apache by xampp, exec() is not working, no error and no respond, test.py is not getting executed. please help , Thank you.
I have
test.php
exec("C:\Users\Json\AppData\Local\Microsoft\WindowsApps\python.exe C:\xampp\htdocs\app\test.py 2>&1", $output);
pr... | Php exec() python file no error no resspond | I run test.php on apache by xampp, exec() is not working, no error and no respond, test.py is not getting executed. please help , Thank you.
I have
test.php
exec("C:\Users\Json\AppData\Local\Microsoft\WindowsApps\python.exe C:\xampp\htdocs\app\test.py 2>&1", $output);
print_r($output)
test.py
import os
os.system("star... | [
"Backslashes will have to be escaped within the path.\nSo you will have to write it like this:\nexec(\"C:\\\\Users\\\\Json\\\\AppData\\\\Local\\\\Microsoft\\\\WindowsApps\\\\python.exe C:\\\\xampp\\\\htdocs\\\\app\\\\test.py 2>&1\", $output);\nprint_r($output);\n\n"
] | [
0
] | [] | [] | [
"php",
"python",
"windows",
"xampp"
] | stackoverflow_0074472710_php_python_windows_xampp.txt |
Q:
How to filter queryset less than 60 months ago?
models.py
class Preschooler(Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
birthday = models.DateField(null=True, blank=True)
def age_months(self):
today = date.today()
date_diff = t... | How to filter queryset less than 60 months ago? | models.py
class Preschooler(Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
birthday = models.DateField(null=True, blank=True)
def age_months(self):
today = date.today()
date_diff = today - self.birthday
in_days = date_diff.days... | [
"You can use Python relativedelta with datetime.today() [Python-doc] so:\nfrom datetime import datetime\n\nfrom dateutil.relativedelta import relativedelta \nless_than_60_mon = datetime.today() - relativedelta(months=60)\n \nPreschooler.objects.filter(birthday__lt=less_than_60_mon)\n\n"
] | [
2
] | [] | [] | [
"django",
"django_filter",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0074472904_django_django_filter_django_models_django_queryset_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.