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:
TypeError: Can't instantiate abstract class <...> with abstract methods
Here is my code:
from abc import ABC
from abc import abstractmethod
class Mamifiero(ABC):
"""docstring for Mamifiero"""
def __init__(self):
self.alimentacion = 'carnivoro'
@abstractmethod
def __respirar(self):
print('inhalar... exhalar')
class Perro(Mamifiero):
"""docstring for Perro"""
def __init__(self, ojos=2,):
self.ojos = ojos
I want that perro.respirar() prints 'inhalar... exhalar' but when I want to instantiate a Perro class show me this error. I want to know what is wrong with my script
A:
By definition (read the docs), an abstract call is a class which CANNOT be instantiated until it has any abstract methods not overridden. So as in the Object-Oriented Programming by design.
You have an abstract method Perro.__respirar() not overridden, as inherited from the parent class. Or, override it with a method Perro.__respirar(), and do something there (maybe even call the parent's method; but not in case it is private with double-underscore, of course).
If you want to instantiate Perro, just do not make that method abstract. Make it normal. Because it also has some implementation, which suggests it is a normal base-class'es method, not an abstract method.
A:
You need to override __respirar() abstract method in Perro class as shown below:
from abc import ABC
from abc import abstractmethod
class Mamifiero(ABC):
"""docstring for Mamifiero"""
def __init__(self):
self.alimentacion = 'carnivoro'
@abstractmethod
def __respirar(self):
print('inhalar... exhalar')
class Perro(Mamifiero):
"""docstring for Perro"""
def __init__(self, ojos=2,):
self.ojos = ojos
# You need to override
def __respirar(self):
print('Hello')
|
TypeError: Can't instantiate abstract class <...> with abstract methods
|
Here is my code:
from abc import ABC
from abc import abstractmethod
class Mamifiero(ABC):
"""docstring for Mamifiero"""
def __init__(self):
self.alimentacion = 'carnivoro'
@abstractmethod
def __respirar(self):
print('inhalar... exhalar')
class Perro(Mamifiero):
"""docstring for Perro"""
def __init__(self, ojos=2,):
self.ojos = ojos
I want that perro.respirar() prints 'inhalar... exhalar' but when I want to instantiate a Perro class show me this error. I want to know what is wrong with my script
|
[
"By definition (read the docs), an abstract call is a class which CANNOT be instantiated until it has any abstract methods not overridden. So as in the Object-Oriented Programming by design.\nYou have an abstract method Perro.__respirar() not overridden, as inherited from the parent class. Or, override it with a method Perro.__respirar(), and do something there (maybe even call the parent's method; but not in case it is private with double-underscore, of course).\nIf you want to instantiate Perro, just do not make that method abstract. Make it normal. Because it also has some implementation, which suggests it is a normal base-class'es method, not an abstract method.\n",
"You need to override __respirar() abstract method in Perro class as shown below:\nfrom abc import ABC\nfrom abc import abstractmethod\n\nclass Mamifiero(ABC):\n \"\"\"docstring for Mamifiero\"\"\"\n def __init__(self):\n self.alimentacion = 'carnivoro'\n \n @abstractmethod\n def __respirar(self):\n print('inhalar... exhalar')\n \nclass Perro(Mamifiero):\n \"\"\"docstring for Perro\"\"\"\n def __init__(self, ojos=2,):\n self.ojos = ojos\n \n # You need to override\n def __respirar(self):\n print('Hello')\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"abstract_class",
"abstract_methods",
"python",
"python_2.7",
"python_3.x"
] |
stackoverflow_0046505037_abstract_class_abstract_methods_python_python_2.7_python_3.x.txt
|
Q:
Creating and saving a gif in python
I have this code, that makes many plots of a trajectory defined by x, y and z. How do i make a gif out of all of those plots? Right now all I've been able to achieve is saving all n plots on my hard drive and using third party software to make them into a gif.
for t in range(len(theta)):
fig = plt.figure('Parametrinai blynai')
ax = fig.add_subplot(111, projection='3d')
ax.plot(x[1:t], y[1:t], z[1:t], '-r', linewidth=3)
ax.set_xlabel('X', fontweight='bold', fontsize=14)
ax.set_ylabel('Y', fontweight='bold', fontsize=14)
ax.set_zlabel('Z', fontweight='bold', fontsize=14)
ax.set_xlim([-20, 20])
ax.set_ylim([-20, 20])
ax.set_zlim([-10, 10])
plt.title('Parametrinis blynas', fontweight='bold', fontsize=16)
ax.quiver(x[t - 1], y[t - 1], z[t - 1], emp * T[t, 0], emp * T[t, 1], emp * T[t, 2], color='k')
ax.quiver(x[t - 1], y[t - 1], z[t - 1], emp * B[t, 0], emp * B[t, 1], emp * B[t, 2], color='b')
ax.quiver(x[t - 1], y[t - 1], z[t - 1], emp * N[t, 0], emp * N[t, 1], emp * N[t, 2], color='g')
pavadinimas = str(t)
plt.savefig(pavadinimas, dpi=300)
A:
I'm not near a machine to test, but you should be able to save the matplotlib figure into an io.BytesIO, i.e. a memory buffer, rewind it and open it as a PIL Image. You can then accumulate the PIL Images in a list and pass them to the save() function of PIL to write a GIF.
Untested, but something like:
from io import BytesIO
from PIL import Image
imlist = []
for ...
...
... your code
...
# Make in memory buffer and save fig into it
buf = BytesIO()
plt.savefig(buf) # you may need "PNG" as type here
buf.seek(0)
im = Image.open(buf)
imlist.append(im)
# Save list of images as animated GIF
imlist[0].save('animated.gif', save_all=True, append_images=imlist[1:])
|
Creating and saving a gif in python
|
I have this code, that makes many plots of a trajectory defined by x, y and z. How do i make a gif out of all of those plots? Right now all I've been able to achieve is saving all n plots on my hard drive and using third party software to make them into a gif.
for t in range(len(theta)):
fig = plt.figure('Parametrinai blynai')
ax = fig.add_subplot(111, projection='3d')
ax.plot(x[1:t], y[1:t], z[1:t], '-r', linewidth=3)
ax.set_xlabel('X', fontweight='bold', fontsize=14)
ax.set_ylabel('Y', fontweight='bold', fontsize=14)
ax.set_zlabel('Z', fontweight='bold', fontsize=14)
ax.set_xlim([-20, 20])
ax.set_ylim([-20, 20])
ax.set_zlim([-10, 10])
plt.title('Parametrinis blynas', fontweight='bold', fontsize=16)
ax.quiver(x[t - 1], y[t - 1], z[t - 1], emp * T[t, 0], emp * T[t, 1], emp * T[t, 2], color='k')
ax.quiver(x[t - 1], y[t - 1], z[t - 1], emp * B[t, 0], emp * B[t, 1], emp * B[t, 2], color='b')
ax.quiver(x[t - 1], y[t - 1], z[t - 1], emp * N[t, 0], emp * N[t, 1], emp * N[t, 2], color='g')
pavadinimas = str(t)
plt.savefig(pavadinimas, dpi=300)
|
[
"I'm not near a machine to test, but you should be able to save the matplotlib figure into an io.BytesIO, i.e. a memory buffer, rewind it and open it as a PIL Image. You can then accumulate the PIL Images in a list and pass them to the save() function of PIL to write a GIF.\nUntested, but something like:\nfrom io import BytesIO\nfrom PIL import Image\n\nimlist = []\nfor ...\n ...\n ... your code\n ...\n # Make in memory buffer and save fig into it\n buf = BytesIO()\n plt.savefig(buf) # you may need \"PNG\" as type here\n buf.seek(0)\n im = Image.open(buf)\n imlist.append(im)\n\n# Save list of images as animated GIF\nimlist[0].save('animated.gif', save_all=True, append_images=imlist[1:])\n\n"
] |
[
0
] |
[] |
[] |
[
"animation",
"gif",
"plot",
"python"
] |
stackoverflow_0074508831_animation_gif_plot_python.txt
|
Q:
Derive an answer that takes into all probabilities from a list
If the 'choice' valiance contains 'a','b','c' at the list each character link a number ('1','2','3').
For example choice = ['a','b','c'] links the numbers '1','2','3'.
choice = ['a','b','c']
def select(choice):
if choice == ['a']:
answer = '1'
elif choice == ['b']:
answer = '2'
elif choice == ['c']:
answer = '3'
elif choice == ['a', 'b']:
answer = "'1', '2'"
elif choice == ['a', 'c']:
answer = "'1', '3'"
elif choice == ['b', 'c']:
answer = "'2', '3'"
else
answer = "'1', '2', '3'"
Could I simply make it using another method?
A:
You can map the choices to their values with a dictionary, and then just use a list-comprehension to get the answer from the choice:
choice2val = {'a': '1', 'b': '2', 'c': '3'}
def select(choice):
answer = [v for k, v in choice2val.items() if k in choice]
return answer
choice = ['a', 'c'] # example
print(select(choice))
# ['1', '3']
|
Derive an answer that takes into all probabilities from a list
|
If the 'choice' valiance contains 'a','b','c' at the list each character link a number ('1','2','3').
For example choice = ['a','b','c'] links the numbers '1','2','3'.
choice = ['a','b','c']
def select(choice):
if choice == ['a']:
answer = '1'
elif choice == ['b']:
answer = '2'
elif choice == ['c']:
answer = '3'
elif choice == ['a', 'b']:
answer = "'1', '2'"
elif choice == ['a', 'c']:
answer = "'1', '3'"
elif choice == ['b', 'c']:
answer = "'2', '3'"
else
answer = "'1', '2', '3'"
Could I simply make it using another method?
|
[
"You can map the choices to their values with a dictionary, and then just use a list-comprehension to get the answer from the choice:\nchoice2val = {'a': '1', 'b': '2', 'c': '3'}\ndef select(choice):\n answer = [v for k, v in choice2val.items() if k in choice]\n return answer\n\nchoice = ['a', 'c'] # example \nprint(select(choice))\n# ['1', '3']\n\n"
] |
[
2
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0074511889_list_python.txt
|
Q:
Web scraping: .find doesn't find string in line of web page
I am writing my first python program and hope that you can help me with my current problem.
I try to extract data from a website and I checked the source of the page where a certain string (lets say "thisstring") is part of a line.
In the HTML-code the string is listed under :
<script>
anotherstring;
thisstring = {...};
My current code:
import requests
from bs4 import BeautifulSoup
page = requests.get('www.somewebadress.com')
soup = BeautifulSoup(page.content, 'html.parser')
lines = soup.find_all('script')
x = 0 #counter for script which returns the correct number of <script> parts in the html-code
for line in lines:
x = x + 1
txt = line.find('thisstring') #didnt work with "thisstring" either
if txt == None:
print("not found")
else:
print("found")
print(x)
I tried a lot different solutions I found in the www but "thisstring" is never found even if python printed it out with print(line).
I think it is quite simple but I tried the whole day to find the correct code.
Does anyone have an idea?
I found several code samples in stackoverflow and other python tutorials for web scraping but non of these worked. I use Spyder. Could this be a problem?
A:
Based on your comments you can use re module to extract the variable:
import re
html_text = """\
<html>
<script>
otherscript;
</script>
<script>
anotherstring;
thisstring = {"data1": 1, "data2": 2};
</script>
</html>"""
# or:
# html_text = requests.get(...).text
data = re.search(r"thisstring = (\{.*\});", html_text).group(1)
print(data)
Prints:
{"data1": 1, "data2": 2}
Then you can use ast.literal_eval, json or js2py to convert the string to python object:
import json
data = json.loads(data)
print(data)
|
Web scraping: .find doesn't find string in line of web page
|
I am writing my first python program and hope that you can help me with my current problem.
I try to extract data from a website and I checked the source of the page where a certain string (lets say "thisstring") is part of a line.
In the HTML-code the string is listed under :
<script>
anotherstring;
thisstring = {...};
My current code:
import requests
from bs4 import BeautifulSoup
page = requests.get('www.somewebadress.com')
soup = BeautifulSoup(page.content, 'html.parser')
lines = soup.find_all('script')
x = 0 #counter for script which returns the correct number of <script> parts in the html-code
for line in lines:
x = x + 1
txt = line.find('thisstring') #didnt work with "thisstring" either
if txt == None:
print("not found")
else:
print("found")
print(x)
I tried a lot different solutions I found in the www but "thisstring" is never found even if python printed it out with print(line).
I think it is quite simple but I tried the whole day to find the correct code.
Does anyone have an idea?
I found several code samples in stackoverflow and other python tutorials for web scraping but non of these worked. I use Spyder. Could this be a problem?
|
[
"Based on your comments you can use re module to extract the variable:\nimport re\n\nhtml_text = \"\"\"\\\n<html>\n<script>\n otherscript;\n</script>\n\n<script>\n anotherstring;\n thisstring = {\"data1\": 1, \"data2\": 2};\n</script>\n</html>\"\"\"\n\n# or:\n# html_text = requests.get(...).text\n\ndata = re.search(r\"thisstring = (\\{.*\\});\", html_text).group(1)\nprint(data)\n\nPrints:\n{\"data1\": 1, \"data2\": 2}\n\n\nThen you can use ast.literal_eval, json or js2py to convert the string to python object:\nimport json\n\ndata = json.loads(data)\nprint(data)\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"web_scraping"
] |
stackoverflow_0074511849_python_web_scraping.txt
|
Q:
Why does python return None in this instance?
I have this python practice question which is to return True if a word is an isogram (word with nonrepeating characters). It is also supposed to return True if the isogram is a blank string.
My answer didn't work out.
from string import ascii_lowercase
def is_isogram(iso):
for x in iso:
return False if (iso.count(x) > 1) and (x in ascii_lowercase) else True
#None
While another answered:
def is_isogram(word):
word = str(word).lower()
alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in word:
if word.count(i) > 1 and i in alphabet_list:
return False
return True
#True
I'm not sure why the return value is different with just a slightly different structure or is it how to return statement is defined?
A:
I would use a set operation. Using str.count repeatedly is expensive as you need to read the whole string over and over.
If your string only has unique characters, then its length equals that of its set of characters.
def is_isogram(iso):
return len(set(iso)) == len(iso)
print(is_isogram('abc'))
print(is_isogram('abac'))
print(is_isogram(''))
print(is_isogram(' '))
Output:
True
False
True
True
You can easily implement additional checks. For instance, convert to unique case if the case doesn't matter. If you want to exclude some characters (e.g. spaces), pre-filter the characters iso = [x for x in iso if x not in excluded_set].
|
Why does python return None in this instance?
|
I have this python practice question which is to return True if a word is an isogram (word with nonrepeating characters). It is also supposed to return True if the isogram is a blank string.
My answer didn't work out.
from string import ascii_lowercase
def is_isogram(iso):
for x in iso:
return False if (iso.count(x) > 1) and (x in ascii_lowercase) else True
#None
While another answered:
def is_isogram(word):
word = str(word).lower()
alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in word:
if word.count(i) > 1 and i in alphabet_list:
return False
return True
#True
I'm not sure why the return value is different with just a slightly different structure or is it how to return statement is defined?
|
[
"I would use a set operation. Using str.count repeatedly is expensive as you need to read the whole string over and over.\nIf your string only has unique characters, then its length equals that of its set of characters.\ndef is_isogram(iso):\n return len(set(iso)) == len(iso)\n\nprint(is_isogram('abc'))\nprint(is_isogram('abac'))\nprint(is_isogram(''))\nprint(is_isogram(' '))\n\nOutput:\nTrue\nFalse\nTrue\nTrue\n\nYou can easily implement additional checks. For instance, convert to unique case if the case doesn't matter. If you want to exclude some characters (e.g. spaces), pre-filter the characters iso = [x for x in iso if x not in excluded_set].\n"
] |
[
0
] |
[
"I think the difference is that in the other code they are looping the letters in the word and return false if a false condition is met and only if they get to the end of the letters in the word without meeting a false condition they are returning true.\nIn your code because the return statement for any condition is in the for loop it will only check the first letter, not the rest of the world.\nI tried your code and I am getting a true output unless the first letter is repeating.\nEdit: I didn't cover the none type output, someone else has already commented saying that it's happening because you never enter your for loop\n"
] |
[
-1
] |
[
"count",
"for_loop",
"if_statement",
"python",
"return"
] |
stackoverflow_0074511050_count_for_loop_if_statement_python_return.txt
|
Q:
How to make the square have blue lines and be at the front of the green line?
I want to make the square appear at the start of the green line and be blue. How do I do that?
from turtle import *
color('green')
begin_fill()
forward(200)
end_fill()
import turtle
turtle.color('blue')
# Creating a for loop that will run four times
for j in range(4):
turtle.forward(20) # Moving the turtle Forward by 150 units
turtle.left(90) # Turning the turtle by 90 degrees
As of now the square is not blue and is drawn at the end of the green line.
A:
Put the begin_fill/end_fill around the drawing of the square, draw the square first, then the line:
import turtle as t
t.color('blue')
t.begin_fill()
for _ in range(4):
t.forward(20)
t.left(90)
t.end_fill()
t.color('green')
t.forward(200)
t.mainloop()
|
How to make the square have blue lines and be at the front of the green line?
|
I want to make the square appear at the start of the green line and be blue. How do I do that?
from turtle import *
color('green')
begin_fill()
forward(200)
end_fill()
import turtle
turtle.color('blue')
# Creating a for loop that will run four times
for j in range(4):
turtle.forward(20) # Moving the turtle Forward by 150 units
turtle.left(90) # Turning the turtle by 90 degrees
As of now the square is not blue and is drawn at the end of the green line.
|
[
"Put the begin_fill/end_fill around the drawing of the square, draw the square first, then the line:\nimport turtle as t\n\nt.color('blue')\n\nt.begin_fill()\nfor _ in range(4):\n t.forward(20)\n t.left(90)\nt.end_fill()\n\nt.color('green')\nt.forward(200)\n\nt.mainloop()\n\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.9",
"python_turtle",
"turtle_graphics"
] |
stackoverflow_0074511861_python_python_3.9_python_turtle_turtle_graphics.txt
|
Q:
Astropy FITS Image Manipulating
I have a task for a course and I am working with NASA FITS files. I have two images and their dimensions which are being used in the projection of an image needed to be reshaped. What I mean from reshaping is that
Filename: jw02107-o039_t018_miri_f1130w_i2d.fits
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 349 ()
1 SCI 1 ImageHDU 75 (2379, 1178) float32
2 ERR 1 ImageHDU 10 (2379, 1178) float32
3 CON 1 ImageHDU 9 (2379, 1178) int32
4 WHT 1 ImageHDU 9 (2379, 1178) float32
5 VAR_POISSON 1 ImageHDU 9 (2379, 1178) float32
6 VAR_RNOISE 1 ImageHDU 9 (2379, 1178) float32
7 VAR_FLAT 1 ImageHDU 9 (2379, 1178) float32
8 HDRTAB 1 BinTableHDU 816 12R x 403C [23A, 5A, 3A, 48A, 7A, 13A, 6A, 5A, 7A, 10A, 4A, L, D, D, D, D, 32A, 48A, 70A, 11A, 2A, D, 47A, D, 10A, 12A, 23A, 23A, 26A, 11A, 5A, 3A, 3A, 2A, 1A, 2A, 1A, L, 12A, 6A, 2A, 26A, 20A, 27A, 10A, K, L, L, L, L, 7A, 7A, 5A, D, D, D, D, D, D, 27A, D, D, D, 4A, 8A, D, D, 6A, D, D, D, D, D, D, D, 4A, D, D, D, D, D, 3A, 4A, D, D, D, D, D, D, D, D, D, K, 5A, 9A, D, D, D, D, D, D, D, D, D, 6A, D, D, K, K, D, D, K, K, D, D, K, K, K, K, K, D, D, D, D, D, D, D, D, K, K, L, L, K, K, D, D, D, D, D, D, D, 4A, K, K, K, K, K, K, D, D, D, D, 12A, D, D, K, D, K, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, 7A, 10A, D, D, D, D, D, D, D, D, D, D, D, D, D, 10A, 11A, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, K, 27A, 27A, 10A, D, D, D, D, D, D, D, 9A, 27A, D, D, D, D, D, D, D, 8A, 14A, 31A, D, D, 3A, 3A, D, 31A, 3A, 37A, D, D, 39A, 31A, 3A, 3A, 3A, 3A, 3A, D, 31A, 3A, 3A, 3A, D, D, 36A, 31A, 3A, 3A, D, D, 33A, D, 36A, D, 3A, D, D, 32A, 31A, 37A, D, D, D, 3A, D, D, D, D, D, D, D, D, 3A, D, D, D, D, D, 8A, D, D, D, D, D, 8A, 8A, D, D, D, D, 8A, 8A, D, 7A, 7A, D, D, 7A, 8A, D, 8A, 8A, D, D, D, 8A, D, D, 8A, 8A, 8A, D, 8A, 8A, 8A, 8A, D, D, D, D, D, D, 8A, D, D, D, 5A, D, L, 6A, D, D, D, D, 4A, D, D, D, K, D, D, D, D, D, D, 12A, 12A, D, 3A, 3A, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, 117A, D, D, D, D, D, D, K, D, D, D, D]
9 ASDF 1 BinTableHDU 11 1R x 1C [36428B]
None
I have this file from the James Webb Space Telescope from the MIRI instrument which you can see in the name of the file. This file has the images which are in the dimensions of (2379,1178). And
Filename: jw02107-o040_t018_nircam_clear-f335m_i2d.fits
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 369 ()
1 SCI 1 ImageHDU 75 (4079, 2190) float32
2 ERR 1 ImageHDU 10 (4079, 2190) float32
3 CON 1 ImageHDU 9 (4079, 2190) int32
4 WHT 1 ImageHDU 9 (4079, 2190) float32
5 VAR_POISSON 1 ImageHDU 9 (4079, 2190) float32
6 VAR_RNOISE 1 ImageHDU 9 (4079, 2190) float32
7 VAR_FLAT 1 ImageHDU 9 (4079, 2190) float32
8 HDRTAB 1 BinTableHDU 816 8R x 403C [23A, 5A, 3A, 48A, 7A, 13A, 6A, 5A, 7A, 10A, 4A, L, D, D, D, D, 32A, 48A, 70A, 11A, 2A, D, 47A, D, 10A, 12A, 23A, 23A, 26A, 11A, 5A, 3A, 3A, 2A, 1A, 2A, 1A, L, 14A, 13A, 2A, 26A, 20A, 27A, 10A, K, L, L, L, L, 7A, 7A, 5A, D, D, D, D, D, D, 27A, D, D, D, 6A, 8A, 1A, 4A, 5A, 5A, L, D, D, D, D, D, D, D, D, D, D, D, D, 4A, D, D, D, D, D, D, D, D, D, K, 5A, 9A, D, D, D, D, D, D, D, D, D, 7A, D, D, K, K, D, D, K, K, D, D, K, K, K, K, K, D, D, D, D, D, D, D, D, K, K, L, L, K, K, D, D, D, D, D, D, D, 4A, K, K, K, K, K, K, D, D, D, D, 4A, D, D, K, D, K, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, 7A, 10A, D, D, D, D, D, D, D, D, D, D, D, D, D, 10A, 10A, D, D, D, D, D, D, D, D, D, D, D, D, K, K, D, 4A, K, K, K, D, 4A, K, K, K, D, 4A, K, D, D, K, 27A, 27A, 10A, D, D, D, D, D, D, D, 9A, 27A, D, D, D, D, D, D, D, 8A, 14A, 33A, D, D, 3A, 3A, D, 33A, 3A, 39A, D, D, 41A, 33A, 3A, 3A, 3A, 3A, 3A, D, 33A, 3A, 3A, 3A, D, D, 38A, 33A, 3A, 3A, D, 35A, 35A, D, 38A, D, 3A, D, D, D, D, 39A, D, D, D, 3A, D, 38A, D, 40A, 37A, D, D, D, 3A, D, D, D, D, D, 8A, D, D, D, D, D, 8A, 8A, D, D, D, D, D, 8A, D, 7A, 7A, D, D, 7A, 8A, D, D, 8A, D, D, D, 8A, D, 8A, 8A, 8A, 8A, D, D, D, 8A, 8A, D, D, D, D, 8A, D, 8A, D, D, D, 5A, D, L, 6A, D, D, D, D, 4A, D, D, D, K, D, D, D, D, D, D, 12A, 12A, D, 3A, 3A, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, 117A, D, D, D, D, D, D, K, D, D, D, D]
9 ASDF 1 BinTableHDU 11 1R x 1C [36706B]
None
I have this from the NIRcam instrument. And this file's images are in the dimensions of (4079, 2190).
When I project them on the Jupyter Notebook, they are projected on a cartesian coordinate system created by the help of numpy and matplotlib.
NIRcam image is projected on the cartesian coordinate system which is x = 4079 and y = 2190.
MIRI image is projectd on the cartesian coordinate system which is x = 2379 and y = 1178.
So, my question is that how can make their dimensions equal in the projection step. I mean, for example, how can I project them both on a cartesian coordinate system which is x = 5000 and y = 2000 ?
I tried to use WCS module and FITS_tools module to rehape it but somehow I could not. In the WCS module, I could not find the appropriate method to use and in the FITS_tools, I had an error like,
local variable 'image' referenced before assignment
What is the solution to reshape and reproject the images for this situation? I would be so glad if you can help out. Thank you.
A:
You need to use reproject (https://reproject.readthedocs.io/en/stable/). From the frontpage example:
from reproject import reproject_interp
array, footprint = reproject_interp(hdu2, hdu1.header)
so you'd do:
from astropy.io import fits
hdu1 = fits.open('JWST_File1.fits')['SCI']
hdu2 = fits.open('JWST_File2.fits')['SCI']
array, footprint = reproject_interp(hdu2, hdu1.header)
|
Astropy FITS Image Manipulating
|
I have a task for a course and I am working with NASA FITS files. I have two images and their dimensions which are being used in the projection of an image needed to be reshaped. What I mean from reshaping is that
Filename: jw02107-o039_t018_miri_f1130w_i2d.fits
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 349 ()
1 SCI 1 ImageHDU 75 (2379, 1178) float32
2 ERR 1 ImageHDU 10 (2379, 1178) float32
3 CON 1 ImageHDU 9 (2379, 1178) int32
4 WHT 1 ImageHDU 9 (2379, 1178) float32
5 VAR_POISSON 1 ImageHDU 9 (2379, 1178) float32
6 VAR_RNOISE 1 ImageHDU 9 (2379, 1178) float32
7 VAR_FLAT 1 ImageHDU 9 (2379, 1178) float32
8 HDRTAB 1 BinTableHDU 816 12R x 403C [23A, 5A, 3A, 48A, 7A, 13A, 6A, 5A, 7A, 10A, 4A, L, D, D, D, D, 32A, 48A, 70A, 11A, 2A, D, 47A, D, 10A, 12A, 23A, 23A, 26A, 11A, 5A, 3A, 3A, 2A, 1A, 2A, 1A, L, 12A, 6A, 2A, 26A, 20A, 27A, 10A, K, L, L, L, L, 7A, 7A, 5A, D, D, D, D, D, D, 27A, D, D, D, 4A, 8A, D, D, 6A, D, D, D, D, D, D, D, 4A, D, D, D, D, D, 3A, 4A, D, D, D, D, D, D, D, D, D, K, 5A, 9A, D, D, D, D, D, D, D, D, D, 6A, D, D, K, K, D, D, K, K, D, D, K, K, K, K, K, D, D, D, D, D, D, D, D, K, K, L, L, K, K, D, D, D, D, D, D, D, 4A, K, K, K, K, K, K, D, D, D, D, 12A, D, D, K, D, K, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, 7A, 10A, D, D, D, D, D, D, D, D, D, D, D, D, D, 10A, 11A, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, K, 27A, 27A, 10A, D, D, D, D, D, D, D, 9A, 27A, D, D, D, D, D, D, D, 8A, 14A, 31A, D, D, 3A, 3A, D, 31A, 3A, 37A, D, D, 39A, 31A, 3A, 3A, 3A, 3A, 3A, D, 31A, 3A, 3A, 3A, D, D, 36A, 31A, 3A, 3A, D, D, 33A, D, 36A, D, 3A, D, D, 32A, 31A, 37A, D, D, D, 3A, D, D, D, D, D, D, D, D, 3A, D, D, D, D, D, 8A, D, D, D, D, D, 8A, 8A, D, D, D, D, 8A, 8A, D, 7A, 7A, D, D, 7A, 8A, D, 8A, 8A, D, D, D, 8A, D, D, 8A, 8A, 8A, D, 8A, 8A, 8A, 8A, D, D, D, D, D, D, 8A, D, D, D, 5A, D, L, 6A, D, D, D, D, 4A, D, D, D, K, D, D, D, D, D, D, 12A, 12A, D, 3A, 3A, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, 117A, D, D, D, D, D, D, K, D, D, D, D]
9 ASDF 1 BinTableHDU 11 1R x 1C [36428B]
None
I have this file from the James Webb Space Telescope from the MIRI instrument which you can see in the name of the file. This file has the images which are in the dimensions of (2379,1178). And
Filename: jw02107-o040_t018_nircam_clear-f335m_i2d.fits
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 369 ()
1 SCI 1 ImageHDU 75 (4079, 2190) float32
2 ERR 1 ImageHDU 10 (4079, 2190) float32
3 CON 1 ImageHDU 9 (4079, 2190) int32
4 WHT 1 ImageHDU 9 (4079, 2190) float32
5 VAR_POISSON 1 ImageHDU 9 (4079, 2190) float32
6 VAR_RNOISE 1 ImageHDU 9 (4079, 2190) float32
7 VAR_FLAT 1 ImageHDU 9 (4079, 2190) float32
8 HDRTAB 1 BinTableHDU 816 8R x 403C [23A, 5A, 3A, 48A, 7A, 13A, 6A, 5A, 7A, 10A, 4A, L, D, D, D, D, 32A, 48A, 70A, 11A, 2A, D, 47A, D, 10A, 12A, 23A, 23A, 26A, 11A, 5A, 3A, 3A, 2A, 1A, 2A, 1A, L, 14A, 13A, 2A, 26A, 20A, 27A, 10A, K, L, L, L, L, 7A, 7A, 5A, D, D, D, D, D, D, 27A, D, D, D, 6A, 8A, 1A, 4A, 5A, 5A, L, D, D, D, D, D, D, D, D, D, D, D, D, 4A, D, D, D, D, D, D, D, D, D, K, 5A, 9A, D, D, D, D, D, D, D, D, D, 7A, D, D, K, K, D, D, K, K, D, D, K, K, K, K, K, D, D, D, D, D, D, D, D, K, K, L, L, K, K, D, D, D, D, D, D, D, 4A, K, K, K, K, K, K, D, D, D, D, 4A, D, D, K, D, K, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, 7A, 10A, D, D, D, D, D, D, D, D, D, D, D, D, D, 10A, 10A, D, D, D, D, D, D, D, D, D, D, D, D, K, K, D, 4A, K, K, K, D, 4A, K, K, K, D, 4A, K, D, D, K, 27A, 27A, 10A, D, D, D, D, D, D, D, 9A, 27A, D, D, D, D, D, D, D, 8A, 14A, 33A, D, D, 3A, 3A, D, 33A, 3A, 39A, D, D, 41A, 33A, 3A, 3A, 3A, 3A, 3A, D, 33A, 3A, 3A, 3A, D, D, 38A, 33A, 3A, 3A, D, 35A, 35A, D, 38A, D, 3A, D, D, D, D, 39A, D, D, D, 3A, D, 38A, D, 40A, 37A, D, D, D, 3A, D, D, D, D, D, 8A, D, D, D, D, D, 8A, 8A, D, D, D, D, D, 8A, D, 7A, 7A, D, D, 7A, 8A, D, D, 8A, D, D, D, 8A, D, 8A, 8A, 8A, 8A, D, D, D, 8A, 8A, D, D, D, D, 8A, D, 8A, D, D, D, 5A, D, L, 6A, D, D, D, D, 4A, D, D, D, K, D, D, D, D, D, D, 12A, 12A, D, 3A, 3A, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, D, 117A, D, D, D, D, D, D, K, D, D, D, D]
9 ASDF 1 BinTableHDU 11 1R x 1C [36706B]
None
I have this from the NIRcam instrument. And this file's images are in the dimensions of (4079, 2190).
When I project them on the Jupyter Notebook, they are projected on a cartesian coordinate system created by the help of numpy and matplotlib.
NIRcam image is projected on the cartesian coordinate system which is x = 4079 and y = 2190.
MIRI image is projectd on the cartesian coordinate system which is x = 2379 and y = 1178.
So, my question is that how can make their dimensions equal in the projection step. I mean, for example, how can I project them both on a cartesian coordinate system which is x = 5000 and y = 2000 ?
I tried to use WCS module and FITS_tools module to rehape it but somehow I could not. In the WCS module, I could not find the appropriate method to use and in the FITS_tools, I had an error like,
local variable 'image' referenced before assignment
What is the solution to reshape and reproject the images for this situation? I would be so glad if you can help out. Thank you.
|
[
"You need to use reproject (https://reproject.readthedocs.io/en/stable/). From the frontpage example:\nfrom reproject import reproject_interp\narray, footprint = reproject_interp(hdu2, hdu1.header)\n\nso you'd do:\nfrom astropy.io import fits\nhdu1 = fits.open('JWST_File1.fits')['SCI']\nhdu2 = fits.open('JWST_File2.fits')['SCI']\narray, footprint = reproject_interp(hdu2, hdu1.header)\n\n"
] |
[
0
] |
[] |
[] |
[
"astropy",
"fits",
"jupyter_notebook",
"python",
"wcs"
] |
stackoverflow_0074252157_astropy_fits_jupyter_notebook_python_wcs.txt
|
Q:
Run streamlit locally without installing
How can I run streamlit file without installing it?
I have tried turning it into an exe and it told me that it wasn't a recognized command.
A:
Hi hope you are doing fine!
I am not very sure if it will work in your case, but from my point of view, the easiest solution will be to make a Docker image from your "app" and then just run it as a Docker container instead of making a binary or exe file. The main benefit is that you will be able to easily run it on any machine and OS not only on Windows, plus the whole environment will be isolated too.
There is an example of how to do it: https://docs.streamlit.io/knowledge-base/tutorials/deploy/docker
|
Run streamlit locally without installing
|
How can I run streamlit file without installing it?
I have tried turning it into an exe and it told me that it wasn't a recognized command.
|
[
"Hi hope you are doing fine!\nI am not very sure if it will work in your case, but from my point of view, the easiest solution will be to make a Docker image from your \"app\" and then just run it as a Docker container instead of making a binary or exe file. The main benefit is that you will be able to easily run it on any machine and OS not only on Windows, plus the whole environment will be isolated too.\nThere is an example of how to do it: https://docs.streamlit.io/knowledge-base/tutorials/deploy/docker\n"
] |
[
1
] |
[] |
[] |
[
"auto_py_to_exe",
"python",
"streamlit"
] |
stackoverflow_0074506907_auto_py_to_exe_python_streamlit.txt
|
Q:
Redirect non authenticated user to login page (for all views)
I am looking to redirect my user to login page, if they have not logged in.
I initally looked at the decorator @login_required(login_url='/accounts/login/').
But this is not ideal, for 2 reasons: first I want this to apply to all views. Also the decorator returns an error message when I try to login with allauth.
I am sure this is solvable, but I am looking for a solution that could apply to all views.
I found something using authmiddleware(doc: https://pypi.org/project/django-authmiddleware/). However the code doesn't not seem to be responsive, in the sense nothing is happening and the logs on the console don't seem to pick up anything.
Can someone see what I am doing wrong?
base.py
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'AuthMiddleware.middleware.AuthRequiredMiddleware',
]
AUTH_SETTINGS = {
"LOGIN_URL" : "login_user",
"DEFAULT_REDIRECT_URL" : None,
"REDIRECT_AFTER_LOGIN" : False,
}
views.py
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.urls import reverse
def list_event(request): #ADDED FOLLOWING REQUEST IN COMMENTS
event_list = Event.objects.all
return render(request, 'main/list_event.html',{'event_list':event_list})
class AuthRequiredMiddleware(object):
def process_request(self, request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('login_user'))
return None
A:
Found an alternative solution and thought I would leave it there.
I used a tutorial on youtube (https://www.youtube.com/watch?v=axsaC62UQOc) which, with a few changes (the video is old), works like a charm. Its about 3 videos 30 minutes very well explained.
Here it goes:
settings.py
MIDDLEWARE = [
'[yourappname].middleware.LoginRequiredMiddleware',
]
LOGIN_EXEMPT_URLS =( #<-- I am using allauth, so left some examples here)
r'logout',
r'register_user',
r'accounts/google/login/',
r'accounts/social/signup/',
r'accounts/facebook/login/',
)
middleware.py (this files goes in your main app, by default "mysite")
import re
from django.conf import settings
from django.shortcuts import redirect
EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
pass
def __init__(self, get_response):
self.get_response = get_response
def __call__ (self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
assert hasattr(request,'user')
path = request.path_info.lstrip('/')
print(path)
if not request.user.is_authenticated:
if not any(url.match(path) for url in EXEMPT_URLS):
return redirect(settings.LOGIN_URL)
A:
why not use
return redirect('%s?next=%s' % (settings.login_user, request.path))'
instead of HttpResponse?
|
Redirect non authenticated user to login page (for all views)
|
I am looking to redirect my user to login page, if they have not logged in.
I initally looked at the decorator @login_required(login_url='/accounts/login/').
But this is not ideal, for 2 reasons: first I want this to apply to all views. Also the decorator returns an error message when I try to login with allauth.
I am sure this is solvable, but I am looking for a solution that could apply to all views.
I found something using authmiddleware(doc: https://pypi.org/project/django-authmiddleware/). However the code doesn't not seem to be responsive, in the sense nothing is happening and the logs on the console don't seem to pick up anything.
Can someone see what I am doing wrong?
base.py
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'AuthMiddleware.middleware.AuthRequiredMiddleware',
]
AUTH_SETTINGS = {
"LOGIN_URL" : "login_user",
"DEFAULT_REDIRECT_URL" : None,
"REDIRECT_AFTER_LOGIN" : False,
}
views.py
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.urls import reverse
def list_event(request): #ADDED FOLLOWING REQUEST IN COMMENTS
event_list = Event.objects.all
return render(request, 'main/list_event.html',{'event_list':event_list})
class AuthRequiredMiddleware(object):
def process_request(self, request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('login_user'))
return None
|
[
"Found an alternative solution and thought I would leave it there.\nI used a tutorial on youtube (https://www.youtube.com/watch?v=axsaC62UQOc) which, with a few changes (the video is old), works like a charm. Its about 3 videos 30 minutes very well explained.\nHere it goes:\nsettings.py\nMIDDLEWARE = [\n\n '[yourappname].middleware.LoginRequiredMiddleware', \n]\n\nLOGIN_EXEMPT_URLS =( #<-- I am using allauth, so left some examples here)\n r'logout',\n r'register_user',\n r'accounts/google/login/',\n r'accounts/social/signup/',\n r'accounts/facebook/login/',\n \n)\n\nmiddleware.py (this files goes in your main app, by default \"mysite\")\nimport re\nfrom django.conf import settings\nfrom django.shortcuts import redirect\n\nEXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]\nif hasattr(settings, 'LOGIN_EXEMPT_URLS'):\n EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]\n\nclass LoginRequiredMiddleware:\n pass\n def __init__(self, get_response):\n self.get_response = get_response\n \n def __call__ (self, request):\n response = self.get_response(request)\n return response\n \n def process_view(self, request, view_func, view_args, view_kwargs):\n assert hasattr(request,'user')\n path = request.path_info.lstrip('/')\n print(path)\n \n if not request.user.is_authenticated:\n if not any(url.match(path) for url in EXEMPT_URLS):\n return redirect(settings.LOGIN_URL)\n \n\n",
"why not use\nreturn redirect('%s?next=%s' % (settings.login_user, request.path))' \n\ninstead of HttpResponse?\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_middleware",
"django_views",
"python"
] |
stackoverflow_0074503923_django_django_middleware_django_views_python.txt
|
Q:
Python - called Tcl_FindHashEntry on deleted table when Pygame window is focused after using Tkinter
So I was working on a larger project and testing on a Mac when I noticed some weird behavior. I'm using Python 3.9.1 and macOS 11.0.1 – the bug doesn't occur on Windows 7, and I haven't tested other versions of macOS or Windows.
I'm using Tkinter for an initial setup window and then switching to Pygame, and in between, I do some cleanup of all the Tkinter variables – theoretically they don't matter, since I'm not using Tkinter for anything after that. Once the Pygame window opens, everything is fine, but if I click on another window to defocus Pygame, and then focus on the Pygame window again, it crashes with the following output:
pygame 2.0.0 (SDL 2.0.12, python 3.9.1)
Hello from the pygame community. https://www.pygame.org/contribute.html
called Tcl_FindHashEntry on deleted table
zsh: abort python3 test.py
The minimum to consistently replicate this issue is
import pygame
import tkinter as tk
from time import sleep
root = tk.Tk()
try:
root.mainloop()
except tk.TclError:
pass
del root
pygame.init()
screen = pygame.display.set_mode((100, 100))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print('User quit.')
exit()
pygame.display.flip()
sleep(0.025)
If I remove the del root then it doesn't crash, so it's not actually a big issue for my project – I don't need to remove the reference to root. But is there a better solution that can prevent the problem and still allow me to clean up the Tkinter references once I'm done with it?
A:
Using _pygame and tkinter in the same application is not fully featured (see Embedding a Pygame window into a Tkinter or WxPython frame). It a bad idea to mix frameworks. The frameworks may interact poorly with each other or conflict completely. If it works on your (operating) system, that doesn't mean it will work on another (operating) system or with a different version of one of the frameworks. Mixing frameworks always means some kind of undefined behavior.
|
Python - called Tcl_FindHashEntry on deleted table when Pygame window is focused after using Tkinter
|
So I was working on a larger project and testing on a Mac when I noticed some weird behavior. I'm using Python 3.9.1 and macOS 11.0.1 – the bug doesn't occur on Windows 7, and I haven't tested other versions of macOS or Windows.
I'm using Tkinter for an initial setup window and then switching to Pygame, and in between, I do some cleanup of all the Tkinter variables – theoretically they don't matter, since I'm not using Tkinter for anything after that. Once the Pygame window opens, everything is fine, but if I click on another window to defocus Pygame, and then focus on the Pygame window again, it crashes with the following output:
pygame 2.0.0 (SDL 2.0.12, python 3.9.1)
Hello from the pygame community. https://www.pygame.org/contribute.html
called Tcl_FindHashEntry on deleted table
zsh: abort python3 test.py
The minimum to consistently replicate this issue is
import pygame
import tkinter as tk
from time import sleep
root = tk.Tk()
try:
root.mainloop()
except tk.TclError:
pass
del root
pygame.init()
screen = pygame.display.set_mode((100, 100))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print('User quit.')
exit()
pygame.display.flip()
sleep(0.025)
If I remove the del root then it doesn't crash, so it's not actually a big issue for my project – I don't need to remove the reference to root. But is there a better solution that can prevent the problem and still allow me to clean up the Tkinter references once I'm done with it?
|
[
"Using _pygame and tkinter in the same application is not fully featured (see Embedding a Pygame window into a Tkinter or WxPython frame). It a bad idea to mix frameworks. The frameworks may interact poorly with each other or conflict completely. If it works on your (operating) system, that doesn't mean it will work on another (operating) system or with a different version of one of the frameworks. Mixing frameworks always means some kind of undefined behavior.\n"
] |
[
0
] |
[] |
[] |
[
"garbage_collection",
"pygame",
"python",
"tkinter"
] |
stackoverflow_0065473778_garbage_collection_pygame_python_tkinter.txt
|
Q:
What is the range of the angle returned by minAreaRect?
Checking the documentation and the posts related to cv2.minAreaRect, I have noticed that the returned angle value should be within the range [-90, 0). When I try to run minAreaRect for the following vertices, it returns the positive value:
import numpy as np
import cv2
vertices = np.array([[ 67.264, 357.4],
[ 484.47, 364.68],
[ 473.14, 1013.5],
[ 55.938, 1006.2]])
test = cv2.minAreaRect(np.array(vertices)) # returns ((270.2044677734375, 685.4646606445312), (417.27044677734375, 648.945068359375), 1.0000191926956177)
Has there been anything changed? what is the actual range of the return value?
A:
It's not formally defined. Here's what one of the OpenCV contributors has said about it:
angle range is unspecified (neither before nor after). Also algorithm's implementation doesn't define even width/height relations (can be swapped with 90 degree angle adjustment). For example, if we want to force width >= height, then angle range's size should be 180 degrees.
anything that is stated in documentation should have corresponding implementation and must be validated by tests.
In other words, the official docs don't say anything about the angle range, to give freedom for future changes in minAreaRect.
In the specific case you're looking at, I believe this was caused by a change to fix a bug. I don't entirely follow why changing the convexHull step to use CCW instead of CW coordinates causes an angle change, but it seems to be why it changed. More information.
|
What is the range of the angle returned by minAreaRect?
|
Checking the documentation and the posts related to cv2.minAreaRect, I have noticed that the returned angle value should be within the range [-90, 0). When I try to run minAreaRect for the following vertices, it returns the positive value:
import numpy as np
import cv2
vertices = np.array([[ 67.264, 357.4],
[ 484.47, 364.68],
[ 473.14, 1013.5],
[ 55.938, 1006.2]])
test = cv2.minAreaRect(np.array(vertices)) # returns ((270.2044677734375, 685.4646606445312), (417.27044677734375, 648.945068359375), 1.0000191926956177)
Has there been anything changed? what is the actual range of the return value?
|
[
"It's not formally defined. Here's what one of the OpenCV contributors has said about it:\n\nangle range is unspecified (neither before nor after). Also algorithm's implementation doesn't define even width/height relations (can be swapped with 90 degree angle adjustment). For example, if we want to force width >= height, then angle range's size should be 180 degrees.\nanything that is stated in documentation should have corresponding implementation and must be validated by tests.\n\nIn other words, the official docs don't say anything about the angle range, to give freedom for future changes in minAreaRect.\nIn the specific case you're looking at, I believe this was caused by a change to fix a bug. I don't entirely follow why changing the convexHull step to use CCW instead of CW coordinates causes an angle change, but it seems to be why it changed. More information.\n"
] |
[
1
] |
[] |
[] |
[
"opencv",
"python"
] |
stackoverflow_0074508074_opencv_python.txt
|
Q:
Can't instantiate abstract class ... with abstract methods
I'm working on a kind of lib, and for a weird reason i have this error.
Here is my code. Of course @abc.abstractmethod have to be uncommented
Here are my tests
Sorry couldn't just copy and paste it
I went on the basis that the code below works.
test.py:
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Base(object):
@abc.abstractmethod
def whatever(self,):
raise NotImplementedError
class SubClass(Base):
def __init__(self,):
super(Base, self).__init__()
self.whatever()
def whatever(self,):
print("whatever")
In the python shell:
>>> from test import *
>>> s = SubClass()
whatever
Why for my roster module i'm having this error:
Can't instantiate abstract class Player with abstract methods _Base__json_builder, _Base__xml_builder
Thanks in advance.
A:
Your issue comes because you have defined the abstract methods in your base abstract class with __ (double underscore) prepended. This causes python to do name mangling at the time of definition of the classes.
The names of the function change from __json_builder to _Base__json_builder or __xml_builder to _Base__xml_builder . And this is the name you have to implement/overwrite in your subclass.
To show this behavior in your example -
>>> import abc
>>> import six
>>> @six.add_metaclass(abc.ABCMeta)
... class Base(object):
... @abc.abstractmethod
... def __whatever(self):
... raise NotImplementedError
...
>>> class SubClass(Base):
... def __init__(self):
... super(Base, self).__init__()
... self.__whatever()
... def __whatever(self):
... print("whatever")
...
>>> a = SubClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class SubClass with abstract methods _Base__whatever
When I change the implementation to the following, it works
>>> class SubClass(Base):
... def __init__(self):
... super(Base, self).__init__()
... self._Base__whatever()
... def _Base__whatever(self):
... print("whatever")
...
>>> a = SubClass()
whatever
But this is very tedious , you may want to think about if you really want to define your functions with __ (double underscore) . You can read more about name mangling here .
A:
Easiest way to make it behave like it did in Python 2 is to use
exec('print("your code")', globals())
This will allow your code to access imports, classes and functions defined in the code will work correctly, etc.
This should only be done w/ code you trust.
A:
I got the same error below:
TypeError: Can't instantiate abstract class Animal with abstract methods sound
When I tried to instantiate Animal abstract class as shown below:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
print("Wow!!")
obj = Animal() # Here
obj.sound()
And also, I got the same error below:
TypeError: Can't instantiate abstract class Cat with abstract methods sound
When I didn't override sound() abstract method in Cat class, then I instantiated Cat class as shown below:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
print("Wow!!")
class Cat(Animal):
pass # I didn't override "sound()" abstract method
obj = Cat() # Here
obj.sound()
So, I overrided sound() abstract method in Cat class, then I instantiated Cat class as shown below:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
print("Wow!!")
# I overrided "sound()" abstract method
class Cat(Animal):
def sound(self):
print("Meow!!")
obj = Cat() # Here
obj.sound()
Then, I could solve the error:
Meow!!
|
Can't instantiate abstract class ... with abstract methods
|
I'm working on a kind of lib, and for a weird reason i have this error.
Here is my code. Of course @abc.abstractmethod have to be uncommented
Here are my tests
Sorry couldn't just copy and paste it
I went on the basis that the code below works.
test.py:
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Base(object):
@abc.abstractmethod
def whatever(self,):
raise NotImplementedError
class SubClass(Base):
def __init__(self,):
super(Base, self).__init__()
self.whatever()
def whatever(self,):
print("whatever")
In the python shell:
>>> from test import *
>>> s = SubClass()
whatever
Why for my roster module i'm having this error:
Can't instantiate abstract class Player with abstract methods _Base__json_builder, _Base__xml_builder
Thanks in advance.
|
[
"Your issue comes because you have defined the abstract methods in your base abstract class with __ (double underscore) prepended. This causes python to do name mangling at the time of definition of the classes.\nThe names of the function change from __json_builder to _Base__json_builder or __xml_builder to _Base__xml_builder . And this is the name you have to implement/overwrite in your subclass.\nTo show this behavior in your example -\n>>> import abc\n>>> import six\n>>> @six.add_metaclass(abc.ABCMeta)\n... class Base(object):\n... @abc.abstractmethod\n... def __whatever(self):\n... raise NotImplementedError\n...\n>>> class SubClass(Base):\n... def __init__(self):\n... super(Base, self).__init__()\n... self.__whatever()\n... def __whatever(self):\n... print(\"whatever\")\n...\n>>> a = SubClass()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: Can't instantiate abstract class SubClass with abstract methods _Base__whatever\n\nWhen I change the implementation to the following, it works\n>>> class SubClass(Base):\n... def __init__(self):\n... super(Base, self).__init__()\n... self._Base__whatever()\n... def _Base__whatever(self):\n... print(\"whatever\")\n...\n>>> a = SubClass()\nwhatever\n\nBut this is very tedious , you may want to think about if you really want to define your functions with __ (double underscore) . You can read more about name mangling here .\n",
"Easiest way to make it behave like it did in Python 2 is to use\nexec('print(\"your code\")', globals())\n\nThis will allow your code to access imports, classes and functions defined in the code will work correctly, etc.\nThis should only be done w/ code you trust.\n",
"I got the same error below:\n\nTypeError: Can't instantiate abstract class Animal with abstract methods sound\n\nWhen I tried to instantiate Animal abstract class as shown below:\nfrom abc import ABC, abstractmethod\n\nclass Animal(ABC):\n @abstractmethod\n def sound(self):\n print(\"Wow!!\")\n\nobj = Animal() # Here\nobj.sound()\n\nAnd also, I got the same error below:\n\nTypeError: Can't instantiate abstract class Cat with abstract methods sound\n\nWhen I didn't override sound() abstract method in Cat class, then I instantiated Cat class as shown below:\nfrom abc import ABC, abstractmethod\n\nclass Animal(ABC):\n @abstractmethod\n def sound(self):\n print(\"Wow!!\")\n\nclass Cat(Animal):\n pass # I didn't override \"sound()\" abstract method\n\nobj = Cat() # Here\nobj.sound()\n\nSo, I overrided sound() abstract method in Cat class, then I instantiated Cat class as shown below:\nfrom abc import ABC, abstractmethod\n\nclass Animal(ABC):\n @abstractmethod\n def sound(self):\n print(\"Wow!!\")\n\n# I overrided \"sound()\" abstract method\nclass Cat(Animal):\n def sound(self):\n print(\"Meow!!\")\n\nobj = Cat() # Here\nobj.sound()\n\nThen, I could solve the error:\nMeow!!\n\n"
] |
[
72,
0,
0
] |
[] |
[] |
[
"abstract_class",
"abstract_methods",
"python",
"python_2.x",
"python_3.x"
] |
stackoverflow_0031457855_abstract_class_abstract_methods_python_python_2.x_python_3.x.txt
|
Q:
Performing Boolean Logic in views and template
am having two set of challenges. First, I have a model with field submit as Boolean field. I use model form and render it in template. There are two options as Boolean select i.e. 'Yes' and 'No' option for user to select whether he want to save the form or not. I want if this user select 'Yes', the form should be save. else if he select 'No', the form should not be save. I have exhausted all the logics that i thought could work but cannot achieve this. Below is the views
views.py
def submit(request):
if request.method =='POST':
form = submitForm(request.POST)
form.instance.user = request.user
sub = form.save()
if sub.sumit ==True:
if sub:
messages.info(request, 'You have submitted you form successfully')
return redirect('home')
messages.info(request, 'Continue editing your data')
return render(request, 'portal/home/submit.html')
form =submitForm()
context = {
'form':form,
# 'sub':sub
}
return render(request, 'portal/home/submit.html', context)
my second question is in this view. since I could not achieve what i wanted in the above form, i just query it in this user_info so that if user save the submit as 'Yes' or 'No' some certain buttons in template should or should not show. below is how i try but not exactly what i wanted. i want only the user that select the above Boolean form as True or 'Yes' as shown on the template to not see the 'save' and 'Update' button but anyone that did not submit yet or submit 'No' can see all the buttons.
views
def user_info(request):
# user = request.user
user =request.user
try:
personal = Personalinfo.objects.get(user_id=user)
except Personalinfo.DoesNotExist:
messages.error(request, 'Please fill in all data')
personal =None
# try:
sub = SubmitData.objects.filter(user_id = user)
# except SubmitData.DoesNotExist:
# messages.error(request, f'You already submitted you data on, {sub.date_submited}')
# sub =None
if request.method == "POST":
form = usersForm(request.POST, request.FILES, instance =personal)
if form.is_valid():
form.instance.user = request.user
form.save()
messages.success(request, 'User data saved successful! Click next to proceed')
return redirect('user_info')
else:
messages.error(request, 'Error! Check your data')
return redirect('user_info')
form = usersForm(instance =personal)
context={
"form": form,
'sub':sub,
# 'submitted':submitted
}
return render(request, 'portal/home/user_info.html', context)
this the template
{% if sub %}
<div class="col-md-4 col-sm-3">
<div class="text-center">
<a class="btn btn-dark text-decoration-none text-white bg-dark mt-4 mb-0" href="{% url 'academy' %}">Next</a>
</div>
</div>
</div>
{% else %}
<div class="row">
<div class="col-md-10 col-sm-10 mx-auto ">
<button type="submit" name="register" class="text-white btn bg-dark mt-4 mb-0">
Save
</button>
<a class="btn btn-dark text-decoration-none text-white btn bg-dark mt-4 mb-0" href="{% url 'user_update' request.user.pk %}"> Update </a>
<a class="btn btn-dark text-decoration-none text-white bg-dark mt-4 mb-0" href="{% url 'academy' %}">Next</a>
</div>
</div>
{% endif %}
Your answers will improve me alot. Thanks
A:
First question:
I'm assuming the field is called sumit as per your question (apologies if this is a typo :-) )
Where you have
form.instance.user = request.user
sub = form.save()
if sub.sumit ==True:
if sub:
messages.info(request, 'You have submitted you form successfully')
return redirect('home')
replace with
#set up sub as a 'falsey' value
sub = ""
#create an instance of form
form = submitForm(request.POST)
#check that the data is valid
if form.is_valid():
#check if the 'submit' checkbox has been checked
#this is assuming you are using a default boolean checkbox widget,
#which only gets submitted if checked
#with other widgets you might need to check for a particular value
#eg, if form.cleaned_data.get("sumit") == "Yes"
if form.cleaned_data.get("sumit"):
form.instance.user = request.user
sub = form.save()
if sub:
messages.info(request, 'You have submitted you form successfully')
return redirect('home')
For the second question - if I've understood correctly, you should be able to do it with a further filter on sub so that the query is only successful if the user has indicated yes :
sub = SubmitData.objects.filter(user_id = user, sumit=True)
|
Performing Boolean Logic in views and template
|
am having two set of challenges. First, I have a model with field submit as Boolean field. I use model form and render it in template. There are two options as Boolean select i.e. 'Yes' and 'No' option for user to select whether he want to save the form or not. I want if this user select 'Yes', the form should be save. else if he select 'No', the form should not be save. I have exhausted all the logics that i thought could work but cannot achieve this. Below is the views
views.py
def submit(request):
if request.method =='POST':
form = submitForm(request.POST)
form.instance.user = request.user
sub = form.save()
if sub.sumit ==True:
if sub:
messages.info(request, 'You have submitted you form successfully')
return redirect('home')
messages.info(request, 'Continue editing your data')
return render(request, 'portal/home/submit.html')
form =submitForm()
context = {
'form':form,
# 'sub':sub
}
return render(request, 'portal/home/submit.html', context)
my second question is in this view. since I could not achieve what i wanted in the above form, i just query it in this user_info so that if user save the submit as 'Yes' or 'No' some certain buttons in template should or should not show. below is how i try but not exactly what i wanted. i want only the user that select the above Boolean form as True or 'Yes' as shown on the template to not see the 'save' and 'Update' button but anyone that did not submit yet or submit 'No' can see all the buttons.
views
def user_info(request):
# user = request.user
user =request.user
try:
personal = Personalinfo.objects.get(user_id=user)
except Personalinfo.DoesNotExist:
messages.error(request, 'Please fill in all data')
personal =None
# try:
sub = SubmitData.objects.filter(user_id = user)
# except SubmitData.DoesNotExist:
# messages.error(request, f'You already submitted you data on, {sub.date_submited}')
# sub =None
if request.method == "POST":
form = usersForm(request.POST, request.FILES, instance =personal)
if form.is_valid():
form.instance.user = request.user
form.save()
messages.success(request, 'User data saved successful! Click next to proceed')
return redirect('user_info')
else:
messages.error(request, 'Error! Check your data')
return redirect('user_info')
form = usersForm(instance =personal)
context={
"form": form,
'sub':sub,
# 'submitted':submitted
}
return render(request, 'portal/home/user_info.html', context)
this the template
{% if sub %}
<div class="col-md-4 col-sm-3">
<div class="text-center">
<a class="btn btn-dark text-decoration-none text-white bg-dark mt-4 mb-0" href="{% url 'academy' %}">Next</a>
</div>
</div>
</div>
{% else %}
<div class="row">
<div class="col-md-10 col-sm-10 mx-auto ">
<button type="submit" name="register" class="text-white btn bg-dark mt-4 mb-0">
Save
</button>
<a class="btn btn-dark text-decoration-none text-white btn bg-dark mt-4 mb-0" href="{% url 'user_update' request.user.pk %}"> Update </a>
<a class="btn btn-dark text-decoration-none text-white bg-dark mt-4 mb-0" href="{% url 'academy' %}">Next</a>
</div>
</div>
{% endif %}
Your answers will improve me alot. Thanks
|
[
"First question:\nI'm assuming the field is called sumit as per your question (apologies if this is a typo :-) )\nWhere you have\n form.instance.user = request.user\n sub = form.save()\n if sub.sumit ==True:\n\n if sub:\n messages.info(request, 'You have submitted you form successfully')\n return redirect('home')\n \n\nreplace with\n #set up sub as a 'falsey' value\n sub = \"\"\n #create an instance of form\n form = submitForm(request.POST)\n #check that the data is valid\n if form.is_valid():\n #check if the 'submit' checkbox has been checked\n #this is assuming you are using a default boolean checkbox widget, \n #which only gets submitted if checked\n #with other widgets you might need to check for a particular value\n #eg, if form.cleaned_data.get(\"sumit\") == \"Yes\"\n if form.cleaned_data.get(\"sumit\"):\n form.instance.user = request.user\n sub = form.save()\n if sub:\n messages.info(request, 'You have submitted you form successfully')\n return redirect('home')\n \n\nFor the second question - if I've understood correctly, you should be able to do it with a further filter on sub so that the query is only successful if the user has indicated yes :\nsub = SubmitData.objects.filter(user_id = user, sumit=True)\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_forms",
"html",
"python",
"templates"
] |
stackoverflow_0074510480_django_django_forms_html_python_templates.txt
|
Q:
How to create a polars data frame from a dictionary which has unequal length values?
I have a dictionary as:
ex_dict = {'A': ['false',
'true',
'false',
'false',
'false',
'true',
'true',
'false',
'false'],
'B': ['false',
'false',
'true',
'false',
'false',
'false'],
'C': ['false',
'true',
'true',
'false',
'false',
'false',
'false',
'false',
'true']}
I'm creating a dataframe as:
pl.DataFrame(ex_dict)
on executing it gives an error as:
ShapeError: Could not create a new DataFrame from Series. The Series have different lengths.Got [shape: (9,)
How to create a polars dataframe in these scenarios ?
A:
You can place each Series into its own DataFrame, and use a concat with how="horizontal". This will automatically extend shorter Series with null values.
pl.concat(
items=[pl.DataFrame({_name: _values})
for _name, _values in ex_dict.items()],
how="horizontal",
)
shape: (9, 3)
┌───────┬───────┬───────┐
│ A ┆ B ┆ C │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═══════╪═══════╪═══════╡
│ false ┆ false ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ true ┆ false ┆ true │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ true ┆ true │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ false ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ false ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ true ┆ false ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ true ┆ null ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ null ┆ false │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ false ┆ null ┆ true │
└───────┴───────┴───────┘
|
How to create a polars data frame from a dictionary which has unequal length values?
|
I have a dictionary as:
ex_dict = {'A': ['false',
'true',
'false',
'false',
'false',
'true',
'true',
'false',
'false'],
'B': ['false',
'false',
'true',
'false',
'false',
'false'],
'C': ['false',
'true',
'true',
'false',
'false',
'false',
'false',
'false',
'true']}
I'm creating a dataframe as:
pl.DataFrame(ex_dict)
on executing it gives an error as:
ShapeError: Could not create a new DataFrame from Series. The Series have different lengths.Got [shape: (9,)
How to create a polars dataframe in these scenarios ?
|
[
"You can place each Series into its own DataFrame, and use a concat with how=\"horizontal\". This will automatically extend shorter Series with null values.\npl.concat(\n items=[pl.DataFrame({_name: _values})\n for _name, _values in ex_dict.items()],\n how=\"horizontal\",\n)\n\nshape: (9, 3)\n┌───────┬───────┬───────┐\n│ A ┆ B ┆ C │\n│ --- ┆ --- ┆ --- │\n│ str ┆ str ┆ str │\n╞═══════╪═══════╪═══════╡\n│ false ┆ false ┆ false │\n├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤\n│ true ┆ false ┆ true │\n├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤\n│ false ┆ true ┆ true │\n├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤\n│ false ┆ false ┆ false │\n├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤\n│ false ┆ false ┆ false │\n├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤\n│ true ┆ false ┆ false │\n├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤\n│ true ┆ null ┆ false │\n├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤\n│ false ┆ null ┆ false │\n├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤\n│ false ┆ null ┆ true │\n└───────┴───────┴───────┘\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_polars"
] |
stackoverflow_0074427780_python_python_polars.txt
|
Q:
button class creates another screen to show buttons instead of displaying on exisiting screen
I have created a screen in pygame and want to display command buttons on it. for that i have written a code containing button class but it creates another screen instead of displaying the buttons on the same screen. can anyone tell me where i have gone wrong?
# import the pygame module
import pygame
import sys
pygame.init()
width, height =1550,800
fps = 60
fpsClock = pygame.time.Clock()
screen=pygame.display.set_mode((width, height))
font=pygame.font.SysFont('arial',40)
objects = []
pygame.display.set_caption('image')
imp=pygame.image.load("D:/PycharmProjects/flay high bangtan/flappy bird\sprites/background/main page.jpg")
screen.blit(imp,(0,0))
pygame.display.flip()
status=True
while (status):
for i in pygame.event.get():
if i.type == pygame.QUIT:
status=False
#COMMAND BUTTONS
class Button():
def __init__(self, x, y, width, height, buttonText='Button', onclickFunction=None, onePress=False):
self.x = x
self.y = y
self.width = width
self.height = height
self.onclickFunction = onclickFunction
self.onePress = onePress
self.fillColors = {
'normal': '#ffffff',
'hover': '#666666',
'pressed': '#333333',
}
self.buttonSurface = pygame.Surface((self.width, self.height))
self.buttonRect = pygame.Rect(self.x, self.y, self.width, self.height)
self.buttonSurf = font.render(buttonText, True, (20, 20, 20))
self.alreadyPressed = False
objects.append(self)
def process(self):
mousePos = pygame.mouse.get_pos()
self.buttonSurface.fill(self.fillColors['normal'])
if self.buttonRect.collidepoint(mousePos):
self.buttonSurface.fill(self.fillColors['hover'])
if pygame.mouse.get_pressed(num_buttons=3)[0]:
self.buttonSurface.fill(self.fillColors['pressed'])
if self.onePress:
self.onclickFunction()
elif not self.alreadyPressed:
self.onclickFunction()
self.alreadyPressed = True
else:
self.alreadyPressed = False
self.buttonSurface.blit(self.buttonSurf, [
self.buttonRect.width / 2 - self.buttonSurf.get_rect().width / 2,
self.buttonRect.height / 2 - self.buttonSurf.get_rect().height / 2
])
screen.blit(self.buttonSurface, self.buttonRect)
def myFunction():
print('Button Pressed')
customButton = Button(30, 30, 400, 100, 'PLAY', myFunction)
customButton = Button(30, 140, 400, 100, 'ABOUT US', myFunction)
customButton = Button(30, 250, 400, 100, 'EXIT', myFunction)
# Game loop.
while True:
screen.fill((20, 20, 20))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
for object in objects:
object.process()
pygame.display.flip()
fpsClock.tick(fps)
pygame.QUIT()
this is code to create a screen in pygame and display buttons on it. but when i run it i get one screen that shows my image and after closing it i get another screen with buttons. but i am not understanding how to put those buttons on the same screen as that of the iamge.
A:
You have 2 application loops. Remove the 1st application loop, but draw the background image in the second application loop:
# DELETE
#screen.blit(imp,(0,0))
#pygame.display.flip()
#status=True
#while (status):
# for i in pygame.event.get():
# if i.type == pygame.QUIT:
# status=False
# [...]
# Game loop.
while True:
# DELETE
# screen.fill((20, 20, 20))
# INSERT
screen.blit(imp,(0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
for object in objects:
object.process()
pygame.display.flip()
fpsClock.tick(fps)
pygame.quit()
|
button class creates another screen to show buttons instead of displaying on exisiting screen
|
I have created a screen in pygame and want to display command buttons on it. for that i have written a code containing button class but it creates another screen instead of displaying the buttons on the same screen. can anyone tell me where i have gone wrong?
# import the pygame module
import pygame
import sys
pygame.init()
width, height =1550,800
fps = 60
fpsClock = pygame.time.Clock()
screen=pygame.display.set_mode((width, height))
font=pygame.font.SysFont('arial',40)
objects = []
pygame.display.set_caption('image')
imp=pygame.image.load("D:/PycharmProjects/flay high bangtan/flappy bird\sprites/background/main page.jpg")
screen.blit(imp,(0,0))
pygame.display.flip()
status=True
while (status):
for i in pygame.event.get():
if i.type == pygame.QUIT:
status=False
#COMMAND BUTTONS
class Button():
def __init__(self, x, y, width, height, buttonText='Button', onclickFunction=None, onePress=False):
self.x = x
self.y = y
self.width = width
self.height = height
self.onclickFunction = onclickFunction
self.onePress = onePress
self.fillColors = {
'normal': '#ffffff',
'hover': '#666666',
'pressed': '#333333',
}
self.buttonSurface = pygame.Surface((self.width, self.height))
self.buttonRect = pygame.Rect(self.x, self.y, self.width, self.height)
self.buttonSurf = font.render(buttonText, True, (20, 20, 20))
self.alreadyPressed = False
objects.append(self)
def process(self):
mousePos = pygame.mouse.get_pos()
self.buttonSurface.fill(self.fillColors['normal'])
if self.buttonRect.collidepoint(mousePos):
self.buttonSurface.fill(self.fillColors['hover'])
if pygame.mouse.get_pressed(num_buttons=3)[0]:
self.buttonSurface.fill(self.fillColors['pressed'])
if self.onePress:
self.onclickFunction()
elif not self.alreadyPressed:
self.onclickFunction()
self.alreadyPressed = True
else:
self.alreadyPressed = False
self.buttonSurface.blit(self.buttonSurf, [
self.buttonRect.width / 2 - self.buttonSurf.get_rect().width / 2,
self.buttonRect.height / 2 - self.buttonSurf.get_rect().height / 2
])
screen.blit(self.buttonSurface, self.buttonRect)
def myFunction():
print('Button Pressed')
customButton = Button(30, 30, 400, 100, 'PLAY', myFunction)
customButton = Button(30, 140, 400, 100, 'ABOUT US', myFunction)
customButton = Button(30, 250, 400, 100, 'EXIT', myFunction)
# Game loop.
while True:
screen.fill((20, 20, 20))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
for object in objects:
object.process()
pygame.display.flip()
fpsClock.tick(fps)
pygame.QUIT()
this is code to create a screen in pygame and display buttons on it. but when i run it i get one screen that shows my image and after closing it i get another screen with buttons. but i am not understanding how to put those buttons on the same screen as that of the iamge.
|
[
"You have 2 application loops. Remove the 1st application loop, but draw the background image in the second application loop:\n# DELETE\n#screen.blit(imp,(0,0))\n#pygame.display.flip()\n#status=True\n#while (status):\n# for i in pygame.event.get():\n# if i.type == pygame.QUIT:\n# status=False\n\n# [...]\n\n# Game loop.\nwhile True:\n \n # DELETE\n # screen.fill((20, 20, 20))\n \n # INSERT\n screen.blit(imp,(0,0))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n for object in objects:\n object.process()\n\n pygame.display.flip()\n fpsClock.tick(fps)\n\npygame.quit()\n\n"
] |
[
0
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0074502674_pygame_python.txt
|
Q:
Await only for some time in Python
So waiting for server can bring pain:
import asyncio
#...
greeting = await websocket.recv() # newer ends
I want to have something like
greeting = await websocket.recv() for seconds(10)
So how to await only for a limited amount of time in Python?
A:
await expressions don't have a timeout parameter, but the asyncio.wait_for (thanks to AChampion) function does. My guess is that this is so that the await expression, tied to coroutine definition in the language itself, does not rely on having clocks or a specific event loop. That functionality is left to the asyncio module of the standard library.
A:
I use this in a try: except: block,
time_seconds = 60
try:
result = await asyncio.wait_for(websocket.recv(), timeout=time_seconds)
print(result)
except Exception as e:
if str(type(e)) == "<class 'asyncio.exceptions.TimeoutError'>":
print('specifically a asyncio TimeoutError')
else:
Print('different error:', e)
if the timeout occurs before the message is received, then one gets a TimeoutError error.
The timeout error is this:
<class 'asyncio.exceptions.TimeoutError'>
which you can then handle differently from other genuine errors.
|
Await only for some time in Python
|
So waiting for server can bring pain:
import asyncio
#...
greeting = await websocket.recv() # newer ends
I want to have something like
greeting = await websocket.recv() for seconds(10)
So how to await only for a limited amount of time in Python?
|
[
"await expressions don't have a timeout parameter, but the asyncio.wait_for (thanks to AChampion) function does. My guess is that this is so that the await expression, tied to coroutine definition in the language itself, does not rely on having clocks or a specific event loop. That functionality is left to the asyncio module of the standard library. \n",
"I use this in a try: except: block,\ntime_seconds = 60\ntry:\n result = await asyncio.wait_for(websocket.recv(), timeout=time_seconds)\n print(result)\n \nexcept Exception as e:\n if str(type(e)) == \"<class 'asyncio.exceptions.TimeoutError'>\": \n print('specifically a asyncio TimeoutError') \n else:\n Print('different error:', e)\n\nif the timeout occurs before the message is received, then one gets a TimeoutError error.\nThe timeout error is this:\n<class 'asyncio.exceptions.TimeoutError'>\n\nwhich you can then handle differently from other genuine errors.\n"
] |
[
8,
0
] |
[] |
[] |
[
"async_await",
"python",
"python_3.x"
] |
stackoverflow_0045229304_async_await_python_python_3.x.txt
|
Q:
Python googleapiclient cannot get more than 10 results
With this code:
import json
from googleapiclient.discovery import build
from pprint import pprint as pp
NUM_RESULTS = 11
MY_SEARCH = 'bordben'
MY_API_KEY = '...'
MY_CSE_ID = '...'
def google_search(search_term, api_key, cse_id, **kwargs):
service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
return res['items']
results = google_search(MY_SEARCH, MY_API_KEY, MY_CSE_ID, num=NUM_RESULTS)
for result in results:
pp(result)
if NUM_RESULTS greater than 10 I will get an error like this:
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://customsearch.googleapis.com/customsearch/v1?q=bordben&cx=...( api key and csi id)&alt=json returned "Request contains an invalid argument.". Details: "[{'message': 'Request contains an invalid argument.', 'domain': 'global', 'reason': 'badRequest'}]">
if NUM_RESULTS = 10 or less than 10, there will print the search results. , why there is a limit by 10?
A:
Found the answer here:
https://gist.github.com/adambernier/0cc96d07691a635cc464d24c63caff39
each API call not be greater then 10 results.
|
Python googleapiclient cannot get more than 10 results
|
With this code:
import json
from googleapiclient.discovery import build
from pprint import pprint as pp
NUM_RESULTS = 11
MY_SEARCH = 'bordben'
MY_API_KEY = '...'
MY_CSE_ID = '...'
def google_search(search_term, api_key, cse_id, **kwargs):
service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
return res['items']
results = google_search(MY_SEARCH, MY_API_KEY, MY_CSE_ID, num=NUM_RESULTS)
for result in results:
pp(result)
if NUM_RESULTS greater than 10 I will get an error like this:
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://customsearch.googleapis.com/customsearch/v1?q=bordben&cx=...( api key and csi id)&alt=json returned "Request contains an invalid argument.". Details: "[{'message': 'Request contains an invalid argument.', 'domain': 'global', 'reason': 'badRequest'}]">
if NUM_RESULTS = 10 or less than 10, there will print the search results. , why there is a limit by 10?
|
[
"Found the answer here:\nhttps://gist.github.com/adambernier/0cc96d07691a635cc464d24c63caff39\neach API call not be greater then 10 results.\n"
] |
[
0
] |
[] |
[] |
[
"google_api_client",
"python"
] |
stackoverflow_0074510694_google_api_client_python.txt
|
Q:
arbitrary polygon with transparency in pygame
I know of pygame.draw.polygon() but that can only handle colors with no alpha value. Is there an analogous function somewhere that can? I searched for a bit and did not find anything, so I tried writing my own. somehow it misses pixels occasionally (it's worth noting it only needs to work for convex quadrilaterals). here it is, apologies in advance for the poorly written inefficient code:
def fill_quad(A, B, C, D, color=(0, 255, 100, 100)):
M = quad_center(A, B, C, D);
dxA, dyA = A[0] - M[0], A[1] - M[1];
dxB, dyB = B[0] - M[0], B[1] - M[1];
dxC, dyC = C[0] - M[0], C[1] - M[1];
dxD, dyD = D[0] - M[0], D[1] - M[1];
dist = max(math.hypot(dxA, dyA), math.hypot(dxB, dyB), math.hypot(dxC, dyC), math.hypot(dxD, dyD));
dxA, dyA, dxB, dyB, dxC, dyC, dxD, dyD = map(lambda d: d / dist, (dxA, dyA, dxB, dyB, dxC, dyC, dxD, dyD));
for i in range(0, int(dist)+1, 1):
connect(A, B, C, D, color=color);
A = A[0] - dxA, A[1] - dyA;
B = B[0] - dxB, B[1] - dyB;
C = C[0] - dxC, C[1] - dyC;
D = D[0] - dxD, D[1] - dyD;
quad_center returns the center of the polygon formed by four points and connect connects points like pygame.draw.lines except it can do transparency. The trouble seems to be with dxA, dxB, etc. and dyA, dyB, etc. (as in they are too big of steps) which is why it misses pixels. The issue is not with my connect function because I have the same problem when using pygame's builtins. In order to run this on your computer just replace connect(A, B, C, D, color=color) with pygame.draw.lines(screen, color, True, (A, B, C, D)) and use this for quad_center:
def midpoint(A, B):
return (A[0] + B[0]) / 2, (A[1] + B[1]) / 2;
def quad_center(A, B, C, D):
return midpoint(midpoint(A, B), midpoint(C, D));
Just for completeness here is an example of what I mean when I say "missing pixels":
Each one of those quadrilaterals is drawn with my function. You can see the little blue streaks everywhere, that's what I'm referring to.
If a function like this already exists, obviously I prefer that, but if not any help with the function that I wrote is appreciated. thanks for any help.
A:
Pygame cannot draw transparent shapes or draw and blend them simultaneously. The only way is to draw single shapes on pygame.Surface with an alpha channel (pygame.SRCALPHA) and blend that surface with the target surface. Also see Draw a transparent rectangles and polygons in pygame.
|
arbitrary polygon with transparency in pygame
|
I know of pygame.draw.polygon() but that can only handle colors with no alpha value. Is there an analogous function somewhere that can? I searched for a bit and did not find anything, so I tried writing my own. somehow it misses pixels occasionally (it's worth noting it only needs to work for convex quadrilaterals). here it is, apologies in advance for the poorly written inefficient code:
def fill_quad(A, B, C, D, color=(0, 255, 100, 100)):
M = quad_center(A, B, C, D);
dxA, dyA = A[0] - M[0], A[1] - M[1];
dxB, dyB = B[0] - M[0], B[1] - M[1];
dxC, dyC = C[0] - M[0], C[1] - M[1];
dxD, dyD = D[0] - M[0], D[1] - M[1];
dist = max(math.hypot(dxA, dyA), math.hypot(dxB, dyB), math.hypot(dxC, dyC), math.hypot(dxD, dyD));
dxA, dyA, dxB, dyB, dxC, dyC, dxD, dyD = map(lambda d: d / dist, (dxA, dyA, dxB, dyB, dxC, dyC, dxD, dyD));
for i in range(0, int(dist)+1, 1):
connect(A, B, C, D, color=color);
A = A[0] - dxA, A[1] - dyA;
B = B[0] - dxB, B[1] - dyB;
C = C[0] - dxC, C[1] - dyC;
D = D[0] - dxD, D[1] - dyD;
quad_center returns the center of the polygon formed by four points and connect connects points like pygame.draw.lines except it can do transparency. The trouble seems to be with dxA, dxB, etc. and dyA, dyB, etc. (as in they are too big of steps) which is why it misses pixels. The issue is not with my connect function because I have the same problem when using pygame's builtins. In order to run this on your computer just replace connect(A, B, C, D, color=color) with pygame.draw.lines(screen, color, True, (A, B, C, D)) and use this for quad_center:
def midpoint(A, B):
return (A[0] + B[0]) / 2, (A[1] + B[1]) / 2;
def quad_center(A, B, C, D):
return midpoint(midpoint(A, B), midpoint(C, D));
Just for completeness here is an example of what I mean when I say "missing pixels":
Each one of those quadrilaterals is drawn with my function. You can see the little blue streaks everywhere, that's what I'm referring to.
If a function like this already exists, obviously I prefer that, but if not any help with the function that I wrote is appreciated. thanks for any help.
|
[
"Pygame cannot draw transparent shapes or draw and blend them simultaneously. The only way is to draw single shapes on pygame.Surface with an alpha channel (pygame.SRCALPHA) and blend that surface with the target surface. Also see Draw a transparent rectangles and polygons in pygame.\n"
] |
[
0
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0055892066_pygame_python.txt
|
Q:
Is there a way to simplify this function using a one-line comprehension in python?
simple question, as the title implies. I was hoping to use the zip function but can't get it to work for some reason.
def tuple_sum(A, B):
out = []
for a,b in [x for x in zip(A,B)]:
out1 = []
for a1, b1 in zip(a, b):
out1.append(a1+b1)
out.append(out1)
return out
A:
Maybe something like this?
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
s = [[a1 + b1 for a1, b1 in zip(a, b)] for a, b in zip(A, B)]
print(s) # [[6, 8], [10, 12]]
|
Is there a way to simplify this function using a one-line comprehension in python?
|
simple question, as the title implies. I was hoping to use the zip function but can't get it to work for some reason.
def tuple_sum(A, B):
out = []
for a,b in [x for x in zip(A,B)]:
out1 = []
for a1, b1 in zip(a, b):
out1.append(a1+b1)
out.append(out1)
return out
|
[
"Maybe something like this?\nA = [[1, 2], [3, 4]]\nB = [[5, 6], [7, 8]]\ns = [[a1 + b1 for a1, b1 in zip(a, b)] for a, b in zip(A, B)]\nprint(s) # [[6, 8], [10, 12]]\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074512101_python.txt
|
Q:
How to use polars to get the rolling values for two dataframes col by col?
For example, I have two dataframes like:
X = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)})
Y = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)})
In pandas, the rolling calculation of two DFs col by col (the columns with same id) can be writen easily by:
# rolling corr:
X.rolling(5).corr(Y)
# rolling cov:
X.rolling(5).cov(Y)
# rolling slope:
X.rolling(5).cov(Y) / X.rolling(5).var()
How to use polars to implement such calculations?
Thanks!
A:
Let's start with setting up the dataframe:
import polars as pl
import numpy as np
X = pl.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)})
There is currently no built-in rolling_covarance, in contrast to for instance rolling_var
Thus we need two things:
set up the rolling bit. For this we use groupby_rolling
the actual covariance computation, using polars.cov
My solution:
# define a small helper function
def my_cov(c1: str, c2: str):
return pl.cov(pl.col(c1),pl.col(c2)).alias(c1 + "_" + c2)
X.with_row_count()
.with_column(pl.col("row_nr").cast(pl.Int32))
.groupby_rolling(index_column="row_nr", period="5i")
.agg([my_cov(c1, c2) for c1 in X.columns for c2 in X.columns])
Lets break this down:
groupby_rolling needs an index column. In contrast to Pandas, polars does not have indices. Usually that works out great, but this is one case where an index is handy. Polars solves this by allowing you to specify the column to use as index. X does not have an index column yet, so we create one using with_row_count, which emits it as row_nr and ensure it is int32, not the default uint32 (for some reason groupby_rolling does not like unsigned integers as index column)
the "5i" says we want a window of 5 observations
the agg defines what we want to do for each row (including lookback). For each combination of columns in X, we want a covariance to be computed for that row. We use a list comprehension to set up the Polars expressions. agg will compute those in parallel. I factored out a bit of boilerplate into my_cov to keep the list comprehension readable.
Snapshot of the output:
shape: (200, 10001)
┌────────┬──────────┬──────────┬───────────┬─────┬───────────┬───────────┬───────────┬───────────┐
│ row_nr ┆ id0_id0 ┆ id0_id1 ┆ id0_id2 ┆ ... ┆ id99_id96 ┆ id99_id97 ┆ id99_id98 ┆ id99_id99 │
│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │
│ i32 ┆ f64 ┆ f64 ┆ f64 ┆ ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════╪══════════╪══════════╪═══════════╪═════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ 0 ┆ NaN ┆ NaN ┆ NaN ┆ ... ┆ NaN ┆ NaN ┆ NaN ┆ NaN │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1 ┆ 0.684141 ┆ 0.083535 ┆ -0.851174 ┆ ... ┆ -0.481743 ┆ -0.352858 ┆ -1.012102 ┆ 0.786184 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ 0.343157 ┆ 0.017021 ┆ -0.427508 ┆ ... ┆ 0.356765 ┆ 0.322567 ┆ -0.267278 ┆ 1.029365 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
The nice thing is that you can easily create more complicated expressions:
def my_beta(c1, c2):
cov = pl.cov(pl.col(c1),pl.col(c2))
return (cov / pl.col(c2).var()).alias(c1 + "_" + c2)
would give the beta of c1 to c2.
A:
Here's a simple way to accomplish this, and still use lazy:
dfX = pl.from_pandas(X).lazy()
dfY = pl.from_pandas(Y).lazy()
(
dfX
.with_row_count()
.with_column(pl.col('row_nr').cast(pl.Int32))
.with_context(
dfY.select(
pl.all().map_alias(lambda col_nm: col_nm + "Y")
)
)
.groupby_rolling(
index_column='row_nr',
period='5i',
)
.agg([
pl.cov(col_nm, col_nm + 'Y')
for col_nm in dfX.columns
])
.collect()
)
shape: (200, 101)
┌────────┬───────────┬───────────┬───────────┬─────┬───────────┬───────────┬──────────┬───────────┐
│ row_nr ┆ id0 ┆ id1 ┆ id2 ┆ ... ┆ id96 ┆ id97 ┆ id98 ┆ id99 │
│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │
│ i32 ┆ f64 ┆ f64 ┆ f64 ┆ ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════╪═══════════╪═══════════╪═══════════╪═════╪═══════════╪═══════════╪══════════╪═══════════╡
│ 0 ┆ NaN ┆ NaN ┆ NaN ┆ ... ┆ NaN ┆ NaN ┆ NaN ┆ NaN │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1 ┆ 0.198871 ┆ 0.021116 ┆ 0.140828 ┆ ... ┆ -0.023675 ┆ 1.240579 ┆ 0.457514 ┆ -0.486475 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ 0.153685 ┆ -0.246208 ┆ 0.008931 ┆ ... ┆ -0.622545 ┆ -0.830773 ┆ 0.446357 ┆ -0.21538 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ 0.235759 ┆ -0.156201 ┆ -0.111072 ┆ ... ┆ -0.270532 ┆ -0.92131 ┆ 0.247192 ┆ -0.200723 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 196 ┆ -0.212265 ┆ 0.069828 ┆ -0.332518 ┆ ... ┆ 0.243745 ┆ 0.097037 ┆ 0.199009 ┆ 0.776244 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 197 ┆ 0.529492 ┆ 0.117366 ┆ -0.285602 ┆ ... ┆ 0.192653 ┆ 0.08174 ┆ 0.127401 ┆ 0.490955 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 198 ┆ 0.315249 ┆ -0.117771 ┆ 0.019203 ┆ ... ┆ 0.345703 ┆ -0.318349 ┆ 0.467904 ┆ 0.426183 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 199 ┆ 0.125482 ┆ 0.02746 ┆ 0.053431 ┆ ... ┆ 0.072234 ┆ -0.172202 ┆ 0.662359 ┆ -0.312281 │
└────────┴───────────┴───────────┴───────────┴─────┴───────────┴───────────┴──────────┴───────────┘
|
How to use polars to get the rolling values for two dataframes col by col?
|
For example, I have two dataframes like:
X = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)})
Y = pd.DataFrame({f"id{i}": np.random.randn(200) for i in range(100)})
In pandas, the rolling calculation of two DFs col by col (the columns with same id) can be writen easily by:
# rolling corr:
X.rolling(5).corr(Y)
# rolling cov:
X.rolling(5).cov(Y)
# rolling slope:
X.rolling(5).cov(Y) / X.rolling(5).var()
How to use polars to implement such calculations?
Thanks!
|
[
"Let's start with setting up the dataframe:\nimport polars as pl\nimport numpy as np\nX = pl.DataFrame({f\"id{i}\": np.random.randn(200) for i in range(100)})\n\nThere is currently no built-in rolling_covarance, in contrast to for instance rolling_var\nThus we need two things:\n\nset up the rolling bit. For this we use groupby_rolling\nthe actual covariance computation, using polars.cov\n\nMy solution:\n# define a small helper function\ndef my_cov(c1: str, c2: str):\n return pl.cov(pl.col(c1),pl.col(c2)).alias(c1 + \"_\" + c2)\n\nX.with_row_count()\n.with_column(pl.col(\"row_nr\").cast(pl.Int32))\n.groupby_rolling(index_column=\"row_nr\", period=\"5i\")\n.agg([my_cov(c1, c2) for c1 in X.columns for c2 in X.columns])\n\nLets break this down:\n\ngroupby_rolling needs an index column. In contrast to Pandas, polars does not have indices. Usually that works out great, but this is one case where an index is handy. Polars solves this by allowing you to specify the column to use as index. X does not have an index column yet, so we create one using with_row_count, which emits it as row_nr and ensure it is int32, not the default uint32 (for some reason groupby_rolling does not like unsigned integers as index column)\nthe \"5i\" says we want a window of 5 observations\nthe agg defines what we want to do for each row (including lookback). For each combination of columns in X, we want a covariance to be computed for that row. We use a list comprehension to set up the Polars expressions. agg will compute those in parallel. I factored out a bit of boilerplate into my_cov to keep the list comprehension readable.\n\nSnapshot of the output:\nshape: (200, 10001)\n┌────────┬──────────┬──────────┬───────────┬─────┬───────────┬───────────┬───────────┬───────────┐\n│ row_nr ┆ id0_id0 ┆ id0_id1 ┆ id0_id2 ┆ ... ┆ id99_id96 ┆ id99_id97 ┆ id99_id98 ┆ id99_id99 │\n│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │\n│ i32 ┆ f64 ┆ f64 ┆ f64 ┆ ┆ f64 ┆ f64 ┆ f64 ┆ f64 │\n╞════════╪══════════╪══════════╪═══════════╪═════╪═══════════╪═══════════╪═══════════╪═══════════╡\n│ 0 ┆ NaN ┆ NaN ┆ NaN ┆ ... ┆ NaN ┆ NaN ┆ NaN ┆ NaN │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 0.684141 ┆ 0.083535 ┆ -0.851174 ┆ ... ┆ -0.481743 ┆ -0.352858 ┆ -1.012102 ┆ 0.786184 │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 0.343157 ┆ 0.017021 ┆ -0.427508 ┆ ... ┆ 0.356765 ┆ 0.322567 ┆ -0.267278 ┆ 1.029365 │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n\nThe nice thing is that you can easily create more complicated expressions:\ndef my_beta(c1, c2):\n cov = pl.cov(pl.col(c1),pl.col(c2))\n return (cov / pl.col(c2).var()).alias(c1 + \"_\" + c2)\n\nwould give the beta of c1 to c2.\n",
"Here's a simple way to accomplish this, and still use lazy:\ndfX = pl.from_pandas(X).lazy()\ndfY = pl.from_pandas(Y).lazy()\n\n(\n dfX\n .with_row_count()\n .with_column(pl.col('row_nr').cast(pl.Int32))\n .with_context(\n dfY.select(\n pl.all().map_alias(lambda col_nm: col_nm + \"Y\")\n )\n )\n .groupby_rolling(\n index_column='row_nr',\n period='5i',\n )\n .agg([\n pl.cov(col_nm, col_nm + 'Y')\n for col_nm in dfX.columns\n ])\n .collect()\n)\n\nshape: (200, 101)\n┌────────┬───────────┬───────────┬───────────┬─────┬───────────┬───────────┬──────────┬───────────┐\n│ row_nr ┆ id0 ┆ id1 ┆ id2 ┆ ... ┆ id96 ┆ id97 ┆ id98 ┆ id99 │\n│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │\n│ i32 ┆ f64 ┆ f64 ┆ f64 ┆ ┆ f64 ┆ f64 ┆ f64 ┆ f64 │\n╞════════╪═══════════╪═══════════╪═══════════╪═════╪═══════════╪═══════════╪══════════╪═══════════╡\n│ 0 ┆ NaN ┆ NaN ┆ NaN ┆ ... ┆ NaN ┆ NaN ┆ NaN ┆ NaN │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 1 ┆ 0.198871 ┆ 0.021116 ┆ 0.140828 ┆ ... ┆ -0.023675 ┆ 1.240579 ┆ 0.457514 ┆ -0.486475 │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 2 ┆ 0.153685 ┆ -0.246208 ┆ 0.008931 ┆ ... ┆ -0.622545 ┆ -0.830773 ┆ 0.446357 ┆ -0.21538 │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 3 ┆ 0.235759 ┆ -0.156201 ┆ -0.111072 ┆ ... ┆ -0.270532 ┆ -0.92131 ┆ 0.247192 ┆ -0.200723 │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 196 ┆ -0.212265 ┆ 0.069828 ┆ -0.332518 ┆ ... ┆ 0.243745 ┆ 0.097037 ┆ 0.199009 ┆ 0.776244 │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 197 ┆ 0.529492 ┆ 0.117366 ┆ -0.285602 ┆ ... ┆ 0.192653 ┆ 0.08174 ┆ 0.127401 ┆ 0.490955 │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 198 ┆ 0.315249 ┆ -0.117771 ┆ 0.019203 ┆ ... ┆ 0.345703 ┆ -0.318349 ┆ 0.467904 ┆ 0.426183 │\n├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤\n│ 199 ┆ 0.125482 ┆ 0.02746 ┆ 0.053431 ┆ ... ┆ 0.072234 ┆ -0.172202 ┆ 0.662359 ┆ -0.312281 │\n└────────┴───────────┴───────────┴───────────┴─────┴───────────┴───────────┴──────────┴───────────┘\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"data_processing",
"python",
"python_polars"
] |
stackoverflow_0074418401_data_processing_python_python_polars.txt
|
Q:
Not getting expected data from SQL Server in Python
I've been following a course, and I want to change my data source from sqlite to mssql.
I've made the connection, and i'm trying to list the users in my db.
But when I do I get the result show below:
<Users 2>
<Users 3>
Instead of showing the actual user data.
Ive uploaded the code to git:
https://github.com/Desc83/flask_mssql
import urllib
import os
import pyodbc
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from flask import Flask, render_template, url_for, redirect
from flask import Flask
from flask import current_app
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mssql://@Localhost/FlaskMSSQL?driver=ODBC Driver 17 for SQL Server"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
Migrate(app,db)
db.init_app(app)
class Users(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key= True)
Username = db.Column(db.Text)
Password = db.Column(db.Text)
Email = db.Column(db.Text)
def __init__(self,name):
self.name = name
@app.route('/users')
def listUsers():
users = Users.query.all()
test = Users.
return render_template('listuers.html', users=users)
@app.route('/')
def index():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
view:
{% extends "base.html" %}
{% block content %}
<div class="jumbotron">
<p>list users</p>
<ul>
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
{% for item in user %}
<li>{{item}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
I have tried to split the data into bits, but it comes with the same result:
{% extends "base.html" %}
{% block content %}
<div class="jumbotron">
<p>list users</p>
<ul>
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
{% for item in user %}
<li>{{item}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
A:
It appears as if you need to specify the __str__ for the Users class.
Alternatively, you can explicitly indicate the fields you want to display in the template.
Instead of this:
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
Try this:
{% for user in users %}
<li>{{user.Username}}</li>
{% endfor %}
|
Not getting expected data from SQL Server in Python
|
I've been following a course, and I want to change my data source from sqlite to mssql.
I've made the connection, and i'm trying to list the users in my db.
But when I do I get the result show below:
<Users 2>
<Users 3>
Instead of showing the actual user data.
Ive uploaded the code to git:
https://github.com/Desc83/flask_mssql
import urllib
import os
import pyodbc
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from flask import Flask, render_template, url_for, redirect
from flask import Flask
from flask import current_app
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mssql://@Localhost/FlaskMSSQL?driver=ODBC Driver 17 for SQL Server"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
Migrate(app,db)
db.init_app(app)
class Users(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key= True)
Username = db.Column(db.Text)
Password = db.Column(db.Text)
Email = db.Column(db.Text)
def __init__(self,name):
self.name = name
@app.route('/users')
def listUsers():
users = Users.query.all()
test = Users.
return render_template('listuers.html', users=users)
@app.route('/')
def index():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
view:
{% extends "base.html" %}
{% block content %}
<div class="jumbotron">
<p>list users</p>
<ul>
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
{% for item in user %}
<li>{{item}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
I have tried to split the data into bits, but it comes with the same result:
{% extends "base.html" %}
{% block content %}
<div class="jumbotron">
<p>list users</p>
<ul>
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
{% for item in user %}
<li>{{item}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
|
[
"It appears as if you need to specify the __str__ for the Users class.\nAlternatively, you can explicitly indicate the fields you want to display in the template.\nInstead of this:\n{% for user in users %}\n<li>{{user}}</li>\n{% endfor %}\n\nTry this:\n{% for user in users %}\n<li>{{user.Username}}</li>\n{% endfor %}\n\n"
] |
[
1
] |
[] |
[] |
[
"flask",
"python",
"sql_server",
"sqlalchemy"
] |
stackoverflow_0074512125_flask_python_sql_server_sqlalchemy.txt
|
Q:
Matplotlib Rectangle.Contains(event) always returns true
I want to detect the button_press and button_release events on matplotlib.patches.Rectangle areas next to my figure to enable the user to move/rescale individual y-axes when using Twinx().
However, rectangle.Contains(event) always seems to return true, no matter where I click. E.g: when click on the red bar in the figure below, Rectangle1, 2 and 3 are all being printed.
A working example:
import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
import matplotlib
fig, ax = plt.subplots()
plt.plot([1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10])
spine_width=20
color = ["red", "green", "blue"]
for i in range(3):
shift = (spine_width * i + 0.5*spine_width)
offset_vec = (1, 0)
offset_dots = shift * np.array(offset_vec) / 72
combitransform = ( ax.transAxes
+ mtransforms.ScaledTranslation(
*offset_dots, fig.canvas.figure.dpi_scale_trans))
rectangle = matplotlib.patches.Rectangle((1, 0), 0, 1, lw=spine_width, ec=color[i], alpha=1, transform=combitransform, clip_on=False)
ax.add_patch(rectangle)
def on_press(event, rectangle, i):
if rectangle.contains(event):
print(f"Clicked on rectangle {i+1} at {event.x} {event.y}!")
fig.canvas.mpl_connect('button_press_event', lambda event, rectangle=rectangle, i=i: on_press(event, rectangle, i))
plt.show()
A:
The problem was probably the fact that the width of the rectangle was zero in my code (lw does not seem to contribute to the click-hitbox). Although it is not entirely clear to me why this would always result in rectangle.contains(event) to evaluate to True.
This ended up working (although transformations are still a bit vague to me, so there might be a better solution):
import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
import matplotlib
fig, ax = plt.subplots()
plt.plot([1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10])
spine_width=20
color = ["red", "green", "blue"]
for i in range(3):
x_transform = mtransforms.IdentityTransform() + mtransforms.ScaledTranslation(1,0 , ax.transAxes)
transform = mtransforms.blended_transform_factory(x_transform, ax.transAxes) #x-axis in pixels, y-axis in axes coords (0, 1)
rectangle = matplotlib.patches.Rectangle((spine_width*i, 0), 20, 1, ec=color[i], fc=color[i], alpha=1, transform=transform, clip_on=False)
ax.add_artist(rectangle)
def on_press(event, rectangle, i):
#Check if click is inside rectangle
if rectangle.contains_point((event.x, event.y)):
print("Click inside rectangle", i)
fig.canvas.mpl_connect('button_press_event', lambda event, rectangle=rectangle, i=i: on_press(event, rectangle, i))
plt.show()
|
Matplotlib Rectangle.Contains(event) always returns true
|
I want to detect the button_press and button_release events on matplotlib.patches.Rectangle areas next to my figure to enable the user to move/rescale individual y-axes when using Twinx().
However, rectangle.Contains(event) always seems to return true, no matter where I click. E.g: when click on the red bar in the figure below, Rectangle1, 2 and 3 are all being printed.
A working example:
import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
import matplotlib
fig, ax = plt.subplots()
plt.plot([1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10])
spine_width=20
color = ["red", "green", "blue"]
for i in range(3):
shift = (spine_width * i + 0.5*spine_width)
offset_vec = (1, 0)
offset_dots = shift * np.array(offset_vec) / 72
combitransform = ( ax.transAxes
+ mtransforms.ScaledTranslation(
*offset_dots, fig.canvas.figure.dpi_scale_trans))
rectangle = matplotlib.patches.Rectangle((1, 0), 0, 1, lw=spine_width, ec=color[i], alpha=1, transform=combitransform, clip_on=False)
ax.add_patch(rectangle)
def on_press(event, rectangle, i):
if rectangle.contains(event):
print(f"Clicked on rectangle {i+1} at {event.x} {event.y}!")
fig.canvas.mpl_connect('button_press_event', lambda event, rectangle=rectangle, i=i: on_press(event, rectangle, i))
plt.show()
|
[
"The problem was probably the fact that the width of the rectangle was zero in my code (lw does not seem to contribute to the click-hitbox). Although it is not entirely clear to me why this would always result in rectangle.contains(event) to evaluate to True.\nThis ended up working (although transformations are still a bit vague to me, so there might be a better solution):\nimport matplotlib.transforms as mtransforms\nimport matplotlib.pyplot as plt\nimport matplotlib\nfig, ax = plt.subplots()\nplt.plot([1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10])\nspine_width=20\n\ncolor = [\"red\", \"green\", \"blue\"]\nfor i in range(3):\n x_transform = mtransforms.IdentityTransform() + mtransforms.ScaledTranslation(1,0 , ax.transAxes)\n transform = mtransforms.blended_transform_factory(x_transform, ax.transAxes) #x-axis in pixels, y-axis in axes coords (0, 1)\n rectangle = matplotlib.patches.Rectangle((spine_width*i, 0), 20, 1, ec=color[i], fc=color[i], alpha=1, transform=transform, clip_on=False)\n ax.add_artist(rectangle)\n\n def on_press(event, rectangle, i):\n #Check if click is inside rectangle\n if rectangle.contains_point((event.x, event.y)):\n print(\"Click inside rectangle\", i)\n\n fig.canvas.mpl_connect('button_press_event', lambda event, rectangle=rectangle, i=i: on_press(event, rectangle, i))\n\n\nplt.show()\n\n"
] |
[
0
] |
[] |
[] |
[
"contains",
"events",
"matplotlib",
"python"
] |
stackoverflow_0074511115_contains_events_matplotlib_python.txt
|
Q:
How can i make python shuffleCards program output one of each card and not random amounts
Python newbie
How can i make the output be 52 cards but one of each and not randomly created cards. As of now output becomes for example 2 clover, 2 clover, 5 diamonds .. etc.
I know its an issue with the shuffeling i am doing but i am not allowed to use "random.shuffle"
import math
import random
def main():
createDeck()
shuffleDeck()
printDeck()
deck = ['A'] * 52
def createDeck():
suits = [" Heart", " Spades", " Clover", " Diamonds"]
cardsHeld = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
for i in range(len(deck)):
deck[i] = cardsHeld[int(i%13)] + suits[int(i/13)]
def shuffleDeck():
rand=0
num = 0
for i in range(len(deck)):
rand = random.random()
num = rand * 52
num = math.floor(num)
deck[i] = deck[num]
def printDeck():
for i in range(len(deck)):
print(deck[i])
main()
I changed
def shuffleDeck():
rand=0
num = 0
for i in range(len(deck)):
rand = random.random()
num = rand * 52
num = math.floor(num)
deck[i] = deck[num]
with
def shuffleDeck():
random.shuffle(deck)
That worked however i am not allowed to use "random.shuffle(deck)" So im not sure how i should be doing the shuffeling then.
A:
When you do deck[i] = deck[num] you overwrite the value at index i while keeping the same value at index num. You need to swap the values with deck[i], deck[num] = deck[num], deck[i]. But there's no need to write something like this yourself. Simply use one line of code with random.shuffle from Pythons standard library.
if you do import random the code is:
def shuffle_deck(deck):
random.shuffle(deck)
I changed the name of the function to be consistent with the Style Guide for Python Code and added deck as a parameter.
|
How can i make python shuffleCards program output one of each card and not random amounts
|
Python newbie
How can i make the output be 52 cards but one of each and not randomly created cards. As of now output becomes for example 2 clover, 2 clover, 5 diamonds .. etc.
I know its an issue with the shuffeling i am doing but i am not allowed to use "random.shuffle"
import math
import random
def main():
createDeck()
shuffleDeck()
printDeck()
deck = ['A'] * 52
def createDeck():
suits = [" Heart", " Spades", " Clover", " Diamonds"]
cardsHeld = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
for i in range(len(deck)):
deck[i] = cardsHeld[int(i%13)] + suits[int(i/13)]
def shuffleDeck():
rand=0
num = 0
for i in range(len(deck)):
rand = random.random()
num = rand * 52
num = math.floor(num)
deck[i] = deck[num]
def printDeck():
for i in range(len(deck)):
print(deck[i])
main()
I changed
def shuffleDeck():
rand=0
num = 0
for i in range(len(deck)):
rand = random.random()
num = rand * 52
num = math.floor(num)
deck[i] = deck[num]
with
def shuffleDeck():
random.shuffle(deck)
That worked however i am not allowed to use "random.shuffle(deck)" So im not sure how i should be doing the shuffeling then.
|
[
"When you do deck[i] = deck[num] you overwrite the value at index i while keeping the same value at index num. You need to swap the values with deck[i], deck[num] = deck[num], deck[i]. But there's no need to write something like this yourself. Simply use one line of code with random.shuffle from Pythons standard library.\nif you do import random the code is:\ndef shuffle_deck(deck):\n random.shuffle(deck)\n\nI changed the name of the function to be consistent with the Style Guide for Python Code and added deck as a parameter.\n"
] |
[
0
] |
[] |
[] |
[
"math",
"python",
"random",
"shuffle"
] |
stackoverflow_0074512148_math_python_random_shuffle.txt
|
Q:
Standard deviation of binned values with `scipy.stats.binned_statistic`
When I bin my data accordingly to scipy.stats.binned_statistic (see here for example), how do I get the error (that is the standard deviation) on the average binned values?
For example, if I bin my data as following:
windspeed = 8 * np.random.rand(500)
boatspeed = .3 * windspeed**.5 + .2 * np.random.rand(500)
bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,
boatspeed, statistic='median', bins=[1,2,3,4,5,6,7])
plt.figure()
plt.plot(windspeed, boatspeed, 'b.', label='raw data')
plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,
label='binned statistic of data')
plt.legend()
how do I get the standard deviation on the bin_means?
A:
The way to go about this is to construct a probability density estimate from the histogram (this is just a question of normalizing the histogram appropriately), and then computing the standard deviation or any other statistic for the estimated density.
The appropriate normalization is whatever is needed to get the area under the histogram to be 1. As for computing statistics for the density estimate, work from the definition of the statistic as integral(p(x)*f(x), x, -infinity, +infinity), substituting the density estimate for p(x) and whatever is needed for f(x), e.g. x and x^2 to get the first and second moments, from which you calculate the variance and then the standard deviation.
I'll post some formulas tomorrow, or maybe someone else wants to give it a try in the meantime. You might be able to look up some formulas, but my advice is to always try to work out the answer before resorting to looking it up.
A:
Maybe I'm a bit late to answer, but I was wondering how to do the same thing and came across this question. I think calculating it with stats.binned_statistic_2d should be possible, but I haven't figured it out yet. For now I calculated it manually, like so (note than in my code I use a fixed number of equally spaced bins):
windspeed = 8 * numpy.random.rand(500)
boatspeed = .3 * windspeed**.5 + .2 * numpy.random.rand(500)
bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,
boatspeed, statistic='median', bins=10)
stds = []
# Match each value to the bin number it belongs to
pairs = zip(boatspeed, binnumber)
# Calculate stdev for all elements inside each bin
for n in list(set(binnumber)): # Iterate over each bin
in_bin = [x for x, nbin in pairs if nbin == n] # Get all elements inside bin n
stds.append(numpy.std(in_bin))
# Calculate the locations of the bins' centers, for plotting
bin_centers = []
for i in range(len(bin_edges) - 1):
center = bin_edges[i] + (float(bin_edges[i + 1]) - float(bin_edges[i]))/2.
bin_centers.append(center)
# Plot means
pyplot.figure()
pyplot.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,
label='binned statistic of data')
# Plot stdev as vertical lines, probably can also be done with errorbar
pyplot.vlines(bin_centers, bin_means - stds, bin_means + stds)
pyplot.legend()
pyplot.show()
Resulting plot (minus the data points):
You have to be careful with the bins. In the code I'm working on using this, one of the bins has no points and I have to adjust my calculations of the stdev accordingly.
A:
just change this line
bin_std, bin_edges, binnumber = stats.binned_statistic(windspeed,
boatspeed, statistic='std', bins=[1,2,3,4,5,6,7])
|
Standard deviation of binned values with `scipy.stats.binned_statistic`
|
When I bin my data accordingly to scipy.stats.binned_statistic (see here for example), how do I get the error (that is the standard deviation) on the average binned values?
For example, if I bin my data as following:
windspeed = 8 * np.random.rand(500)
boatspeed = .3 * windspeed**.5 + .2 * np.random.rand(500)
bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,
boatspeed, statistic='median', bins=[1,2,3,4,5,6,7])
plt.figure()
plt.plot(windspeed, boatspeed, 'b.', label='raw data')
plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,
label='binned statistic of data')
plt.legend()
how do I get the standard deviation on the bin_means?
|
[
"The way to go about this is to construct a probability density estimate from the histogram (this is just a question of normalizing the histogram appropriately), and then computing the standard deviation or any other statistic for the estimated density.\nThe appropriate normalization is whatever is needed to get the area under the histogram to be 1. As for computing statistics for the density estimate, work from the definition of the statistic as integral(p(x)*f(x), x, -infinity, +infinity), substituting the density estimate for p(x) and whatever is needed for f(x), e.g. x and x^2 to get the first and second moments, from which you calculate the variance and then the standard deviation.\nI'll post some formulas tomorrow, or maybe someone else wants to give it a try in the meantime. You might be able to look up some formulas, but my advice is to always try to work out the answer before resorting to looking it up.\n",
"Maybe I'm a bit late to answer, but I was wondering how to do the same thing and came across this question. I think calculating it with stats.binned_statistic_2d should be possible, but I haven't figured it out yet. For now I calculated it manually, like so (note than in my code I use a fixed number of equally spaced bins):\nwindspeed = 8 * numpy.random.rand(500)\nboatspeed = .3 * windspeed**.5 + .2 * numpy.random.rand(500)\nbin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,\n boatspeed, statistic='median', bins=10)\n\nstds = []\n\n# Match each value to the bin number it belongs to\npairs = zip(boatspeed, binnumber)\n\n# Calculate stdev for all elements inside each bin\nfor n in list(set(binnumber)): # Iterate over each bin\n in_bin = [x for x, nbin in pairs if nbin == n] # Get all elements inside bin n\n stds.append(numpy.std(in_bin))\n\n# Calculate the locations of the bins' centers, for plotting\nbin_centers = []\n\nfor i in range(len(bin_edges) - 1):\n center = bin_edges[i] + (float(bin_edges[i + 1]) - float(bin_edges[i]))/2.\n bin_centers.append(center)\n\n# Plot means\npyplot.figure()\npyplot.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,\n label='binned statistic of data')\n\n# Plot stdev as vertical lines, probably can also be done with errorbar\npyplot.vlines(bin_centers, bin_means - stds, bin_means + stds)\n\npyplot.legend()\npyplot.show()\n\nResulting plot (minus the data points):\n\nYou have to be careful with the bins. In the code I'm working on using this, one of the bins has no points and I have to adjust my calculations of the stdev accordingly. \n",
"just change this line\nbin_std, bin_edges, binnumber = stats.binned_statistic(windspeed,\n boatspeed, statistic='std', bins=[1,2,3,4,5,6,7])\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"binning",
"python",
"statistics"
] |
stackoverflow_0048997277_binning_python_statistics.txt
|
Q:
Is there a faster method for multiplying very large integers or storing them in many caches/variables instead of one to improve performance?
def exponentiation(base,n):
if n == 0:
return 1
if n % 2 == 0:
return exponentiation(base*base, n/2)
else:
return base * exponentiation(base * base, (n-1)/2)
if __name__ == '__main__':
print(len(str(exponentiation(2, 66666666))))
For very large integers, the computer becomes quite sluggish at finding the product of numbers; And I know that 1 Gigabyte of RAM can store atleast 2^8000000000 digits, but this program slows down far before this limit is reached.
I wished to use Exponentiation by squaring in order to improve the rate at which the program did the multiplications, but yet it seems as though there is a problem with the program storing such large integers.
A:
Just use the built-in ** operator for this. It works significantly faster.
big_number_a = 2 ** 66666666
big_number_b = exponentiation(2, 66666666)
big_number_a == big_number_b # True
Also, don't try converting such a huge number to a decimal string with str unless you really have to. That part is super slow.
A:
Yes, there is a faster way:
exponentiation = pow
This is about twice as fast as your method, and it works for non-integers as well.
The exponentiation time in your code is negligible, though. Most of its time is spent converting the integers to strings. If you want the number of digits an integer has, use int(math.log10(n)) + 1 instead.
|
Is there a faster method for multiplying very large integers or storing them in many caches/variables instead of one to improve performance?
|
def exponentiation(base,n):
if n == 0:
return 1
if n % 2 == 0:
return exponentiation(base*base, n/2)
else:
return base * exponentiation(base * base, (n-1)/2)
if __name__ == '__main__':
print(len(str(exponentiation(2, 66666666))))
For very large integers, the computer becomes quite sluggish at finding the product of numbers; And I know that 1 Gigabyte of RAM can store atleast 2^8000000000 digits, but this program slows down far before this limit is reached.
I wished to use Exponentiation by squaring in order to improve the rate at which the program did the multiplications, but yet it seems as though there is a problem with the program storing such large integers.
|
[
"Just use the built-in ** operator for this. It works significantly faster.\nbig_number_a = 2 ** 66666666\nbig_number_b = exponentiation(2, 66666666)\nbig_number_a == big_number_b # True\n\nAlso, don't try converting such a huge number to a decimal string with str unless you really have to. That part is super slow.\n",
"Yes, there is a faster way:\nexponentiation = pow\n\nThis is about twice as fast as your method, and it works for non-integers as well.\nThe exponentiation time in your code is negligible, though. Most of its time is spent converting the integers to strings. If you want the number of digits an integer has, use int(math.log10(n)) + 1 instead.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074512116_python.txt
|
Q:
First Time Importing CSV into Python
I am an R user and have recently been learning how to use Python!
In R, I normally import CSV files like this:
> getwd()
[1] "C:/Users/me/OneDrive/Documents"
my_file = read.csv("my_file.csv")
Now, I am trying to learn how to do this in Python.
I first tried this code and got the following error:
import pandas as pd
df = pandas.read_csv('C:\Users\me\OneDrive\Documents\my_file.csv')
File "<ipython-input-17-45a11fa3e8b1>", line 1
df = pandas.read_csv('C:\Users\me\OneDrive\Documents\my_file.csv')
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
I then tried this alternate method, but still got an error:
df = pandas.read_csv(r"C:\Users\me\OneDrive\Documents\my_file.csv")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-20-c0ac0d536b37> in <module>
----> 1 df = pandas.read_csv(r"C:\Users\me\OneDrive\Documents\my_file.csv")
NameError: name 'pandas' is not defined
Can someone please show me what I am doing wrong and how to fix this?
Thank you!
Note: I am using Jupyter Notebooks within Anaconda
A:
Regarding the second error, make sure pandas module is installed in your system. You can run this code snippet in the terminal to install the module.
pip install pandas -U
In python \somealphabet is represented as a Unicode character. What you can do is, you can either use \\somealphabet or replace \ with /
df = pd.read_csv('C:\\Users\\me\\OneDrive\\Documents\\my_file.csv')
df = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')
A:
df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')
I fixed my own problem!
|
First Time Importing CSV into Python
|
I am an R user and have recently been learning how to use Python!
In R, I normally import CSV files like this:
> getwd()
[1] "C:/Users/me/OneDrive/Documents"
my_file = read.csv("my_file.csv")
Now, I am trying to learn how to do this in Python.
I first tried this code and got the following error:
import pandas as pd
df = pandas.read_csv('C:\Users\me\OneDrive\Documents\my_file.csv')
File "<ipython-input-17-45a11fa3e8b1>", line 1
df = pandas.read_csv('C:\Users\me\OneDrive\Documents\my_file.csv')
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
I then tried this alternate method, but still got an error:
df = pandas.read_csv(r"C:\Users\me\OneDrive\Documents\my_file.csv")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-20-c0ac0d536b37> in <module>
----> 1 df = pandas.read_csv(r"C:\Users\me\OneDrive\Documents\my_file.csv")
NameError: name 'pandas' is not defined
Can someone please show me what I am doing wrong and how to fix this?
Thank you!
Note: I am using Jupyter Notebooks within Anaconda
|
[
"Regarding the second error, make sure pandas module is installed in your system. You can run this code snippet in the terminal to install the module.\npip install pandas -U\n\nIn python \\somealphabet is represented as a Unicode character. What you can do is, you can either use \\\\somealphabet or replace \\ with /\ndf = pd.read_csv('C:\\\\Users\\\\me\\\\OneDrive\\\\Documents\\\\my_file.csv')\n\ndf = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')\n\n",
"df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')\n\nI fixed my own problem!\n"
] |
[
1,
0
] |
[] |
[] |
[
"csv",
"python",
"r"
] |
stackoverflow_0074505645_csv_python_r.txt
|
Q:
Jax - vmap over batch of dataclasses
In JAX, I am looking to vmap a function over a fixed length list of dataclasses, for example:
import jax, chex
from flax import struct
@struct.dataclass
class EnvParams:
max_steps: int = 500
random_respawn: bool = False
def foo(params: EnvParams):
...
param_list = jnp.Array([EnvParams(max_steps=500), EnvParams(max_steps=600)])
jax.vmap(foo)(param_list)
The example above fails since is not possible to create a jnp.Array of custom objects, and JAX doesn't allow vmapping over Python Lists. The only remaining option I see is to transform the dataclass to represent a batch of parameters, as so:
@struct.dataclass
class EnvParamBatch:
max_steps: jnp.Array = jnp.array([500, 600])
random_respawn: jnp.Array = jnp.array([False, True])
def bar(params):
...
jax.vmap(bar)(EnvParamBatch())
It would be preferable to use a container of structs (with each representing a single parameter set), so I'm wondering if there are any alternative approaches to this?
N.B. I am aware of this answer, however it's not precisely the same question and there may now be better solutions.
A:
vmap cannot process lists of objects, only a single object containing arrays. Here is an example:
import typing
import jax
import jax.numpy as jnp
class EnvParams(typing.NamedTuple):
max_steps: int = 500
random_respawn: bool = False
param_array = EnvParams(
max_steps=jnp.array([500, 600]),
random_respawn=jnp.array([False, False]))
vmap_param_array = jax.vmap(lambda x: x)(param_array)
It's best to use the above approach most of the time so objects can be stored in GPU / TPU memory instead of CPU... but if you really must convert between lists / arrays on a CPU here is an example:
def list_to_array(list):
cls = type(list[0])
return cls(**{k: jnp.array([getattr(v, k) for v in list]) for k in cls._fields})
def array_to_list(array):
cls = type(array)
size = len(getattr(array, cls._fields[0]))
return [cls(**{k: v(getattr(array, k)[i]) for k, v in cls._field_types.items()}) for i in range(size)]
param_list = [EnvParams(max_steps=500), EnvParams(max_steps=600)]
param_array = list_to_array(param_list)
vmap_param_array = jax.vmap(lambda x: x)(param_array)
vmap_param_list = array_to_list(vmap_param_array)
|
Jax - vmap over batch of dataclasses
|
In JAX, I am looking to vmap a function over a fixed length list of dataclasses, for example:
import jax, chex
from flax import struct
@struct.dataclass
class EnvParams:
max_steps: int = 500
random_respawn: bool = False
def foo(params: EnvParams):
...
param_list = jnp.Array([EnvParams(max_steps=500), EnvParams(max_steps=600)])
jax.vmap(foo)(param_list)
The example above fails since is not possible to create a jnp.Array of custom objects, and JAX doesn't allow vmapping over Python Lists. The only remaining option I see is to transform the dataclass to represent a batch of parameters, as so:
@struct.dataclass
class EnvParamBatch:
max_steps: jnp.Array = jnp.array([500, 600])
random_respawn: jnp.Array = jnp.array([False, True])
def bar(params):
...
jax.vmap(bar)(EnvParamBatch())
It would be preferable to use a container of structs (with each representing a single parameter set), so I'm wondering if there are any alternative approaches to this?
N.B. I am aware of this answer, however it's not precisely the same question and there may now be better solutions.
|
[
"vmap cannot process lists of objects, only a single object containing arrays. Here is an example:\nimport typing\nimport jax\nimport jax.numpy as jnp\n\nclass EnvParams(typing.NamedTuple):\n max_steps: int = 500\n random_respawn: bool = False\n\nparam_array = EnvParams(\n max_steps=jnp.array([500, 600]),\n random_respawn=jnp.array([False, False]))\nvmap_param_array = jax.vmap(lambda x: x)(param_array)\n\nIt's best to use the above approach most of the time so objects can be stored in GPU / TPU memory instead of CPU... but if you really must convert between lists / arrays on a CPU here is an example:\ndef list_to_array(list):\n cls = type(list[0])\n return cls(**{k: jnp.array([getattr(v, k) for v in list]) for k in cls._fields})\n\ndef array_to_list(array):\n cls = type(array)\n size = len(getattr(array, cls._fields[0]))\n return [cls(**{k: v(getattr(array, k)[i]) for k, v in cls._field_types.items()}) for i in range(size)]\n\nparam_list = [EnvParams(max_steps=500), EnvParams(max_steps=600)]\nparam_array = list_to_array(param_list)\nvmap_param_array = jax.vmap(lambda x: x)(param_array)\nvmap_param_list = array_to_list(vmap_param_array)\n\n"
] |
[
0
] |
[] |
[] |
[
"flax",
"jax",
"python"
] |
stackoverflow_0073765064_flax_jax_python.txt
|
Q:
how to remove multiple headers
I have a spreadsheet that is in a pdf where I extract these values and transform them into .csv with textract from aws using Python.
However, when I extract the values, there are several headers and I would like to keep only the first header.
account ;description ;old balance ;debit ;credit ;mov. ;balance ; **# --> first header**
1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;
1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;
account ;description ;old balance ;debit ;credit ;mov. ;balance ; **# --> second header**
2.00 ;: investments ;120.0400.0 ;20.000.000.0 ;82.840.400.0 ;-100.2 ;314.262.0 ;
;;;;debit ;credit ;mov. ;balance ; **# --> third header**
3.00 ;real state ;1.000.200.4 ;4.000.031.47 ;2.273.121,44 ;-144.089.77 ;254.844.390,75 ;
Note that in the same .csv file I have 3 headers and one of them only has a few values, but as I want to remove it, I believe it doesn't matter so much.
So how to remove the other headers? using python.
Each pdf has a different header, so I believe I can use the same solution in the others
OBS: this is the way I transform the string into csv
# replace content
with open("file_name.csv", "at") as fout:
fout.write(table_csv)
I haven't tried any solutions as I can't think of anything useful
A:
You can use re module to remove the duplicate headers. For example:
text = """\
account ;description ;old balance ;debit ;credit ;mov. ;balance ;
1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;
1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;
account ;description ;old balance ;debit ;credit ;mov. ;balance ;
2.00 ;: investments ;120.0400.0 ;20.000.000.0 ;82.840.400.0 ;-100.2 ;314.262.0 ;
;;;;debit ;credit ;mov. ;balance ;
3.00 ;real state ;1.000.200.4 ;4.000.031.47 ;2.273.121,44 ;-144.089.77 ;254.844.390,75 ;"""
import re
import pandas as pd
from io import StringIO
# remove the headers
text = re.sub(r"(?m)\n\n^.*$", "", text.strip())
# remove ; at end of lines
text = re.sub(r"(?m);\s*$", "", text.strip())
print(text)
Prints:
account ;description ;old balance ;debit ;credit ;mov. ;balance
1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01
1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01
2.00 ;: investments ;120.0400.0 ;20.000.000.0 ;82.840.400.0 ;-100.2 ;314.262.0
3.00 ;real state ;1.000.200.4 ;4.000.031.47 ;2.273.121,44 ;-144.089.77 ;254.844.390,75
Then you can load the text to a DataFrame:
df = pd.read_csv(StringIO(text), delimiter=";")
print(df)
Prints:
account description old balance debit credit mov. balance
0 1.0 : investments 212.844.26 63.856.811,44 63.857.250.69 -439.25 212.405.01
1 1.0 : investments 212.844.26 63.856.811,44 63.857.250.69 -439.25 212.405.01
2 2.0 : investments 120.0400.0 20.000.000.0 82.840.400.0 -100.2 314.262.0
3 3.0 real state 1.000.200.4 4.000.031.47 2.273.121,44 -144.089.77 254.844.390,75
To save to CSV:
df.to_csv('file_name.csv', index=False)
|
how to remove multiple headers
|
I have a spreadsheet that is in a pdf where I extract these values and transform them into .csv with textract from aws using Python.
However, when I extract the values, there are several headers and I would like to keep only the first header.
account ;description ;old balance ;debit ;credit ;mov. ;balance ; **# --> first header**
1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;
1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;
account ;description ;old balance ;debit ;credit ;mov. ;balance ; **# --> second header**
2.00 ;: investments ;120.0400.0 ;20.000.000.0 ;82.840.400.0 ;-100.2 ;314.262.0 ;
;;;;debit ;credit ;mov. ;balance ; **# --> third header**
3.00 ;real state ;1.000.200.4 ;4.000.031.47 ;2.273.121,44 ;-144.089.77 ;254.844.390,75 ;
Note that in the same .csv file I have 3 headers and one of them only has a few values, but as I want to remove it, I believe it doesn't matter so much.
So how to remove the other headers? using python.
Each pdf has a different header, so I believe I can use the same solution in the others
OBS: this is the way I transform the string into csv
# replace content
with open("file_name.csv", "at") as fout:
fout.write(table_csv)
I haven't tried any solutions as I can't think of anything useful
|
[
"You can use re module to remove the duplicate headers. For example:\ntext = \"\"\"\\\naccount ;description ;old balance ;debit ;credit ;mov. ;balance ;\n1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;\n1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 ;\n\naccount ;description ;old balance ;debit ;credit ;mov. ;balance ;\n2.00 ;: investments ;120.0400.0 ;20.000.000.0 ;82.840.400.0 ;-100.2 ;314.262.0 ;\n\n;;;;debit ;credit ;mov. ;balance ;\n3.00 ;real state ;1.000.200.4 ;4.000.031.47 ;2.273.121,44 ;-144.089.77 ;254.844.390,75 ;\"\"\"\n\nimport re\nimport pandas as pd\nfrom io import StringIO\n\n# remove the headers\ntext = re.sub(r\"(?m)\\n\\n^.*$\", \"\", text.strip())\n\n# remove ; at end of lines\ntext = re.sub(r\"(?m);\\s*$\", \"\", text.strip())\n\nprint(text)\n\nPrints:\naccount ;description ;old balance ;debit ;credit ;mov. ;balance \n1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 \n1.00 ;: investments ;212.844.26 ;63.856.811,44 ;63.857.250.69 ;-439.25 ;212.405.01 \n2.00 ;: investments ;120.0400.0 ;20.000.000.0 ;82.840.400.0 ;-100.2 ;314.262.0 \n3.00 ;real state ;1.000.200.4 ;4.000.031.47 ;2.273.121,44 ;-144.089.77 ;254.844.390,75 \n\n\nThen you can load the text to a DataFrame:\ndf = pd.read_csv(StringIO(text), delimiter=\";\")\nprint(df)\n\nPrints:\n account description old balance debit credit mov. balance \n0 1.0 : investments 212.844.26 63.856.811,44 63.857.250.69 -439.25 212.405.01 \n1 1.0 : investments 212.844.26 63.856.811,44 63.857.250.69 -439.25 212.405.01 \n2 2.0 : investments 120.0400.0 20.000.000.0 82.840.400.0 -100.2 314.262.0 \n3 3.0 real state 1.000.200.4 4.000.031.47 2.273.121,44 -144.089.77 254.844.390,75 \n\n\nTo save to CSV:\ndf.to_csv('file_name.csv', index=False)\n\n"
] |
[
3
] |
[] |
[] |
[
"amazon_textract",
"csv",
"python"
] |
stackoverflow_0074511931_amazon_textract_csv_python.txt
|
Q:
Run aws cli from EC2 python script with variables
I need to run AWS CLI Polly service from AWS EC2 using python, with additional variables. The problem is with the including variable in the cmd string
import subprocess
row1 = 'My husband and I have done around 100 rooms and came to Barcelona as it has a reputation for top class rooms. We did Bajo Zero based on a recommendation from an escape room enthusiast in the UK and werent disappointed. It was a very well made immersive room with some clever puzzles. We chose hard mode and it was quite challenging as a pair but we did make it out in time. ,Escapem Elements Aire Escape Room'
cmd = 'aws polly synthesize-speech --output-format mp3 --engine neural --voice-id Kevin --text' +row1+ 'speech1.mp3'
subprocess.call(cmd, shell=True)
This script command is executed from withing EC2 NOT local
A:
Rather than calling the aws program from Python, you can use the boto3 library to directly call AWS. In fact, the AWS CLI is written in Python and uses this library too!
You can then use boto3 to call Polly.
For example:
import boto3
client = boto3.client('polly')
response = client.synthesize_speech(
Engine='neural',
LanguageCode='en-US',
OutputFormat='mp3',
Text='My husband and I have done around 100 rooms',
VoiceId='Kevin'
)
|
Run aws cli from EC2 python script with variables
|
I need to run AWS CLI Polly service from AWS EC2 using python, with additional variables. The problem is with the including variable in the cmd string
import subprocess
row1 = 'My husband and I have done around 100 rooms and came to Barcelona as it has a reputation for top class rooms. We did Bajo Zero based on a recommendation from an escape room enthusiast in the UK and werent disappointed. It was a very well made immersive room with some clever puzzles. We chose hard mode and it was quite challenging as a pair but we did make it out in time. ,Escapem Elements Aire Escape Room'
cmd = 'aws polly synthesize-speech --output-format mp3 --engine neural --voice-id Kevin --text' +row1+ 'speech1.mp3'
subprocess.call(cmd, shell=True)
This script command is executed from withing EC2 NOT local
|
[
"Rather than calling the aws program from Python, you can use the boto3 library to directly call AWS. In fact, the AWS CLI is written in Python and uses this library too!\nYou can then use boto3 to call Polly.\nFor example:\nimport boto3\n\nclient = boto3.client('polly')\n\nresponse = client.synthesize_speech(\n Engine='neural',\n LanguageCode='en-US',\n OutputFormat='mp3',\n Text='My husband and I have done around 100 rooms',\n VoiceId='Kevin'\n)\n\n"
] |
[
1
] |
[] |
[] |
[
"amazon_web_services",
"aws_cli",
"python"
] |
stackoverflow_0074507794_amazon_web_services_aws_cli_python.txt
|
Q:
How to "spread" a numpy array (opposite of slice with step size)?
Is there a way to spread the values of a numpy array? Like an opposite to slicing with a step size > 1:
>>> a = np.array([[1, 0, 2], [0, 0, 0], [3, 0, 4]])
>>> a
array([[1, 0, 2],
[0, 0, 0],
[3, 0, 4]])
>>> b = a[::2, ::2]
>>> b
array([[1, 2],
[3, 4]])
In this example, is there an elegant way to get a from b?
A:
You can create a zeros array with correct shape first and then assign with step size:
import numpy as np
b = np.array([[1, 2], [3, 4]])
a = np.zeros((b.shape[0] * 2 - 1, b.shape[1] * 2 - 1), dtype='int')
a[::2, ::2] = b
a
# array([[1, 0, 2],
# [0, 0, 0],
# [3, 0, 4]])
|
How to "spread" a numpy array (opposite of slice with step size)?
|
Is there a way to spread the values of a numpy array? Like an opposite to slicing with a step size > 1:
>>> a = np.array([[1, 0, 2], [0, 0, 0], [3, 0, 4]])
>>> a
array([[1, 0, 2],
[0, 0, 0],
[3, 0, 4]])
>>> b = a[::2, ::2]
>>> b
array([[1, 2],
[3, 4]])
In this example, is there an elegant way to get a from b?
|
[
"You can create a zeros array with correct shape first and then assign with step size:\nimport numpy as np\nb = np.array([[1, 2], [3, 4]])\na = np.zeros((b.shape[0] * 2 - 1, b.shape[1] * 2 - 1), dtype='int')\na[::2, ::2] = b\na\n# array([[1, 0, 2],\n# [0, 0, 0],\n# [3, 0, 4]])\n\n"
] |
[
1
] |
[] |
[] |
[
"numpy",
"numpy_ndarray",
"numpy_slicing",
"python"
] |
stackoverflow_0074512250_numpy_numpy_ndarray_numpy_slicing_python.txt
|
Q:
Depending on the content's name, converting a text file into a list of dictionaries or a list
I have a question, I'm not sure where to begin. I have a text file with all the contents of recipes and other things. I wonder if there's a straightforward way to replace the text file and make it into the example of the function that I've pasted at the bottom. If not, does that imply that in order to turn some texts into lists and dictionaries by iterating through each line and splitting at certain places?
Text file:
name:Chocolate Chip Cookies
categories:dessert;cookie;chocolate
ingredient:2¼ cups all-purpose flour
ingredient:1 teaspoon baking soda
ingredient:1 teaspoon salts
ingredient:½ cup (1 stick) butter, softened
ingredient:¾ cup granulated sugar
ingredient:¾ cup packed brown sugar
ingredient:1 teaspoon vanilla extract
ingredient:2 large eggs
ingredient:2 cups (12-ounce package) Semi-Sweet Chocolate Chips
step:Preheat oven to 375°F
step:Combine flour, baking soda, and salt in a small bowl.
step:Beat butter, sugar, brown sugar, and vanilla extract in a large bowl until creamy.
step:Add eggs, beating well after each addition.
step:Gradually beat the flour mixture into the wet mixture.
step:Stir in morsels.
step:Drop rounded tablespoons of dough onto ungreased baking sheets.
step:Bake for 9 to 11 minutes or until golden brown.
step:Cool on baking sheets for 2 minutes.
step:Move to wire racks to cool completely.
name:Sugar Cookies
categories:dessert;cookie;kid's favorites
ingredient:2¾ cups all-purpose flour
ingredient:1 teaspoon baking soda
ingredient:½ teaspoon baking powder
ingredient:1 cup butter, softened
ingredient:1½ cups white sugar
ingredient:1 egg
ingredient:1 teaspoon vanilla extract
step:Preheat oven to 375°F
step:In a small bowl, stir together flour, baking soda, and baking powder. Set aside.
step:In a large bowl, mix together butter and sugar until smooth. Beat in egg and vanilla.
step:Blend the wet and dry ingredients.
step:Place teaspoon-size balls of dough onto an ungreased cookie sheet.
step:Bake 8 to 10 minutes in the preheated oven, or until golden.
step:Let stand on cookie sheet two minutes before removing to cool on wire racks.
def load_data():
return [
{
'name': 'Chocolate Chip Cookies',
'categories': ['dessert', 'cookie', 'chocolate'],
'ingredients': ['2¼ cups all-purpose flour',
'1 teaspoon baking soda',
'1 teaspoon salts',
'½ cup (1 stick) butter, softened',
'¾ cup granulated sugar',
'¾ cup packed brown sugar',
'1 teaspoon vanilla extract',
'2 large eggs',
'2 cups (12-ounce package) Semi-Sweet Chocolate Chips'],
'steps': ['Preheat oven to 375°F',
'Combine flour, baking soda, and salt in a small bowl.',
'Beat butter, sugar, brown sugar, and vanilla extract in a large bowl until creamy.',
'Add eggs, beating well after each addition.',
'Gradually beat the flour mixture into the wet mixture.',
'Stir in morsels.',
'Drop rounded tablespoons of dough onto ungreased baking sheets.',
'Bake for 9 to 11 minutes or until golden brown.',
'Cool on baking sheets for 2 minutes.',
'Move to wire racks to cool completely.']
},
{
'name': 'Sugar Cookies',
'categories': ['dessert', 'cookie'],
'ingredients': ['2¾ cups all-purpose flour',
'1 teaspoon baking soda',
'½ teaspoon baking powder',
'1 cup butter, softened',
'1½ cups white sugar',
'1 egg',
'1 teaspoon vanilla extract'],
'steps': ['Preheat oven to 375°F',
'In a small bowl, stir together flour, baking soda, and baking powder. Set aside.',
'In a large bowl, mix together butter and sugar until smooth. Beat in egg and vanilla.',
'Blend the wet and dry ingredients.',
'Place teaspoon-size balls of dough onto an ungreased cookie sheet.',
'Bake 8 to 10 minutes in the preheated oven, or until golden.',
'Let stand on cookie sheet two minutes before removing to cool on wire racks.']
}
]
A:
To make a list of dictionaries from the text you can do (text variable contains string from your question):
out, current = [], None
for line in text.splitlines():
if line.startswith("name:"):
if current:
out.append(current)
current = {"name": line.split(":", maxsplit=1)[1]}
elif ":" in line:
k, v = line.split(":", maxsplit=1)
if k == "categories":
v = v.split(";")
current.setdefault(k, []).extend(v)
else:
current.setdefault(k, []).append(v)
if current:
out.append(current)
print(out)
Prints:
[
{
"name": "Chocolate Chip Cookies",
"categories": ["dessert", "cookie", "chocolate"],
"ingredient": [
"2¼ cups all-purpose flour",
"1 teaspoon baking soda",
"1 teaspoon salts",
"½ cup (1 stick) butter, softened",
"¾ cup granulated sugar",
"¾ cup packed brown sugar",
"1 teaspoon vanilla extract",
"2 large eggs",
"2 cups (12-ounce package) Semi-Sweet Chocolate Chips",
],
"step": [
"Preheat oven to 375°F",
"Combine flour, baking soda, and salt in a small bowl.",
"Beat butter, sugar, brown sugar, and vanilla extract in a large bowl until creamy.",
"Add eggs, beating well after each addition.",
"Gradually beat the flour mixture into the wet mixture.",
"Stir in morsels.",
"Drop rounded tablespoons of dough onto ungreased baking sheets.",
"Bake for 9 to 11 minutes or until golden brown.",
"Cool on baking sheets for 2 minutes.",
"Move to wire racks to cool completely.",
],
},
{
"name": "Sugar Cookies",
"categories": ["dessert", "cookie", "kid's favorites"],
"ingredient": [
"2¾ cups all-purpose flour",
"1 teaspoon baking soda",
"½ teaspoon baking powder",
"1 cup butter, softened",
"1½ cups white sugar",
"1 egg",
"1 teaspoon vanilla extract ",
],
"step": [
"Preheat oven to 375°F",
"In a small bowl, stir together flour, baking soda, and baking powder. Set aside.",
"In a large bowl, mix together butter and sugar until smooth. Beat in egg and vanilla.",
"Blend the wet and dry ingredients.",
"Place teaspoon-size balls of dough onto an ungreased cookie sheet.",
"Bake 8 to 10 minutes in the preheated oven, or until golden.",
"Let stand on cookie sheet two minutes before removing to cool on wire racks.",
],
},
]
|
Depending on the content's name, converting a text file into a list of dictionaries or a list
|
I have a question, I'm not sure where to begin. I have a text file with all the contents of recipes and other things. I wonder if there's a straightforward way to replace the text file and make it into the example of the function that I've pasted at the bottom. If not, does that imply that in order to turn some texts into lists and dictionaries by iterating through each line and splitting at certain places?
Text file:
name:Chocolate Chip Cookies
categories:dessert;cookie;chocolate
ingredient:2¼ cups all-purpose flour
ingredient:1 teaspoon baking soda
ingredient:1 teaspoon salts
ingredient:½ cup (1 stick) butter, softened
ingredient:¾ cup granulated sugar
ingredient:¾ cup packed brown sugar
ingredient:1 teaspoon vanilla extract
ingredient:2 large eggs
ingredient:2 cups (12-ounce package) Semi-Sweet Chocolate Chips
step:Preheat oven to 375°F
step:Combine flour, baking soda, and salt in a small bowl.
step:Beat butter, sugar, brown sugar, and vanilla extract in a large bowl until creamy.
step:Add eggs, beating well after each addition.
step:Gradually beat the flour mixture into the wet mixture.
step:Stir in morsels.
step:Drop rounded tablespoons of dough onto ungreased baking sheets.
step:Bake for 9 to 11 minutes or until golden brown.
step:Cool on baking sheets for 2 minutes.
step:Move to wire racks to cool completely.
name:Sugar Cookies
categories:dessert;cookie;kid's favorites
ingredient:2¾ cups all-purpose flour
ingredient:1 teaspoon baking soda
ingredient:½ teaspoon baking powder
ingredient:1 cup butter, softened
ingredient:1½ cups white sugar
ingredient:1 egg
ingredient:1 teaspoon vanilla extract
step:Preheat oven to 375°F
step:In a small bowl, stir together flour, baking soda, and baking powder. Set aside.
step:In a large bowl, mix together butter and sugar until smooth. Beat in egg and vanilla.
step:Blend the wet and dry ingredients.
step:Place teaspoon-size balls of dough onto an ungreased cookie sheet.
step:Bake 8 to 10 minutes in the preheated oven, or until golden.
step:Let stand on cookie sheet two minutes before removing to cool on wire racks.
def load_data():
return [
{
'name': 'Chocolate Chip Cookies',
'categories': ['dessert', 'cookie', 'chocolate'],
'ingredients': ['2¼ cups all-purpose flour',
'1 teaspoon baking soda',
'1 teaspoon salts',
'½ cup (1 stick) butter, softened',
'¾ cup granulated sugar',
'¾ cup packed brown sugar',
'1 teaspoon vanilla extract',
'2 large eggs',
'2 cups (12-ounce package) Semi-Sweet Chocolate Chips'],
'steps': ['Preheat oven to 375°F',
'Combine flour, baking soda, and salt in a small bowl.',
'Beat butter, sugar, brown sugar, and vanilla extract in a large bowl until creamy.',
'Add eggs, beating well after each addition.',
'Gradually beat the flour mixture into the wet mixture.',
'Stir in morsels.',
'Drop rounded tablespoons of dough onto ungreased baking sheets.',
'Bake for 9 to 11 minutes or until golden brown.',
'Cool on baking sheets for 2 minutes.',
'Move to wire racks to cool completely.']
},
{
'name': 'Sugar Cookies',
'categories': ['dessert', 'cookie'],
'ingredients': ['2¾ cups all-purpose flour',
'1 teaspoon baking soda',
'½ teaspoon baking powder',
'1 cup butter, softened',
'1½ cups white sugar',
'1 egg',
'1 teaspoon vanilla extract'],
'steps': ['Preheat oven to 375°F',
'In a small bowl, stir together flour, baking soda, and baking powder. Set aside.',
'In a large bowl, mix together butter and sugar until smooth. Beat in egg and vanilla.',
'Blend the wet and dry ingredients.',
'Place teaspoon-size balls of dough onto an ungreased cookie sheet.',
'Bake 8 to 10 minutes in the preheated oven, or until golden.',
'Let stand on cookie sheet two minutes before removing to cool on wire racks.']
}
]
|
[
"To make a list of dictionaries from the text you can do (text variable contains string from your question):\nout, current = [], None\nfor line in text.splitlines():\n if line.startswith(\"name:\"):\n if current:\n out.append(current)\n current = {\"name\": line.split(\":\", maxsplit=1)[1]}\n elif \":\" in line:\n k, v = line.split(\":\", maxsplit=1)\n if k == \"categories\":\n v = v.split(\";\")\n current.setdefault(k, []).extend(v)\n else:\n current.setdefault(k, []).append(v)\n\nif current:\n out.append(current)\n\nprint(out)\n\nPrints:\n[\n {\n \"name\": \"Chocolate Chip Cookies\",\n \"categories\": [\"dessert\", \"cookie\", \"chocolate\"],\n \"ingredient\": [\n \"2¼ cups all-purpose flour\",\n \"1 teaspoon baking soda\",\n \"1 teaspoon salts\",\n \"½ cup (1 stick) butter, softened\",\n \"¾ cup granulated sugar\",\n \"¾ cup packed brown sugar\",\n \"1 teaspoon vanilla extract\",\n \"2 large eggs\",\n \"2 cups (12-ounce package) Semi-Sweet Chocolate Chips\",\n ],\n \"step\": [\n \"Preheat oven to 375°F\",\n \"Combine flour, baking soda, and salt in a small bowl.\",\n \"Beat butter, sugar, brown sugar, and vanilla extract in a large bowl until creamy.\",\n \"Add eggs, beating well after each addition.\",\n \"Gradually beat the flour mixture into the wet mixture.\",\n \"Stir in morsels.\",\n \"Drop rounded tablespoons of dough onto ungreased baking sheets.\",\n \"Bake for 9 to 11 minutes or until golden brown.\",\n \"Cool on baking sheets for 2 minutes.\",\n \"Move to wire racks to cool completely.\",\n ],\n },\n {\n \"name\": \"Sugar Cookies\",\n \"categories\": [\"dessert\", \"cookie\", \"kid's favorites\"],\n \"ingredient\": [\n \"2¾ cups all-purpose flour\",\n \"1 teaspoon baking soda\",\n \"½ teaspoon baking powder\",\n \"1 cup butter, softened\",\n \"1½ cups white sugar\",\n \"1 egg\",\n \"1 teaspoon vanilla extract \",\n ],\n \"step\": [\n \"Preheat oven to 375°F\",\n \"In a small bowl, stir together flour, baking soda, and baking powder. Set aside.\",\n \"In a large bowl, mix together butter and sugar until smooth. Beat in egg and vanilla.\",\n \"Blend the wet and dry ingredients.\",\n \"Place teaspoon-size balls of dough onto an ungreased cookie sheet.\",\n \"Bake 8 to 10 minutes in the preheated oven, or until golden.\",\n \"Let stand on cookie sheet two minutes before removing to cool on wire racks.\",\n ],\n },\n]\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"replace",
"text"
] |
stackoverflow_0074512203_python_replace_text.txt
|
Q:
Is there a python implementation to .net automapper?
Automapper is a object-object mapper where we can use to project domain model to view model in asp.net mvc.
http://automapper.codeplex.com/
Is there equivalent implementation in Python for use in Django(Template)/Pylons ?
Or is there necessity for this in Python world?
A:
Yes, There is.
ObjectMapper is a class for automatic object mapping. It helps you to create objects between project layers (data layer, service layer, view) in a simple, transparent way.
https://pypi.python.org/pypi/object-mapper
A:
This generally isn't necessary in Python. We have some pretty complex domain models and we're able to use them in our views easily, without noticing any performance issues, and we serve millions of page views a month.
Also remember that "view" in Django == "controller" in MVC, and "template" in Django is "view" in MVC. Hence MTV rather than MVC. Something that tripped me up initially :-)
If there's some specific issue you're running into, post that as a question too ...
A:
Here is a nice Python automapper that is possible to extend for any framework models:
https://pypi.org/project/py-automapper/
A:
I ended up rolling my own basic version of automapper modelled on the .net version.
from typing import Protocol, TypeVar, Callable
from dataclasses import is_dataclass, fields
from dataclasses import MISSING
S = TypeVar("S")
T = TypeVar("T")
class IProfile(Protocol):
mappings: dict[tuple[type[S], type[T]], dict[str, Callable[[S], object]]]
def create_map(self,
source_type: type[S],
target_type: type[T],
**mappings: Callable[[S], object]) -> None:
...
class IMapper(Protocol):
def map(self, data: object, data_type: type[T]) -> T:
...
class Profile:
mappings: dict[tuple[type[S], type[T]], dict[str, Callable[[S], object]]]
def __init__(self) -> None:
self.mappings = {}
def create_map(self,
source_type: type[S],
target_type: type[T],
**mappings: Callable[[S], object]) -> None:
self.mappings[(source_type, target_type)] = dict(mappings)
class Mapper:
_mappings: dict[tuple[type[S], type[T]], dict[str, Callable[[S], object]]]
def __init__(self, profiles: list[IProfile]) -> None:
self._mappings = {}
for profile in profiles:
for key, value in profile.mappings.items():
self._mappings[key] = value
def map(self, data: object, data_type: type[T]) -> T:
if not is_dataclass(data_type):
raise TypeError("type must be a dataclass")
mapping_key = (type(data), data_type,)
data_fields = fields(data_type)
data_params = {}
mappings = self._mappings.get(mapping_key, {})
for field in data_fields:
field_name, field_type = field.name, field.type
field_value = getattr(data, field_name, None)
if is_dataclass(field_type):
field_value = self.map(field_value, field_type)
else:
if field_name in mappings:
field_value = mappings[field_name](field_value)
if not field_value and field.default is not MISSING:
field_value = field.default
data_params[field_name] = field_value
return data_type(**data_params)
I won't claim it's perfect but it works well enough for what I required.
https://gist.github.com/ahancock1/5e5e0c665c3e696f1e8085f7b38bd123
|
Is there a python implementation to .net automapper?
|
Automapper is a object-object mapper where we can use to project domain model to view model in asp.net mvc.
http://automapper.codeplex.com/
Is there equivalent implementation in Python for use in Django(Template)/Pylons ?
Or is there necessity for this in Python world?
|
[
"Yes, There is.\n\nObjectMapper is a class for automatic object mapping. It helps you to create objects between project layers (data layer, service layer, view) in a simple, transparent way.\n\nhttps://pypi.python.org/pypi/object-mapper\n",
"This generally isn't necessary in Python. We have some pretty complex domain models and we're able to use them in our views easily, without noticing any performance issues, and we serve millions of page views a month.\nAlso remember that \"view\" in Django == \"controller\" in MVC, and \"template\" in Django is \"view\" in MVC. Hence MTV rather than MVC. Something that tripped me up initially :-)\nIf there's some specific issue you're running into, post that as a question too ...\n",
"Here is a nice Python automapper that is possible to extend for any framework models:\nhttps://pypi.org/project/py-automapper/\n",
"I ended up rolling my own basic version of automapper modelled on the .net version.\nfrom typing import Protocol, TypeVar, Callable\n\nfrom dataclasses import is_dataclass, fields\nfrom dataclasses import MISSING\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass IProfile(Protocol):\n\n mappings: dict[tuple[type[S], type[T]], dict[str, Callable[[S], object]]]\n\n def create_map(self,\n source_type: type[S],\n target_type: type[T],\n **mappings: Callable[[S], object]) -> None:\n ...\n\n\nclass IMapper(Protocol):\n\n def map(self, data: object, data_type: type[T]) -> T:\n ...\n\n\nclass Profile:\n\n mappings: dict[tuple[type[S], type[T]], dict[str, Callable[[S], object]]]\n\n def __init__(self) -> None:\n\n self.mappings = {}\n\n def create_map(self,\n source_type: type[S],\n target_type: type[T],\n **mappings: Callable[[S], object]) -> None:\n\n self.mappings[(source_type, target_type)] = dict(mappings)\n\n\nclass Mapper:\n\n _mappings: dict[tuple[type[S], type[T]], dict[str, Callable[[S], object]]]\n\n def __init__(self, profiles: list[IProfile]) -> None:\n\n self._mappings = {}\n\n for profile in profiles:\n for key, value in profile.mappings.items():\n self._mappings[key] = value\n\n def map(self, data: object, data_type: type[T]) -> T:\n\n if not is_dataclass(data_type):\n raise TypeError(\"type must be a dataclass\")\n\n mapping_key = (type(data), data_type,)\n\n data_fields = fields(data_type)\n data_params = {}\n\n mappings = self._mappings.get(mapping_key, {})\n\n for field in data_fields:\n\n field_name, field_type = field.name, field.type\n field_value = getattr(data, field_name, None)\n\n if is_dataclass(field_type):\n field_value = self.map(field_value, field_type)\n else:\n if field_name in mappings:\n field_value = mappings[field_name](field_value)\n\n if not field_value and field.default is not MISSING:\n field_value = field.default\n\n data_params[field_name] = field_value\n\n return data_type(**data_params)\n\nI won't claim it's perfect but it works well enough for what I required.\nhttps://gist.github.com/ahancock1/5e5e0c665c3e696f1e8085f7b38bd123\n"
] |
[
14,
2,
0,
0
] |
[] |
[] |
[
"automapper",
"django",
"pylons",
"python"
] |
stackoverflow_0003348925_automapper_django_pylons_python.txt
|
Q:
Drop non-unique values in a range of columns based on a condition from a different range of columns
This is a small part of a df.
In this case, I have 3 y-values I need to map: 0.933883, 97.658330 and 1.650013
I have this df
x y1 y2 y3 y4 d1 d2 d3 d4
23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN
25 5.3 NaN NaN NaN 97.658330 NaN NaN NaN 0.038670
26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN
29 5.3 NaN NaN 97.658330 NaN NaN NaN 96.549581 NaN
30 5.3 NaN NaN NaN 1.650013 NaN NaN NaN 96.046987
There is not more than one of these values per column, I already dropped duplicates.
What I need:
I can not have the same value in more than one column.
The condition to choose which row to remove is as shown in this example:
There is 97.658330 in column y3 and y4. Since, for that value, d3(96.549581) is bigger than d4(0.038670), row 29 is removed.
There is 1.650013 in column y3 and y4. Since d4(96.046987) is bigger than d3(0.541264), row 30 is removed.
Output:
x y1 y2 y3 y4 d1 d2 d3 d4
23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN
25 5.3 NaN NaN NaN 97.658330 NaN NaN NaN 0.038670
26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN
P.S. There are a lot more values to map inside the complete data frame.
A:
You can use:
y = df.filter(regex=r'y\d+')
d = df.filter(regex=r'd\d+')
# target = [0.933883, 97.658330, 1.650013]
# define the target values automatically
s = y.stack()
target = set(s[s.duplicated()])
# {1.650013, 97.65833}
drop = set()
for x in target:
s = d.where(y.eq(x).to_numpy()).stack().droplevel(1)
drop.update(s.index.difference([s.idxmin()]))
# drop is {29, 30}
out = df.drop(drop)
Output:
x y1 y2 y3 y4 d1 d2 d3 d4
23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN
25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867
26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN
A:
There may be a more effective solution, but this works. First, let's take the common values in columns y3 and y4 as a list. Then find what are the values of d3 and d4 while y3 and y4 take the common values ? (v1,v2)
. Finally Drop row by index number according to specified condition.
vals=sorted(list(df[['y3','y4']].stack()))
dupes = list(set(vals[::2]) & set(vals[1::2])) #https://stackoverflow.com/a/64956890/15415267
#dupes= [1.650013, 97.65833]
for i in dupes:
v1=df[df['y3']==i]['d3'].iloc[0]
v2=df[df['y4']==i]['d4'].iloc[0]
if v1 > v2:
df=df.drop(df[df['y3']==i]['d3'].index)
else:
df=df.drop(df[df['y4']==i]['d4'].index)
print(df)
'''
x y1 y2 y3 y4 d1 d2 d3 d4
23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN
25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867
26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN
'''
|
Drop non-unique values in a range of columns based on a condition from a different range of columns
|
This is a small part of a df.
In this case, I have 3 y-values I need to map: 0.933883, 97.658330 and 1.650013
I have this df
x y1 y2 y3 y4 d1 d2 d3 d4
23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN
25 5.3 NaN NaN NaN 97.658330 NaN NaN NaN 0.038670
26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN
29 5.3 NaN NaN 97.658330 NaN NaN NaN 96.549581 NaN
30 5.3 NaN NaN NaN 1.650013 NaN NaN NaN 96.046987
There is not more than one of these values per column, I already dropped duplicates.
What I need:
I can not have the same value in more than one column.
The condition to choose which row to remove is as shown in this example:
There is 97.658330 in column y3 and y4. Since, for that value, d3(96.549581) is bigger than d4(0.038670), row 29 is removed.
There is 1.650013 in column y3 and y4. Since d4(96.046987) is bigger than d3(0.541264), row 30 is removed.
Output:
x y1 y2 y3 y4 d1 d2 d3 d4
23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN
25 5.3 NaN NaN NaN 97.658330 NaN NaN NaN 0.038670
26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN
P.S. There are a lot more values to map inside the complete data frame.
|
[
"You can use:\ny = df.filter(regex=r'y\\d+')\nd = df.filter(regex=r'd\\d+')\n\n# target = [0.933883, 97.658330, 1.650013]\n\n# define the target values automatically\ns = y.stack()\ntarget = set(s[s.duplicated()])\n# {1.650013, 97.65833}\n\ndrop = set()\nfor x in target:\n s = d.where(y.eq(x).to_numpy()).stack().droplevel(1)\n drop.update(s.index.difference([s.idxmin()]))\n\n# drop is {29, 30}\n\nout = df.drop(drop)\n\nOutput:\n x y1 y2 y3 y4 d1 d2 d3 d4\n23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN\n25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867\n26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN\n\n",
"There may be a more effective solution, but this works. First, let's take the common values in columns y3 and y4 as a list. Then find what are the values of d3 and d4 while y3 and y4 take the common values ? (v1,v2)\n. Finally Drop row by index number according to specified condition.\nvals=sorted(list(df[['y3','y4']].stack()))\ndupes = list(set(vals[::2]) & set(vals[1::2])) #https://stackoverflow.com/a/64956890/15415267\n#dupes= [1.650013, 97.65833]\n\nfor i in dupes:\n v1=df[df['y3']==i]['d3'].iloc[0]\n v2=df[df['y4']==i]['d4'].iloc[0]\n if v1 > v2:\n df=df.drop(df[df['y3']==i]['d3'].index)\n else:\n df=df.drop(df[df['y4']==i]['d4'].index)\nprint(df)\n'''\n x y1 y2 y3 y4 d1 d2 d3 d4\n23 5.3 NaN NaN 0.933883 NaN NaN NaN 0.174866 NaN\n25 5.3 NaN NaN NaN 97.65833 NaN NaN NaN 0.03867\n26 5.3 NaN NaN 1.650013 NaN NaN NaN 0.541264 NaN\n'''\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074511824_dataframe_pandas_python.txt
|
Q:
How can I centre/detect the digits for MNIST Handwritten Digit Prediction?
I am producing a mobile app and in the first part of it, the user will have to take a photo of a sudoku grid and the computer will scan and read it, using my trained TensorFlow Model.
I have a big issue with the TensorFlow model though, it seems to not be very good at its job, and I think it's not the model's fault but rather that the tensors being sent don't have the digits centred.
Obviously, I don't expect 100% accuracy but especially for digits printed on[ the grid, I would expect better as around 20% of digits seem to be wrong.
Here is a picture of a 6 which the model predicted as an 8
img=<base64 string represeting 313*320 image of grid>
[This is the base64 image at the top](https://i.stack.imgur.com/OrPis.jpg)
import cv2
import json
import numpy as np
import tensorflow as tf
import base64
import matplotlib.pyplot as plt
model = tf.keras.models.load_model("newmodel")
data = base64.b64decode(img)
np_data = np.fromstring(data, np.uint8)
img = cv2.imdecode(np_data, cv2.IMREAD_GRAYSCALE)
height, width = img.shape
img = cv2.resize(img, (width, width))
height, width = img.shape
print(height,width)
nums = []
for y in range(9):
row = []
for x in range(9):
left = round(x*(width)/9+3)
top = round(y*(height)/9+3)
right = round((x+1)*(width)/9-3)
bottom = round((y+1)*(height)/9-3)
image = img[top:bottom, left:right]
image = np.array(image)
image = cv2.resize(image, (28,28))
image = 255-image
#Checking for empty cells
numofBlack = 0
for r in image:
for item in r:
if item > 127:
numofBlack += 1
if numofBlack < 50:
row.append(0)
else:
pred = model.predict(image.reshape(1,28, 28, 1))
row.append(int(pred.argmax()))
nums.append(row)
print(nums)
The grid from the image above returned:
[[8, 3, 0, 0, 7, 0, 0, 0, 0], [8, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 8], [4, 0, 0, 8, 0, 3, 0, 0, 7], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 8, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 6]]
Mistaking one or two digits its fine with me because I can have a manual check after the image detection and I get that the model won't be perfect but the number of 8's that were read from digits that aren't 8 is suspicious and I feel like it might come from the digits being slightly off centred.
So, the question: Is there a library in python I can use to detect the digits in the cells rather than the current manual method with round(x*(width)/9+3) and ugly maths like that OR is the problem I'm facing and hence the solution, something completely different?
A:
Thanks to NickODell's helpful comments, my solution is going to be to find the centre of mass of each image and shift the images to centre them.
Here is the link to the python solution I'm using:
center of mass of pixels in grayscale image
|
How can I centre/detect the digits for MNIST Handwritten Digit Prediction?
|
I am producing a mobile app and in the first part of it, the user will have to take a photo of a sudoku grid and the computer will scan and read it, using my trained TensorFlow Model.
I have a big issue with the TensorFlow model though, it seems to not be very good at its job, and I think it's not the model's fault but rather that the tensors being sent don't have the digits centred.
Obviously, I don't expect 100% accuracy but especially for digits printed on[ the grid, I would expect better as around 20% of digits seem to be wrong.
Here is a picture of a 6 which the model predicted as an 8
img=<base64 string represeting 313*320 image of grid>
[This is the base64 image at the top](https://i.stack.imgur.com/OrPis.jpg)
import cv2
import json
import numpy as np
import tensorflow as tf
import base64
import matplotlib.pyplot as plt
model = tf.keras.models.load_model("newmodel")
data = base64.b64decode(img)
np_data = np.fromstring(data, np.uint8)
img = cv2.imdecode(np_data, cv2.IMREAD_GRAYSCALE)
height, width = img.shape
img = cv2.resize(img, (width, width))
height, width = img.shape
print(height,width)
nums = []
for y in range(9):
row = []
for x in range(9):
left = round(x*(width)/9+3)
top = round(y*(height)/9+3)
right = round((x+1)*(width)/9-3)
bottom = round((y+1)*(height)/9-3)
image = img[top:bottom, left:right]
image = np.array(image)
image = cv2.resize(image, (28,28))
image = 255-image
#Checking for empty cells
numofBlack = 0
for r in image:
for item in r:
if item > 127:
numofBlack += 1
if numofBlack < 50:
row.append(0)
else:
pred = model.predict(image.reshape(1,28, 28, 1))
row.append(int(pred.argmax()))
nums.append(row)
print(nums)
The grid from the image above returned:
[[8, 3, 0, 0, 7, 0, 0, 0, 0], [8, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 8], [4, 0, 0, 8, 0, 3, 0, 0, 7], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 8, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 6]]
Mistaking one or two digits its fine with me because I can have a manual check after the image detection and I get that the model won't be perfect but the number of 8's that were read from digits that aren't 8 is suspicious and I feel like it might come from the digits being slightly off centred.
So, the question: Is there a library in python I can use to detect the digits in the cells rather than the current manual method with round(x*(width)/9+3) and ugly maths like that OR is the problem I'm facing and hence the solution, something completely different?
|
[
"Thanks to NickODell's helpful comments, my solution is going to be to find the centre of mass of each image and shift the images to centre them.\nHere is the link to the python solution I'm using:\ncenter of mass of pixels in grayscale image\n"
] |
[
1
] |
[] |
[] |
[
"digits",
"image_processing",
"mnist",
"python",
"tensorflow"
] |
stackoverflow_0074512039_digits_image_processing_mnist_python_tensorflow.txt
|
Q:
Pyspark Improve Repetitive Function Calls When Returning Dataframes
I have a multiple dataframes that I need to apply different functions to and I want to know if there is a way better way to do this in pyspark ?
I am doing the following right now:
df1 = function_one(df1)
df2 = function_one(df2)
df3 = function_one(df3)
df1 = function_two(df1, dfx, 0)
df2 = function_two(df2, dfx, 1)
df3 = function_two(df3, dfx, 2)
I have tried this:
list_dfs = [df1, df2, df3]
num_list = [0,1,2]
for dataframe,num in zip(list_dfs,num_list):
dataframe = function(dataframe)
dataframe = function_two(dataframe , dfx, num)
This does not apply the changes.
Is there a way I can maybe do a loop in pyspark and apply the function to the multiple dataframes?
A:
This is just something I wrote quickly (not tested)
Just a suggestion, not sure if it's more convenient than what you're doing already (obviously it is if you have more dfs)
def make_changes(df):
df = func(df)
df = func2(df)
return df
new_df_list = []
df_list = [df1, df2, df3]
for dfs in df_list:
new_df_list.append(make_changes(dfs))
|
Pyspark Improve Repetitive Function Calls When Returning Dataframes
|
I have a multiple dataframes that I need to apply different functions to and I want to know if there is a way better way to do this in pyspark ?
I am doing the following right now:
df1 = function_one(df1)
df2 = function_one(df2)
df3 = function_one(df3)
df1 = function_two(df1, dfx, 0)
df2 = function_two(df2, dfx, 1)
df3 = function_two(df3, dfx, 2)
I have tried this:
list_dfs = [df1, df2, df3]
num_list = [0,1,2]
for dataframe,num in zip(list_dfs,num_list):
dataframe = function(dataframe)
dataframe = function_two(dataframe , dfx, num)
This does not apply the changes.
Is there a way I can maybe do a loop in pyspark and apply the function to the multiple dataframes?
|
[
"This is just something I wrote quickly (not tested)\nJust a suggestion, not sure if it's more convenient than what you're doing already (obviously it is if you have more dfs)\ndef make_changes(df):\n df = func(df)\n df = func2(df)\n return df\n\nnew_df_list = []\ndf_list = [df1, df2, df3]\nfor dfs in df_list:\n new_df_list.append(make_changes(dfs))\n\n"
] |
[
0
] |
[] |
[] |
[
"automation",
"dataframe",
"loops",
"pyspark",
"python"
] |
stackoverflow_0074512259_automation_dataframe_loops_pyspark_python.txt
|
Q:
Redirection to previous page after login using LoginRequiredMiddleware
I used to use next_param = request.POST.get('next') to redirect users to their previous page after they log in.
I however, decided to go fancier with my code and now force any unauthenticated user to login by using LoginRequiredMiddleware: users are automatically redirected to login page if not authenticated.
This allows me to avoid having to call a decorator for all views. Instead, specify the accessible views that don't require the user to be logged in.
Small problem: my next_param = request.POST.get('next')doesnt work now for obvious reason: I cannot stick
?next={{ request.path|urlencode}} in the referring page since the redirection happens automatically and the user doesnt have to click anywhere.
What alternative do I have to redirect the user to the initial/previous page they landed on before being redirected automatically?
base.py
MIDDLEWARE = [
..
'mysite.middleware.LoginRequiredMiddleware',
]
middleware.py
import re
from django.conf import settings
from django.shortcuts import redirect
EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
pass
def __init__(self, get_response):
self.get_response = get_response
def __call__ (self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
assert hasattr(request,'user')
path = request.path_info.lstrip('/')
print(path)
if not request.user.is_authenticated:
if not any(url.match(path) for url in EXEMPT_URLS):
return redirect(settings.LOGIN_URL)
views.py
def login_user(request):
if request.user.is_authenticated:
return redirect('list-venues')
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
next_param = request.POST.get('next')
if next_param: #<-- this is the bit that is not working anymore
url= next_param
else:
url = reverse('list-venues')
return redirect(url)
else:
messages.success(request,("There was an error, try again!"))
return redirect('login_user')
else:
return render(request,'main/registration/login_user.html',{})
A:
You could place it in a session variable
In your middleware
request.session['next_param'] = path
return redirect(settings.LOGIN_URL)
Then in your login page
...
if user is not None:
login(request, user)
#next_param = request.POST.get('next')
url= request.session.get('next_param', reverse('list_venues'))
return redirect(url)
|
Redirection to previous page after login using LoginRequiredMiddleware
|
I used to use next_param = request.POST.get('next') to redirect users to their previous page after they log in.
I however, decided to go fancier with my code and now force any unauthenticated user to login by using LoginRequiredMiddleware: users are automatically redirected to login page if not authenticated.
This allows me to avoid having to call a decorator for all views. Instead, specify the accessible views that don't require the user to be logged in.
Small problem: my next_param = request.POST.get('next')doesnt work now for obvious reason: I cannot stick
?next={{ request.path|urlencode}} in the referring page since the redirection happens automatically and the user doesnt have to click anywhere.
What alternative do I have to redirect the user to the initial/previous page they landed on before being redirected automatically?
base.py
MIDDLEWARE = [
..
'mysite.middleware.LoginRequiredMiddleware',
]
middleware.py
import re
from django.conf import settings
from django.shortcuts import redirect
EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
pass
def __init__(self, get_response):
self.get_response = get_response
def __call__ (self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
assert hasattr(request,'user')
path = request.path_info.lstrip('/')
print(path)
if not request.user.is_authenticated:
if not any(url.match(path) for url in EXEMPT_URLS):
return redirect(settings.LOGIN_URL)
views.py
def login_user(request):
if request.user.is_authenticated:
return redirect('list-venues')
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
next_param = request.POST.get('next')
if next_param: #<-- this is the bit that is not working anymore
url= next_param
else:
url = reverse('list-venues')
return redirect(url)
else:
messages.success(request,("There was an error, try again!"))
return redirect('login_user')
else:
return render(request,'main/registration/login_user.html',{})
|
[
"You could place it in a session variable\nIn your middleware\n request.session['next_param'] = path\n return redirect(settings.LOGIN_URL)\n\nThen in your login page\n ... \n if user is not None:\n login(request, user)\n #next_param = request.POST.get('next')\n url= request.session.get('next_param', reverse('list_venues'))\n return redirect(url)\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_middleware",
"django_views",
"python"
] |
stackoverflow_0074511980_django_django_middleware_django_views_python.txt
|
Q:
How to make while loop a function in python?
I created a While Loop that works perfectly fine on its own. However, once I try to store it as a function, it no longer works. Below is a simple example of my problem.
import random
money = 100
bet = 0
while bet < 10:
outcome = random.randint(0,1)
bet = bet + 1
if outcome == 1:
money = money + 10
if outcome == 0:
money = money - 10
money
Here is my attempt to store it as a function. The output only runs one bet and not all 10.
def loop():
money = 100
bet = 0
while bet < 10:
outcome = random.randint(0,1)
bet = bet + 1
if outcome == 1:
money = money + 10
if outcome == 0:
money = money - 10
return money
A:
You make a simple mistake with an indent - your return is in while loop, so it returns after first iteration. Move it back a bit ;)
def loop():
money = 100
bet = 0
while bet < 10:
outcome = random.randint(0,1)
bet = bet + 1
if outcome == 1:
money = money + 10
if outcome == 0:
money = money - 10
return money
|
How to make while loop a function in python?
|
I created a While Loop that works perfectly fine on its own. However, once I try to store it as a function, it no longer works. Below is a simple example of my problem.
import random
money = 100
bet = 0
while bet < 10:
outcome = random.randint(0,1)
bet = bet + 1
if outcome == 1:
money = money + 10
if outcome == 0:
money = money - 10
money
Here is my attempt to store it as a function. The output only runs one bet and not all 10.
def loop():
money = 100
bet = 0
while bet < 10:
outcome = random.randint(0,1)
bet = bet + 1
if outcome == 1:
money = money + 10
if outcome == 0:
money = money - 10
return money
|
[
"You make a simple mistake with an indent - your return is in while loop, so it returns after first iteration. Move it back a bit ;)\ndef loop():\n money = 100\n bet = 0\n \n while bet < 10:\n outcome = random.randint(0,1)\n bet = bet + 1\n\n if outcome == 1:\n money = money + 10\n\n if outcome == 0:\n money = money - 10\n\n return money\n\n"
] |
[
1
] |
[] |
[] |
[
"probability",
"python",
"while_loop"
] |
stackoverflow_0074512382_probability_python_while_loop.txt
|
Q:
Switch/Change the version of Python in pyscript
I am just started looking/experimenting pyscript as per the current python code which is running on Python 3.6.0. But looks like pyscript loads the python version along with Pyodide and it is retuning the latest stable version based on the Pyodide version.
Problem Statement : Is there any way we can change/switch the python version as per the need while working with pyscript ?
What did I tried so far to verify the Pyodide and Python version :
I checked the version of Pyodide by using below code.
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css"/>
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<py-script>import pyodide_js; print(pyodide_js.version)</py-script>
As per the above code snippet, It is returning 0.21.2, Now to check python version.
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css"/>
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<py-script>
import pyodide_js;
import sys;
print('Pyodide version : ' + pyodide_js.version)
print('Python version : ' + sys.version)
</py-script>
It is returning 3.10.2 but I want to change/switch it to 3.6.0.
A:
YOu cannot as Python is built into Pyodide. You would need to rebuild Pyodide to change the version of Python. I also do not think that Python 3.6 will work with the current version of PyScript and Pyodide. Your only practical option is to make your application work with the Pyodide version of Python.
|
Switch/Change the version of Python in pyscript
|
I am just started looking/experimenting pyscript as per the current python code which is running on Python 3.6.0. But looks like pyscript loads the python version along with Pyodide and it is retuning the latest stable version based on the Pyodide version.
Problem Statement : Is there any way we can change/switch the python version as per the need while working with pyscript ?
What did I tried so far to verify the Pyodide and Python version :
I checked the version of Pyodide by using below code.
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css"/>
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<py-script>import pyodide_js; print(pyodide_js.version)</py-script>
As per the above code snippet, It is returning 0.21.2, Now to check python version.
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css"/>
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<py-script>
import pyodide_js;
import sys;
print('Pyodide version : ' + pyodide_js.version)
print('Python version : ' + sys.version)
</py-script>
It is returning 3.10.2 but I want to change/switch it to 3.6.0.
|
[
"YOu cannot as Python is built into Pyodide. You would need to rebuild Pyodide to change the version of Python. I also do not think that Python 3.6 will work with the current version of PyScript and Pyodide. Your only practical option is to make your application work with the Pyodide version of Python.\n"
] |
[
0
] |
[] |
[] |
[
"pyodide",
"pyscript",
"python"
] |
stackoverflow_0074509113_pyodide_pyscript_python.txt
|
Q:
Displaying Outliers Using The any() function
I have created a dataframe of five columns and 500 rows. The dataframe holds random integer values by executing the following Python code:
RandomValues = pd.DataFrame(np.random.randint(0, 100, size=(500, 5)),
columns=['Name', 'State', 'Age', 'Experience', 'Annual Income'])
The following is the data frame:
Name State Age Experience Annual Income
0 85 10 16 56 89
1 94 1 87 61 37
2 51 7 37 18 92
3 15 1 62 72 60
4 84 88 1 43 14
... ... ... ... ... ...
495 66 33 67 84 7
496 81 2 55 87 59
497 38 50 40 77 36
498 68 45 37 55 90
499 13 82 84 98 35
I am using the standard deviation to find outliers in the "Annual Income" column.
upper_limit = RandomValues['Annual Income'].mean() + 3 * RandomValues['Annual Income'].std()
lower_limit = RandomValues['Annual Income'].mean() - 3 * RandomValues['Annual Income'].std()
How can I use the any() method to find the outliers on the "Annual Income" column of the "RandomValues" dataframe. I appreciate any help. Thank you.
I have tried to use the where() method, as well as the following Python code, but it did not solve the problem:
highOutliers = RandomValues['Annual Income'] < upper_limit
lowOutliers = RandomValues['Annual Income'] > lower_limit
print(highOutliers)
print(lowOutliers)
Secondly, I have attempted the following, but am getting back a Series with an empty list:
highOutliers = RandomValues.loc[RandomValues['Annual Income'] > upper_limit, 'Annual Income']
lowOutliers = RandomValues.loc[RandomValues['Annual Income'] < lower_limit, 'Annual Income']
print(highOutliers)
print(lowOutliers)
Output:
Series([], Name: Annual Income, dtype: int64)
Series([], Name: Annual Income, dtype: int64)
A:
When you just do a comparison like this, you're creating a boolean series, which is the same shape as your Annual Income column, but containing True/False values
highOutliers_locations = RandomValues['Annual Income'] > upper_limit
lowOutliers_locations = RandomValues['Annual Income'] < lower_limit
This is a useful step in calculating the outliers, but you haven't subset the data yet.
To actually subset your dataframe to only include these outliers, use indexing, e.g with .loc:
highOutliers = RandomValues.loc[highOutliers_locations, 'Annual Income']
lowOutliers = RandomValues.loc[lowOutliers_locations, 'Annual Income']
Or, in one step:
highOutliers = RandomValues.loc[
RandomValues['Annual Income'] > upper_limit, 'Annual Income'
]
lowOutliers = RandomValues.loc[
RandomValues['Annual Income'] < lower_limit, 'Annual Income'
]
See the pandas guide to indexing and selecting data for more info and examples
|
Displaying Outliers Using The any() function
|
I have created a dataframe of five columns and 500 rows. The dataframe holds random integer values by executing the following Python code:
RandomValues = pd.DataFrame(np.random.randint(0, 100, size=(500, 5)),
columns=['Name', 'State', 'Age', 'Experience', 'Annual Income'])
The following is the data frame:
Name State Age Experience Annual Income
0 85 10 16 56 89
1 94 1 87 61 37
2 51 7 37 18 92
3 15 1 62 72 60
4 84 88 1 43 14
... ... ... ... ... ...
495 66 33 67 84 7
496 81 2 55 87 59
497 38 50 40 77 36
498 68 45 37 55 90
499 13 82 84 98 35
I am using the standard deviation to find outliers in the "Annual Income" column.
upper_limit = RandomValues['Annual Income'].mean() + 3 * RandomValues['Annual Income'].std()
lower_limit = RandomValues['Annual Income'].mean() - 3 * RandomValues['Annual Income'].std()
How can I use the any() method to find the outliers on the "Annual Income" column of the "RandomValues" dataframe. I appreciate any help. Thank you.
I have tried to use the where() method, as well as the following Python code, but it did not solve the problem:
highOutliers = RandomValues['Annual Income'] < upper_limit
lowOutliers = RandomValues['Annual Income'] > lower_limit
print(highOutliers)
print(lowOutliers)
Secondly, I have attempted the following, but am getting back a Series with an empty list:
highOutliers = RandomValues.loc[RandomValues['Annual Income'] > upper_limit, 'Annual Income']
lowOutliers = RandomValues.loc[RandomValues['Annual Income'] < lower_limit, 'Annual Income']
print(highOutliers)
print(lowOutliers)
Output:
Series([], Name: Annual Income, dtype: int64)
Series([], Name: Annual Income, dtype: int64)
|
[
"When you just do a comparison like this, you're creating a boolean series, which is the same shape as your Annual Income column, but containing True/False values\nhighOutliers_locations = RandomValues['Annual Income'] > upper_limit\nlowOutliers_locations = RandomValues['Annual Income'] < lower_limit\n\nThis is a useful step in calculating the outliers, but you haven't subset the data yet.\nTo actually subset your dataframe to only include these outliers, use indexing, e.g with .loc:\nhighOutliers = RandomValues.loc[highOutliers_locations, 'Annual Income']\nlowOutliers = RandomValues.loc[lowOutliers_locations, 'Annual Income']\n\nOr, in one step:\nhighOutliers = RandomValues.loc[\n RandomValues['Annual Income'] > upper_limit, 'Annual Income'\n]\nlowOutliers = RandomValues.loc[\n RandomValues['Annual Income'] < lower_limit, 'Annual Income'\n]\n\nSee the pandas guide to indexing and selecting data for more info and examples\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074512328_dataframe_pandas_python.txt
|
Q:
MNLogit fit and summary displays all nan
I am new to ML world.
Trying to do Logistic regression from Stats model. However, when I execute I get current Function Value as nan
I tried checking if dataframe is finite as I saw it might be cause. But that turns out to be ok.
Referred the below link, but did not work in my case.
update : Still did not figure it out
Referred Links :
MNLogit in statsmodel returning nan
numpy: Invalid value encountered in true_divide
Please can someone help me on this ?
A:
After reviewing your problem and the solution identified in referred link#1. {FYI it gives the same error as shown in your screen capture.}
It seems like you need to identify a different solving method.
In your code you can try to do the following to have the same solution as link#1.
result=logit_model.fit(method='bfgs')
I'm sorry if you already tried this. Unfortunately, I cannot test it without the dataset, let me know if that works.
|
MNLogit fit and summary displays all nan
|
I am new to ML world.
Trying to do Logistic regression from Stats model. However, when I execute I get current Function Value as nan
I tried checking if dataframe is finite as I saw it might be cause. But that turns out to be ok.
Referred the below link, but did not work in my case.
update : Still did not figure it out
Referred Links :
MNLogit in statsmodel returning nan
numpy: Invalid value encountered in true_divide
Please can someone help me on this ?
|
[
"After reviewing your problem and the solution identified in referred link#1. {FYI it gives the same error as shown in your screen capture.}\nIt seems like you need to identify a different solving method.\nIn your code you can try to do the following to have the same solution as link#1.\nresult=logit_model.fit(method='bfgs')\n\nI'm sorry if you already tried this. Unfortunately, I cannot test it without the dataset, let me know if that works.\n"
] |
[
0
] |
[] |
[] |
[
"machine_learning",
"pandas",
"python",
"statsmodels"
] |
stackoverflow_0074470088_machine_learning_pandas_python_statsmodels.txt
|
Q:
How to "skip" a character in a string in Python?
I just stated learning Python. My teacher asked me to take this string "quick brown fox, jumps over the lazy dog!", iterate all letter using i in range() function, and whenever I find a whitespace in the string I need to make the next character uppercase. So that the final output would be Quick Brown Fox, Jumps Over The Lazy Dog!
The teacher said that I may need to use len(mastering)-1 for this homework.
Below is my code. I don’t know why I see the uppercase letter and then the repeated lower case of the same letter. I don't know how to skip them from the string during looping. Any suggestions are greatly appreciated!
I tried using different sequences in the for loop function but none worked.
mystring = 'quick brown fox, jumps over the lazy dog!'
newstring = mystring[0].upper()
for i in range (1,len(mystring)):
newstring = newstring + mystring [i]
if mystring [i] == ' ':
newstring = newstring + mystring[i+1].upper()
print (newstring)
I am getting double letters. Here is the output -
Quick Bbrown Ffox, Jjumps Oover Tthe Llazy Ddog!
A:
Iterating over indices using for i in range(len(container)) is frowned upon in python. Instead use for element in container to get the elements directly. If you need the index, you can use enumerate to get the element and index.
As for your question: one approach would be to create a variable that remembers if your previous character was a space. If it was, make the current letter uppercase. If not, append it to the new string as-is.
Another point to remember is that when you append to a string repeatedly in a loop, e.g.: str1 = str1 + new_character python needs to copy all characters from the old string, plus your new character, to the new string every time this operation is performed. It is more efficient to append all your characters to a list, and use str.join to join all elements of that list in one shot after your iterations are done.
mystring = 'quick brown fox, jumps over the lazy dog!'
result = []
uppercase_next = True # Since you want to uppercase the first character, we default this to True
for char in mystring:
if uppercase_next:
result.append(char.upper())
else:
result.append(char)
uppercase_next = (char == " ") # char == " " figures out if the character is a space,
# Then we assign the result to the variable uppercase_next
newstring = "".join(result)
print(newstring)
A:
You are very close! To debug the program it's often good to take the simple input and go line by line, drawing what is happening on some sheet of paper.
Here when your i == 6 mystring[i] points to space. Condition is fulfilled, nestring becomes "Quick" + "b".upper(), great! But now i==7 and you add newstring (which is Quick B) mystring[i] which is b.
To fix it you could e.g. check if previous character is a space:
for i in range (1,len(mystring)):
if mystring [i-1] == ' ':
newstring = newstring + mystring[i].upper()
else:
newstring = newstring + mystring[i]
And as a bonus, one liner for that.
" ".join(word.capitalize() for word in mystring.split(" "))
|
How to "skip" a character in a string in Python?
|
I just stated learning Python. My teacher asked me to take this string "quick brown fox, jumps over the lazy dog!", iterate all letter using i in range() function, and whenever I find a whitespace in the string I need to make the next character uppercase. So that the final output would be Quick Brown Fox, Jumps Over The Lazy Dog!
The teacher said that I may need to use len(mastering)-1 for this homework.
Below is my code. I don’t know why I see the uppercase letter and then the repeated lower case of the same letter. I don't know how to skip them from the string during looping. Any suggestions are greatly appreciated!
I tried using different sequences in the for loop function but none worked.
mystring = 'quick brown fox, jumps over the lazy dog!'
newstring = mystring[0].upper()
for i in range (1,len(mystring)):
newstring = newstring + mystring [i]
if mystring [i] == ' ':
newstring = newstring + mystring[i+1].upper()
print (newstring)
I am getting double letters. Here is the output -
Quick Bbrown Ffox, Jjumps Oover Tthe Llazy Ddog!
|
[
"Iterating over indices using for i in range(len(container)) is frowned upon in python. Instead use for element in container to get the elements directly. If you need the index, you can use enumerate to get the element and index.\nAs for your question: one approach would be to create a variable that remembers if your previous character was a space. If it was, make the current letter uppercase. If not, append it to the new string as-is.\nAnother point to remember is that when you append to a string repeatedly in a loop, e.g.: str1 = str1 + new_character python needs to copy all characters from the old string, plus your new character, to the new string every time this operation is performed. It is more efficient to append all your characters to a list, and use str.join to join all elements of that list in one shot after your iterations are done.\nmystring = 'quick brown fox, jumps over the lazy dog!'\n\nresult = []\n\nuppercase_next = True # Since you want to uppercase the first character, we default this to True\n\nfor char in mystring:\n if uppercase_next:\n result.append(char.upper())\n else:\n result.append(char)\n\n uppercase_next = (char == \" \") # char == \" \" figures out if the character is a space, \n # Then we assign the result to the variable uppercase_next\n \nnewstring = \"\".join(result) \nprint(newstring)\n\n",
"You are very close! To debug the program it's often good to take the simple input and go line by line, drawing what is happening on some sheet of paper.\nHere when your i == 6 mystring[i] points to space. Condition is fulfilled, nestring becomes \"Quick\" + \"b\".upper(), great! But now i==7 and you add newstring (which is Quick B) mystring[i] which is b.\nTo fix it you could e.g. check if previous character is a space:\nfor i in range (1,len(mystring)):\n if mystring [i-1] == ' ':\n newstring = newstring + mystring[i].upper()\n else:\n newstring = newstring + mystring[i]\n\nAnd as a bonus, one liner for that.\n\" \".join(word.capitalize() for word in mystring.split(\" \"))\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074512381_python.txt
|
Q:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
I've noticed that many operations on lists that modify the list's contents will return None, rather than returning the list itself. Examples:
>>> mylist = ['a', 'b', 'c']
>>> empty = mylist.clear()
>>> restored = mylist.extend(range(3))
>>> backwards = mylist.reverse()
>>> with_four = mylist.append(4)
>>> in_order = mylist.sort()
>>> without_one = mylist.remove(1)
>>> mylist
[0, 2, 4]
>>> [empty, restored, backwards, with_four, in_order, without_one]
[None, None, None, None, None, None]
What is the thought process behind this decision?
To me, it seems hampering, since it prevents "chaining" of list processing (e.g. mylist.reverse().append('a string')[:someLimit]). I imagine it might be that "The Powers That Be" decided that list comprehension is a better paradigm (a valid opinion), and so didn't want to encourage other methods - but it seems perverse to prevent an intuitive method, even if better alternatives exist.
This question is specifically about Python's design decision to return None from mutating list methods like .append. Novices often write incorrect code that expects .append (in particular) to return the same list that was just modified.
For the simple question of "how do I append to a list?" (or debugging questions that boil down to that problem), see Why does "x = x.append([i])" not work in a for loop?.
To get modified versions of the list, see:
For .sort: How can I get a sorted copy of a list?
For .reverse: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
The same issue applies to some methods of other built-in data types, e.g. set.discard (see How to remove specific element from sets inside a list using list comprehension) and dict.update (see Why doesn't a python dict.update() return the object?).
The same reasoning applies to designing your own APIs. See Is making in-place operations return the object a bad idea?.
A:
The general design principle in Python is for functions that mutate an object in-place to return None. I'm not sure it would have been the design choice I'd have chosen, but it's basically to emphasise that a new object is not returned.
Guido van Rossum (our Python BDFL) states the design choice on the Python-Dev mailing list:
I'd like to explain once more why I'm so adamant that sort() shouldn't
return 'self'.
This comes from a coding style (popular in various other languages, I
believe especially Lisp revels in it) where a series of side effects
on a single object can be chained like this:
x.compress().chop(y).sort(z)
which would be the same as
x.compress()
x.chop(y)
x.sort(z)
I find the chaining form a threat to readability; it requires that the
reader must be intimately familiar with each of the methods. The
second form makes it clear that each of these calls acts on the same
object, and so even if you don't know the class and its methods very
well, you can understand that the second and third call are applied to
x (and that all calls are made for their side-effects), and not to
something else.
I'd like to reserve chaining for operations that return new values,
like string processing operations:
y = x.rstrip("\n").split(":").lower()
There are a few standard library modules that encourage chaining of
side-effect calls (pstat comes to mind). There shouldn't be any new
ones; pstat slipped through my filter when it was weak.
A:
I can't speak for the developers, but I find this behavior very intuitive.
If a method works on the original object and modifies it in-place, it doesn't return anything, because there is no new information - you obviously already have a reference to the (now mutated) object, so why return it again?
If, however, a method or function creates a new object, then of course it has to return it.
So l.reverse() returns nothing (because now the list has been reversed, but the identfier l still points to that list), but reversed(l) has to return the newly generated list because l still points to the old, unmodified list.
EDIT: I just learned from another answer that this principle is called Command-Query separation.
A:
One could argue that the signature itself makes it clear that the function mutates the list rather than returning a new one: if the function returned a list, its behavior would have been much less obvious.
A:
If you were sent here after asking for help fixing your code:
In the future, please try to look for problems in the code yourself, by carefully studying what happens when the code runs. Rather than giving up because there is an error message, check the result of each calculation, and see where the code starts working differently from what you expect.
If you had code calling a method like .append or .sort on a list, you will notice that the return value is None, while the list is modified in place. Study the example carefully:
>>> x = ['e', 'x', 'a', 'm', 'p', 'l', 'e']
>>> y = x.sort()
>>> print(y)
None
>>> print(x)
['a', 'e', 'e', 'l', 'm', 'p', 'x']
y got the special None value, because that is what was returned. x changed, because the sort happened in place.
It works this way on purpose, so that code like x.sort().reverse() breaks. See the other answers to understand why the Python developers wanted it that way.
To fix the problem
First, think carefully about the intent of the code. Should x change? Do we actually need a separate y?
Let's consider .sort first. If x should change, then call x.sort() by itself, without assigning the result anywhere.
If a sorted copy is needed instead, use y = x.sorted(). See How can I get a sorted copy of a list? for details.
For other methods, we can get modified copies like so:
.clear -> there is no point to this; a "cleared copy" of the list is just an empty list. Just use y = [].
.append and .extend -> probably the simplest way is to use the + operator. To add multiple elements from a list l, use y = x + l rather than .extend. To add a single element e wrap it in a list first: y = x + [e]. Another way in 3.5 and up is to use unpacking: y = [*x, *l] for .extend, y = [*x, e] for .append. See also How to allow list append() method to return the new list for .append and How do I concatenate two lists in Python? for .extend.
.reverse -> First, consider whether an actual copy is needed. The built-in reversed gives you an iterator that can be used to loop over the elements in reverse order. To make an actual copy, simply pass that iterator to list: y = list(reversed(x)). See How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)? for details.
.remove -> Figure out the index of the element that will be removed (using .index), then use slicing to find the elements before and after that point and put them together. As a function:
def without(a_list, value):
index = a_list.index(value)
return a_list[:index] + a_list[index+1:]
(We can translate .pop similarly to make a modified copy, though of course .pop actually returns an element from the list.)
See also A quick way to return list without a specific element in Python.
(If you plan to remove multiple elements, strongly consider using a list comprehension (or filter) instead. It will be much simpler than any of the workarounds needed for removing items from the list while iterating over it. This way also naturally gives a modified copy.)
For any of the above, of course, we can also make a modified copy by explicitly making a copy and then using the in-place method on the copy. The most elegant approach will depend on the context and on personal taste.
A:
As we know list in python is a mutable object and one of characteristics of mutable object is the ability to modify the state of this object without the need to assign its new state to a variable. we should demonstrate more about this topic to understand the root of this issue.
An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created. Object mutability is one of the characteristics that makes Python a dynamically typed language.
Every object in python has three attributes:
Identity – This refers to the address that the object refers to in the computer’s memory.
Type – This refers to the kind of object that is created. For example integer, list, string etc.
Value – This refers to the value stored by the object. For example str = "a".
While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.
let us discuss the below code step-by-step to depict what it means in Python:
Creating a list which contains name of cities
cities = ['London', 'New York', 'Chicago']
Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(cities)))
Output [1]: 0x1691d7de8c8
Adding a new city to the list cities
cities.append('Delhi')
Printing the elements from the list cities, separated by a comma
for city in cities:
print(city, end=', ')
Output [2]: London, New York, Chicago, Delhi
Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(cities)))
Output [3]: 0x1691d7de8c8
The above example shows us that we were able to change the internal state of the object cities by adding one more city 'Delhi' to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name cities is a MUTABLE OBJECT.
While the immutable object internal state can not be changed. For instance, consider the below code and associated error message with it, while trying to change the value of a Tuple at index 0
Creating a Tuple with variable name foo
foo = (1, 2)
Changing the index 0 value from 1 to 3
foo[0] = 3
TypeError: 'tuple' object does not support item assignment
We can conclude from the examples why mutable object shouldn't return anything when executing operations on it because it's modifying the internal state of the object directly and there is no point in returning new modified object. unlike immutable object which should return new object of the modified state after executing operations on it.
|
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
|
I've noticed that many operations on lists that modify the list's contents will return None, rather than returning the list itself. Examples:
>>> mylist = ['a', 'b', 'c']
>>> empty = mylist.clear()
>>> restored = mylist.extend(range(3))
>>> backwards = mylist.reverse()
>>> with_four = mylist.append(4)
>>> in_order = mylist.sort()
>>> without_one = mylist.remove(1)
>>> mylist
[0, 2, 4]
>>> [empty, restored, backwards, with_four, in_order, without_one]
[None, None, None, None, None, None]
What is the thought process behind this decision?
To me, it seems hampering, since it prevents "chaining" of list processing (e.g. mylist.reverse().append('a string')[:someLimit]). I imagine it might be that "The Powers That Be" decided that list comprehension is a better paradigm (a valid opinion), and so didn't want to encourage other methods - but it seems perverse to prevent an intuitive method, even if better alternatives exist.
This question is specifically about Python's design decision to return None from mutating list methods like .append. Novices often write incorrect code that expects .append (in particular) to return the same list that was just modified.
For the simple question of "how do I append to a list?" (or debugging questions that boil down to that problem), see Why does "x = x.append([i])" not work in a for loop?.
To get modified versions of the list, see:
For .sort: How can I get a sorted copy of a list?
For .reverse: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
The same issue applies to some methods of other built-in data types, e.g. set.discard (see How to remove specific element from sets inside a list using list comprehension) and dict.update (see Why doesn't a python dict.update() return the object?).
The same reasoning applies to designing your own APIs. See Is making in-place operations return the object a bad idea?.
|
[
"The general design principle in Python is for functions that mutate an object in-place to return None. I'm not sure it would have been the design choice I'd have chosen, but it's basically to emphasise that a new object is not returned.\nGuido van Rossum (our Python BDFL) states the design choice on the Python-Dev mailing list:\n\nI'd like to explain once more why I'm so adamant that sort() shouldn't\nreturn 'self'.\nThis comes from a coding style (popular in various other languages, I\nbelieve especially Lisp revels in it) where a series of side effects\non a single object can be chained like this:\nx.compress().chop(y).sort(z)\n\nwhich would be the same as\nx.compress()\nx.chop(y)\nx.sort(z)\n\nI find the chaining form a threat to readability; it requires that the\nreader must be intimately familiar with each of the methods. The\nsecond form makes it clear that each of these calls acts on the same\nobject, and so even if you don't know the class and its methods very\nwell, you can understand that the second and third call are applied to\nx (and that all calls are made for their side-effects), and not to\nsomething else.\nI'd like to reserve chaining for operations that return new values,\nlike string processing operations:\ny = x.rstrip(\"\\n\").split(\":\").lower()\n\nThere are a few standard library modules that encourage chaining of\nside-effect calls (pstat comes to mind). There shouldn't be any new\nones; pstat slipped through my filter when it was weak.\n\n",
"I can't speak for the developers, but I find this behavior very intuitive.\nIf a method works on the original object and modifies it in-place, it doesn't return anything, because there is no new information - you obviously already have a reference to the (now mutated) object, so why return it again?\nIf, however, a method or function creates a new object, then of course it has to return it.\nSo l.reverse() returns nothing (because now the list has been reversed, but the identfier l still points to that list), but reversed(l) has to return the newly generated list because l still points to the old, unmodified list.\nEDIT: I just learned from another answer that this principle is called Command-Query separation.\n",
"One could argue that the signature itself makes it clear that the function mutates the list rather than returning a new one: if the function returned a list, its behavior would have been much less obvious.\n",
"If you were sent here after asking for help fixing your code:\nIn the future, please try to look for problems in the code yourself, by carefully studying what happens when the code runs. Rather than giving up because there is an error message, check the result of each calculation, and see where the code starts working differently from what you expect.\nIf you had code calling a method like .append or .sort on a list, you will notice that the return value is None, while the list is modified in place. Study the example carefully:\n>>> x = ['e', 'x', 'a', 'm', 'p', 'l', 'e']\n>>> y = x.sort()\n>>> print(y)\nNone\n>>> print(x)\n['a', 'e', 'e', 'l', 'm', 'p', 'x']\n\ny got the special None value, because that is what was returned. x changed, because the sort happened in place.\nIt works this way on purpose, so that code like x.sort().reverse() breaks. See the other answers to understand why the Python developers wanted it that way.\nTo fix the problem\nFirst, think carefully about the intent of the code. Should x change? Do we actually need a separate y?\nLet's consider .sort first. If x should change, then call x.sort() by itself, without assigning the result anywhere.\nIf a sorted copy is needed instead, use y = x.sorted(). See How can I get a sorted copy of a list? for details.\nFor other methods, we can get modified copies like so:\n.clear -> there is no point to this; a \"cleared copy\" of the list is just an empty list. Just use y = [].\n.append and .extend -> probably the simplest way is to use the + operator. To add multiple elements from a list l, use y = x + l rather than .extend. To add a single element e wrap it in a list first: y = x + [e]. Another way in 3.5 and up is to use unpacking: y = [*x, *l] for .extend, y = [*x, e] for .append. See also How to allow list append() method to return the new list for .append and How do I concatenate two lists in Python? for .extend.\n.reverse -> First, consider whether an actual copy is needed. The built-in reversed gives you an iterator that can be used to loop over the elements in reverse order. To make an actual copy, simply pass that iterator to list: y = list(reversed(x)). See How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)? for details.\n.remove -> Figure out the index of the element that will be removed (using .index), then use slicing to find the elements before and after that point and put them together. As a function:\ndef without(a_list, value):\n index = a_list.index(value)\n return a_list[:index] + a_list[index+1:]\n\n(We can translate .pop similarly to make a modified copy, though of course .pop actually returns an element from the list.)\nSee also A quick way to return list without a specific element in Python.\n(If you plan to remove multiple elements, strongly consider using a list comprehension (or filter) instead. It will be much simpler than any of the workarounds needed for removing items from the list while iterating over it. This way also naturally gives a modified copy.)\n\nFor any of the above, of course, we can also make a modified copy by explicitly making a copy and then using the in-place method on the copy. The most elegant approach will depend on the context and on personal taste.\n",
"As we know list in python is a mutable object and one of characteristics of mutable object is the ability to modify the state of this object without the need to assign its new state to a variable. we should demonstrate more about this topic to understand the root of this issue.\nAn object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created. Object mutability is one of the characteristics that makes Python a dynamically typed language.\nEvery object in python has three attributes:\n\nIdentity – This refers to the address that the object refers to in the computer’s memory.\nType – This refers to the kind of object that is created. For example integer, list, string etc.\nValue – This refers to the value stored by the object. For example str = \"a\".\n\nWhile ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.\nlet us discuss the below code step-by-step to depict what it means in Python:\nCreating a list which contains name of cities\ncities = ['London', 'New York', 'Chicago']\n\nPrinting the location of the object created in the memory address in hexadecimal format\nprint(hex(id(cities)))\n\nOutput [1]: 0x1691d7de8c8\n\nAdding a new city to the list cities\ncities.append('Delhi')\n\nPrinting the elements from the list cities, separated by a comma\nfor city in cities:\n print(city, end=', ')\n\nOutput [2]: London, New York, Chicago, Delhi\n\nPrinting the location of the object created in the memory address in hexadecimal format\nprint(hex(id(cities)))\n\nOutput [3]: 0x1691d7de8c8\n\nThe above example shows us that we were able to change the internal state of the object cities by adding one more city 'Delhi' to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name cities is a MUTABLE OBJECT.\nWhile the immutable object internal state can not be changed. For instance, consider the below code and associated error message with it, while trying to change the value of a Tuple at index 0\nCreating a Tuple with variable name foo\nfoo = (1, 2)\n\nChanging the index 0 value from 1 to 3\nfoo[0] = 3\n \nTypeError: 'tuple' object does not support item assignment \n\nWe can conclude from the examples why mutable object shouldn't return anything when executing operations on it because it's modifying the internal state of the object directly and there is no point in returning new modified object. unlike immutable object which should return new object of the modified state after executing operations on it.\n"
] |
[
33,
16,
5,
3,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0011205254_list_python.txt
|
Q:
How to check if a 2D list contains a list that partly contains another list
I'm trying to find out if my Tabu list (2D) contains a list that partly contains another list.
Like:
Tabu = [[1, 2, 3], [3, 2, 1, 0]]
Test = [3, 2, 1]
Test2 = [1, 3, 2]
Here Tabu contains a list: [3, 2, 1, 0] that contains [3, 2, 1], so Tabu contains Test, but doesn't contain Test2 as there are no lists in Tabu that contain [1, 3, 2] in this order.
Note: All values of Test must be in a sublist of Tabu to pass.
Changing the lists to sets is not an option. There are no repeating values in Test and only two seperate lists can contain the same value in Tabu.
Edit: More info and clarification
A:
you need to iterate through the Tabu and check if all element of the Test list are in the sublist of Tabu
>>> Tabu = [[1, 2, 3], [4, 5, 6, 0]]
>>> Test = [4, 5, 6]
>>>
>>> result = any(all(i in sublist for i in Test) for sublist in Tabu)
>>> result
True
>>>
|
How to check if a 2D list contains a list that partly contains another list
|
I'm trying to find out if my Tabu list (2D) contains a list that partly contains another list.
Like:
Tabu = [[1, 2, 3], [3, 2, 1, 0]]
Test = [3, 2, 1]
Test2 = [1, 3, 2]
Here Tabu contains a list: [3, 2, 1, 0] that contains [3, 2, 1], so Tabu contains Test, but doesn't contain Test2 as there are no lists in Tabu that contain [1, 3, 2] in this order.
Note: All values of Test must be in a sublist of Tabu to pass.
Changing the lists to sets is not an option. There are no repeating values in Test and only two seperate lists can contain the same value in Tabu.
Edit: More info and clarification
|
[
"you need to iterate through the Tabu and check if all element of the Test list are in the sublist of Tabu\n>>> Tabu = [[1, 2, 3], [4, 5, 6, 0]]\n>>> Test = [4, 5, 6]\n>>> \n>>> result = any(all(i in sublist for i in Test) for sublist in Tabu)\n>>> result\nTrue\n>>> \n\n"
] |
[
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0074512493_list_python.txt
|
Q:
Python Tornado TCPServer - TCPClient alternative to interface with other objects through Queues?
I have a Tornado TCPServer which is acting as a "bridge" between two Python programs on different computers that need to exchange data (streaming & files) and commands. There is only ever one client at a time. Since the TCPServer runs using IOLoop I have it in a separate thread to avoid blocking other server actions.
Commands are received as strings from reading the TCP connection and are put in a Queue that can be accessed in both the TCPServer thread and the outer Python thread. There is an additional Queue for sending data back to the TCPServer after a command is interpreted and executed in the outer Python thread. This arrangement is mirrored on the client side with its TCPClient as well. Each Queue is used as one-directional.
Example simplified flowchart:
My questions:
Queues are very limited in the sense that there is no relation between the request and the response (i.e. two requests submitted at once could get each-other's responses if one queue is used). Other than making a list of queues and routing commands/responses through them, are there good alternatives for parallel, cross-thread communication?
I would prefer not to reinvent the wheel and I imagine this is not a totally unique
use-case. Are there alternatives to this TCP-to-Queue routing?
A:
Adding a partial answer to address the potential cross-communication of requests and responses in one Queue:
class OnDemandQueue(Queue):
def __init__(self, *args, **kwargs):
super(OnDemandQueue, self).__init__(*args, **kwargs)
# Create and share new temporary queues as-needed via a single existing queue
def get_queue(self):
send = Queue()
receive = Queue()
# Remote reference
self.put_nowait([receive, send])
# Local reference
return [send, receive]
One or two instances of OnDemandQueue is/are shared across threads, and any time a new command-response pair is needed a new Queue pair is generated and shared via get_queue. This keeps everything nicely segregated and the pairs can be maintained as long as they are needed, then cleanly discarded.
In typical use a listener is needed to watch for new items in the shared OnDemandQueue, then determine what to do with the resulting Queue pair. While communication is bidirectional through the get_queue pair, the
OnDemandQueue itself is treated as unidirectional due to the listener, so two instances may be needed.
|
Python Tornado TCPServer - TCPClient alternative to interface with other objects through Queues?
|
I have a Tornado TCPServer which is acting as a "bridge" between two Python programs on different computers that need to exchange data (streaming & files) and commands. There is only ever one client at a time. Since the TCPServer runs using IOLoop I have it in a separate thread to avoid blocking other server actions.
Commands are received as strings from reading the TCP connection and are put in a Queue that can be accessed in both the TCPServer thread and the outer Python thread. There is an additional Queue for sending data back to the TCPServer after a command is interpreted and executed in the outer Python thread. This arrangement is mirrored on the client side with its TCPClient as well. Each Queue is used as one-directional.
Example simplified flowchart:
My questions:
Queues are very limited in the sense that there is no relation between the request and the response (i.e. two requests submitted at once could get each-other's responses if one queue is used). Other than making a list of queues and routing commands/responses through them, are there good alternatives for parallel, cross-thread communication?
I would prefer not to reinvent the wheel and I imagine this is not a totally unique
use-case. Are there alternatives to this TCP-to-Queue routing?
|
[
"Adding a partial answer to address the potential cross-communication of requests and responses in one Queue:\nclass OnDemandQueue(Queue):\n def __init__(self, *args, **kwargs):\n super(OnDemandQueue, self).__init__(*args, **kwargs)\n # Create and share new temporary queues as-needed via a single existing queue\n\n def get_queue(self):\n send = Queue()\n receive = Queue()\n # Remote reference\n self.put_nowait([receive, send])\n # Local reference\n return [send, receive]\n\nOne or two instances of OnDemandQueue is/are shared across threads, and any time a new command-response pair is needed a new Queue pair is generated and shared via get_queue. This keeps everything nicely segregated and the pairs can be maintained as long as they are needed, then cleanly discarded.\nIn typical use a listener is needed to watch for new items in the shared OnDemandQueue, then determine what to do with the resulting Queue pair. While communication is bidirectional through the get_queue pair, the\nOnDemandQueue itself is treated as unidirectional due to the listener, so two instances may be needed.\n"
] |
[
0
] |
[] |
[] |
[
"multithreading",
"python",
"tornado"
] |
stackoverflow_0074512019_multithreading_python_tornado.txt
|
Q:
python enums with attributes
Consider:
class Item:
def __init__(self, a, b):
self.a = a
self.b = b
class Items:
GREEN = Item('a', 'b')
BLUE = Item('c', 'd')
Is there a way to adapt the ideas for simple enums to this case? (see this question) Ideally, as in Java, I would like to cram it all into one class.
Java model:
enum EnumWithAttrs {
GREEN("a", "b"),
BLUE("c", "d");
EnumWithAttrs(String a, String b) {
this.a = a;
this.b = b;
}
private String a;
private String b;
/* accessors and other java noise */
}
A:
Python 3.4 has a new Enum data type (which has been backported as enum34 and enhanced as aenum1). Both enum34 and aenum2 easily support your use case:
aenum (Python 2/3)
import aenum
class EnumWithAttrs(aenum.AutoNumberEnum):
_init_ = 'a b'
GREEN = 'a', 'b'
BLUE = 'c', 'd'
enum34 (Python 2/3) or standard library enum (Python 3.4+)
import enum
class EnumWithAttrs(enum.Enum):
def __new__(cls, *args, **kwds):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
def __init__(self, a, b):
self.a = a
self.b = b
GREEN = 'a', 'b'
BLUE = 'c', 'd'
And in use:
>>> EnumWithAttrs.BLUE
<EnumWithAttrs.BLUE: 1>
>>> EnumWithAttrs.BLUE.a
'c'
1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.
2 aenum also supports NamedConstants and metaclass-based NamedTuples.
A:
Before Python 3.4 and the addition of the excellent enum module, a good choice would have been to use a namedtuple:
from collections import namedtuple
Item = namedtuple('abitem', ['a', 'b'])
class Items:
GREEN = Item('a', 'b')
BLUE = Item('c', 'd')
These days, any supported version of Python has enum, so please use that module. It gives you a lot more control over how each enum value is produced.
If you give each item a tuple of values, then these are passed to the __init__ method as separate (positional) arguments, which lets you set additional attributes on the enum value:
from enum import Enum
class Items(Enum):
GREEN = ('a', 'b')
BLUE = ('c', 'd')
def __init__(self, a, b):
self.a = a
self.b = b
This produces enum entries whose value is the tuple assigned to each name, as well as two attributes a and b:
>>> Items.GREEN, Items.BLUE
(<Items.GREEN: ('a', 'b')>, <Items.BLUE: ('c', 'd')>)
>>> Items.BLUE.a
'c'
>>> Items.BLUE.b
'd'
>>> Items(('a', 'b'))
<Items.GREEN: ('a', 'b')>
Note that you can look up each enum value by passing in the same tuple again.
If the first item should represent the value of each enum entry, use a __new__ method to set _value_:
from enum import Enum
class Items(Enum):
GREEN = ('a', 'b')
BLUE = ('c', 'd')
def __new__(cls, a, b):
entry = object.__new__(cls)
entry.a = entry._value_ = a # set the value, and the extra attribute
entry.b = b
return entry
def __repr__(self):
return f'<{type(self).__name__}.{self.name}: ({self.a!r}, {self.b!r})>'
I added a custom __repr__ as well, the default only includes self._value_. Now the value of each entry is defined by the first item in the tuple, and can be used to look up the enum entry:
>>> Items.GREEN, Items.BLUE
(<Items.GREEN: ('a', 'b')>, <Items.BLUE: ('c', 'd')>)
>>> Items.BLUE.a
'c'
>>> Items.BLUE.b
'd'
>>> Items('a')
<Items.GREEN: ('a', 'b')>
See the section on __init__ vs. __new__ in the documentation for further options.
A:
For Python 3:
class Status(Enum):
READY = "ready", "I'm ready to do whatever is needed"
ERROR = "error", "Something went wrong here"
def __new__(cls, *args, **kwds):
obj = object.__new__(cls)
obj._value_ = args[0]
return obj
# ignore the first param since it's already set by __new__
def __init__(self, _: str, description: str = None):
self._description_ = description
def __str__(self):
return self.value
# this makes sure that the description is read-only
@property
def description(self):
return self._description_
And you can use it as a standard enum or factory by type:
print(Status.READY)
# ready
print(Status.READY.description)
# I'm ready to do whatever is needed
print(Status("ready")) # this does not create a new object
# ready
A:
Here's another approach which I think is simpler than the others, but allows the most flexibility:
from collections import namedtuple
from enum import Enum
class Status(namedtuple('Status', 'name description'), Enum):
READY = 'ready', 'I am ready to do whatever is needed'
ERROR = 'error', 'Something went wrong here'
def __str__(self) -> str:
return self.name
It works as expected:
>>> str(Status.READY)
ready
>>> Status.READY
<Status.READY: Status(name='ready', description='I am ready to do whatever is needed')>
>>> Status.READY.description
'I am ready to do whatever is needed'
>>> Status.READY.value
Status(name='ready', description='I am ready to do whatever is needed')
Also you are able to retrieve the enum by name (Thanks @leoll2 for pointing this out). For example
>>> Status['READY']
<Status.READY: Status(name='ready', description='I am ready to do whatever is needed')>
You get the best of namedtuple and Enum.
A:
for small enums @property might work:
class WikiCfpEntry(Enum):
'''
possible supported storage modes
'''
EVENT = "Event"
SERIES = "Series"
@property
def urlPrefix(self):
baseUrl="http://www.wikicfp.com/cfp"
if self==WikiCfpEntry.EVENT:
url= f"{baseUrl}/servlet/event.showcfp?eventid="
elif self==WikiCfpEntry.SERIES:
url= f"{baseUrl}/program?id="
return url
A:
For keyword-based initialization of attributes, you might try data-enum, a more lightweight implementation of enum with cleaner syntax for some cases, including this one.
from data_enum import DataEnum
class Item(DataEnum):
data_attribute_names = ('a', 'b')
Item.GREEN = Item(a='a', b='b')
Item.BLUE = Item(a='c', b='d')
I should note that I am the author of data-enum, and built it specifically to address this use case.
A:
After searching a lot, I found these two working examples!
That's it my friends!
Codes...
from enum import Enum
class StatusInt(int, Enum):
READY = (0, "Ready to go!")
ERROR = (1, "Something wrong!")
def __new__(cls, value, description):
obj = int.__new__(cls, value)
obj._value_ = value
obj._description_ = description
return obj
@property
def description(self):
return self._description_
class StatusObj(Enum):
READY = (0, "Ready to go!")
ERROR = (1, "Something wrong!")
def __init__(self, value, description):
self._value_ = value
self._description_ = description
@property
def description(self):
return self._description_
print(str(StatusInt.READY == StatusInt.ERROR))
print(str(StatusInt.READY.value))
print(StatusInt.READY.description)
print(str(StatusObj.READY == StatusObj.ERROR))
print(str(StatusObj.READY.value))
print(StatusObj.READY.description)
Outputs...
False
0
Ready to go!
False
0
Ready to go!
[Ref(s).: https://docs.python.org/3/library/enum.html#when-to-use-new-vs-init , https://docs.python.org/3/library/enum.html#planet ]
A:
Inspired by some of the other answers, I found a way of including additional fields to an enum as 'transparently' as possible, overcoming some shortcomings of the other approaches. Everything works the same as if the additional fields weren't there.
The enum is immutable just like a tuple, the value of the enum is just as it would be without the additional fields, it works just like a normal enum with auto(), and selecting an enum by value works.
import enum
# Common base class for all enums you want to create with additional fields (you only need this once)
class EnumFI(enum.Enum):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls._values = []
def __new__(cls, *args, **kwargs):
value = args[0]
if isinstance(value, enum.auto):
if value.value == enum._auto_null:
value.value = cls._generate_next_value_(None, 1, len(cls.__members__), cls._values[:]) # Note: This just passes None for the key, which is generally okay
value = value.value
args = (value,) + args[1:]
cls._values.append(value)
instance = cls._member_type_.__new__(cls, *args, **kwargs)
instance._value_ = value
return instance
def __format__(self, format_spec):
return str.__format__(str(self), format_spec)
Then anywhere in the code you can just do:
from enum import auto
from collections import namedtuple
class Color(namedtuple('ColorTuple', 'id r g b'), EnumFI):
GREEN = auto(), 0, 255, 0
BLUE = auto(), 0, 0, 255
Example output:
In[4]: Color.GREEN
Out[4]: <Color.GREEN: 1>
In[5]: Color.GREEN.value
Out[5]: 1
In[6]: Color.GREEN.r
Out[6]: 0
In[7]: Color.GREEN.g
Out[7]: 255
In[8]: Color.GREEN.b
Out[8]: 0
In[9]: Color.GREEN.r = 8
Traceback (most recent call last):
File "/home/phil/anaconda3/envs/dl/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-9-914a059d9d3b>", line 1, in <module>
Color.GREEN.r = 8
AttributeError: can't set attribute
In[10]: Color(2)
Out[10]: <Color.BLUE: 2>
In[11]: Color['BLUE']
Out[11]: <Color.BLUE: 2>
A:
enum-properties provides an extension of the Enum base class that allows attributes on enum values and also allows symmetric mapping backwards from attribute values to their enumeration values.
Add properties to Python enumeration values with a simple declarative syntax. Enum Properties is a lightweight extension to Python's Enum class. Example:
from enum_properties import EnumProperties, p
from enum import auto
class Color(EnumProperties, p('rgb'), p('hex')):
# name value rgb hex
RED = auto(), (1, 0, 0), 'ff0000'
GREEN = auto(), (0, 1, 0), '00ff00'
BLUE = auto(), (0, 0, 1), '0000ff'
# the named p() values in the Enum's inheritance become properties on
# each value, matching the order in which they are specified
Color.RED.rgb == (1, 0, 0)
Color.GREEN.rgb == (0, 1, 0)
Color.BLUE.rgb == (0, 0, 1)
Color.RED.hex == 'ff0000'
Color.GREEN.hex == '00ff00'
Color.BLUE.hex == '0000ff'
Properties may also be symmetrically mapped to enumeration values, using s() values:
from enum_properties import EnumProperties, s
from enum import auto
class Color(EnumProperties, s('rgb'), s('hex', case_fold=True)):
RED = auto(), (1, 0, 0), 'ff0000'
GREEN = auto(), (0, 1, 0), '00ff00'
BLUE = auto(), (0, 0, 1), '0000ff'
# any named s() values in the Enum's inheritance become properties on
# each value, and the enumeration value may be instantiated from the
# property's value
Color((1, 0, 0)) == Color.RED
Color((0, 1, 0)) == Color.GREEN
Color((0, 0, 1)) == Color.BLUE
Color('ff0000') == Color.RED
Color('FF0000') == Color.RED # case_fold makes mapping case insensitive
Color('00ff00') == Color.GREEN
Color('00FF00') == Color.GREEN
Color('0000ff') == Color.BLUE
Color('0000FF') == Color.BLUE
Color.RED.hex == 'ff0000'
|
python enums with attributes
|
Consider:
class Item:
def __init__(self, a, b):
self.a = a
self.b = b
class Items:
GREEN = Item('a', 'b')
BLUE = Item('c', 'd')
Is there a way to adapt the ideas for simple enums to this case? (see this question) Ideally, as in Java, I would like to cram it all into one class.
Java model:
enum EnumWithAttrs {
GREEN("a", "b"),
BLUE("c", "d");
EnumWithAttrs(String a, String b) {
this.a = a;
this.b = b;
}
private String a;
private String b;
/* accessors and other java noise */
}
|
[
"Python 3.4 has a new Enum data type (which has been backported as enum34 and enhanced as aenum1). Both enum34 and aenum2 easily support your use case:\n\naenum (Python 2/3)\n import aenum\n class EnumWithAttrs(aenum.AutoNumberEnum):\n _init_ = 'a b'\n GREEN = 'a', 'b'\n BLUE = 'c', 'd'\n\n\nenum34 (Python 2/3) or standard library enum (Python 3.4+)\n import enum\n class EnumWithAttrs(enum.Enum):\n\n def __new__(cls, *args, **kwds):\n value = len(cls.__members__) + 1\n obj = object.__new__(cls)\n obj._value_ = value\n return obj\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n GREEN = 'a', 'b'\n BLUE = 'c', 'd'\n\n\n\nAnd in use:\n>>> EnumWithAttrs.BLUE\n<EnumWithAttrs.BLUE: 1>\n\n>>> EnumWithAttrs.BLUE.a\n'c'\n\n\n1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.\n2 aenum also supports NamedConstants and metaclass-based NamedTuples.\n",
"Before Python 3.4 and the addition of the excellent enum module, a good choice would have been to use a namedtuple:\nfrom collections import namedtuple\n\nItem = namedtuple('abitem', ['a', 'b'])\n\nclass Items:\n GREEN = Item('a', 'b')\n BLUE = Item('c', 'd')\n\nThese days, any supported version of Python has enum, so please use that module. It gives you a lot more control over how each enum value is produced.\nIf you give each item a tuple of values, then these are passed to the __init__ method as separate (positional) arguments, which lets you set additional attributes on the enum value:\nfrom enum import Enum\n\nclass Items(Enum):\n GREEN = ('a', 'b')\n BLUE = ('c', 'd')\n\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\nThis produces enum entries whose value is the tuple assigned to each name, as well as two attributes a and b:\n>>> Items.GREEN, Items.BLUE\n(<Items.GREEN: ('a', 'b')>, <Items.BLUE: ('c', 'd')>)\n>>> Items.BLUE.a\n'c'\n>>> Items.BLUE.b\n'd'\n>>> Items(('a', 'b'))\n<Items.GREEN: ('a', 'b')>\n\nNote that you can look up each enum value by passing in the same tuple again.\nIf the first item should represent the value of each enum entry, use a __new__ method to set _value_:\nfrom enum import Enum\n\nclass Items(Enum):\n GREEN = ('a', 'b')\n BLUE = ('c', 'd')\n\n def __new__(cls, a, b):\n entry = object.__new__(cls) \n entry.a = entry._value_ = a # set the value, and the extra attribute\n entry.b = b\n return entry\n\n def __repr__(self):\n return f'<{type(self).__name__}.{self.name}: ({self.a!r}, {self.b!r})>'\n\nI added a custom __repr__ as well, the default only includes self._value_. Now the value of each entry is defined by the first item in the tuple, and can be used to look up the enum entry:\n>>> Items.GREEN, Items.BLUE\n(<Items.GREEN: ('a', 'b')>, <Items.BLUE: ('c', 'd')>)\n>>> Items.BLUE.a\n'c'\n>>> Items.BLUE.b\n'd'\n>>> Items('a')\n<Items.GREEN: ('a', 'b')>\n\nSee the section on __init__ vs. __new__ in the documentation for further options.\n",
"For Python 3:\nclass Status(Enum):\n READY = \"ready\", \"I'm ready to do whatever is needed\"\n ERROR = \"error\", \"Something went wrong here\"\n\n def __new__(cls, *args, **kwds):\n obj = object.__new__(cls)\n obj._value_ = args[0]\n return obj\n\n # ignore the first param since it's already set by __new__\n def __init__(self, _: str, description: str = None):\n self._description_ = description\n\n def __str__(self):\n return self.value\n\n # this makes sure that the description is read-only\n @property\n def description(self):\n return self._description_\n\nAnd you can use it as a standard enum or factory by type:\nprint(Status.READY)\n# ready\nprint(Status.READY.description)\n# I'm ready to do whatever is needed\nprint(Status(\"ready\")) # this does not create a new object\n# ready\n\n",
"Here's another approach which I think is simpler than the others, but allows the most flexibility:\nfrom collections import namedtuple\nfrom enum import Enum\n\nclass Status(namedtuple('Status', 'name description'), Enum):\n READY = 'ready', 'I am ready to do whatever is needed'\n ERROR = 'error', 'Something went wrong here'\n\n def __str__(self) -> str:\n return self.name\n\nIt works as expected:\n>>> str(Status.READY)\nready\n\n>>> Status.READY\n<Status.READY: Status(name='ready', description='I am ready to do whatever is needed')>\n\n>>> Status.READY.description\n'I am ready to do whatever is needed'\n\n>>> Status.READY.value\nStatus(name='ready', description='I am ready to do whatever is needed')\n\nAlso you are able to retrieve the enum by name (Thanks @leoll2 for pointing this out). For example\n>>> Status['READY']\n<Status.READY: Status(name='ready', description='I am ready to do whatever is needed')>\n\nYou get the best of namedtuple and Enum.\n",
"for small enums @property might work:\nclass WikiCfpEntry(Enum):\n '''\n possible supported storage modes\n '''\n EVENT = \"Event\" \n SERIES = \"Series\"\n \n @property\n def urlPrefix(self):\n baseUrl=\"http://www.wikicfp.com/cfp\"\n if self==WikiCfpEntry.EVENT:\n url= f\"{baseUrl}/servlet/event.showcfp?eventid=\"\n elif self==WikiCfpEntry.SERIES:\n url= f\"{baseUrl}/program?id=\"\n return url\n\n",
"For keyword-based initialization of attributes, you might try data-enum, a more lightweight implementation of enum with cleaner syntax for some cases, including this one.\nfrom data_enum import DataEnum\n\nclass Item(DataEnum):\n data_attribute_names = ('a', 'b')\n\nItem.GREEN = Item(a='a', b='b')\nItem.BLUE = Item(a='c', b='d')\n\nI should note that I am the author of data-enum, and built it specifically to address this use case.\n",
"After searching a lot, I found these two working examples! \nThat's it my friends! \nCodes...\nfrom enum import Enum\n\n\nclass StatusInt(int, Enum):\n READY = (0, \"Ready to go!\")\n ERROR = (1, \"Something wrong!\")\n\n def __new__(cls, value, description):\n obj = int.__new__(cls, value)\n obj._value_ = value\n obj._description_ = description\n return obj\n\n @property\n def description(self):\n return self._description_\n\n\nclass StatusObj(Enum):\n READY = (0, \"Ready to go!\")\n ERROR = (1, \"Something wrong!\")\n\n def __init__(self, value, description):\n self._value_ = value\n self._description_ = description\n\n @property\n def description(self):\n return self._description_\n\n\nprint(str(StatusInt.READY == StatusInt.ERROR))\nprint(str(StatusInt.READY.value))\nprint(StatusInt.READY.description)\n\nprint(str(StatusObj.READY == StatusObj.ERROR))\nprint(str(StatusObj.READY.value))\nprint(StatusObj.READY.description)\n\nOutputs...\nFalse\n0\nReady to go!\nFalse\n0\nReady to go!\n\n[Ref(s).: https://docs.python.org/3/library/enum.html#when-to-use-new-vs-init , https://docs.python.org/3/library/enum.html#planet ]\n",
"Inspired by some of the other answers, I found a way of including additional fields to an enum as 'transparently' as possible, overcoming some shortcomings of the other approaches. Everything works the same as if the additional fields weren't there.\nThe enum is immutable just like a tuple, the value of the enum is just as it would be without the additional fields, it works just like a normal enum with auto(), and selecting an enum by value works.\nimport enum\n\n# Common base class for all enums you want to create with additional fields (you only need this once)\nclass EnumFI(enum.Enum):\n\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls._values = []\n\n def __new__(cls, *args, **kwargs):\n value = args[0]\n if isinstance(value, enum.auto):\n if value.value == enum._auto_null:\n value.value = cls._generate_next_value_(None, 1, len(cls.__members__), cls._values[:]) # Note: This just passes None for the key, which is generally okay\n value = value.value\n args = (value,) + args[1:]\n cls._values.append(value)\n instance = cls._member_type_.__new__(cls, *args, **kwargs)\n instance._value_ = value\n return instance\n\n def __format__(self, format_spec):\n return str.__format__(str(self), format_spec)\n\nThen anywhere in the code you can just do:\nfrom enum import auto\nfrom collections import namedtuple\n\nclass Color(namedtuple('ColorTuple', 'id r g b'), EnumFI):\n GREEN = auto(), 0, 255, 0\n BLUE = auto(), 0, 0, 255\n\nExample output:\nIn[4]: Color.GREEN\nOut[4]: <Color.GREEN: 1>\n\nIn[5]: Color.GREEN.value\nOut[5]: 1\n\nIn[6]: Color.GREEN.r\nOut[6]: 0\n\nIn[7]: Color.GREEN.g\nOut[7]: 255\n\nIn[8]: Color.GREEN.b\nOut[8]: 0\n\nIn[9]: Color.GREEN.r = 8\nTraceback (most recent call last):\n File \"/home/phil/anaconda3/envs/dl/lib/python3.6/site-packages/IPython/core/interactiveshell.py\", line 3326, in run_code\n exec(code_obj, self.user_global_ns, self.user_ns)\n File \"<ipython-input-9-914a059d9d3b>\", line 1, in <module>\n Color.GREEN.r = 8\nAttributeError: can't set attribute\n\nIn[10]: Color(2)\nOut[10]: <Color.BLUE: 2>\n\nIn[11]: Color['BLUE']\nOut[11]: <Color.BLUE: 2>\n\n",
"enum-properties provides an extension of the Enum base class that allows attributes on enum values and also allows symmetric mapping backwards from attribute values to their enumeration values.\nAdd properties to Python enumeration values with a simple declarative syntax. Enum Properties is a lightweight extension to Python's Enum class. Example:\nfrom enum_properties import EnumProperties, p\nfrom enum import auto\n\nclass Color(EnumProperties, p('rgb'), p('hex')):\n\n # name value rgb hex\n RED = auto(), (1, 0, 0), 'ff0000'\n GREEN = auto(), (0, 1, 0), '00ff00'\n BLUE = auto(), (0, 0, 1), '0000ff'\n\n# the named p() values in the Enum's inheritance become properties on\n# each value, matching the order in which they are specified\n\nColor.RED.rgb == (1, 0, 0)\nColor.GREEN.rgb == (0, 1, 0)\nColor.BLUE.rgb == (0, 0, 1)\n\nColor.RED.hex == 'ff0000'\nColor.GREEN.hex == '00ff00'\nColor.BLUE.hex == '0000ff'\n\nProperties may also be symmetrically mapped to enumeration values, using s() values:\nfrom enum_properties import EnumProperties, s\nfrom enum import auto\n\nclass Color(EnumProperties, s('rgb'), s('hex', case_fold=True)):\n\n RED = auto(), (1, 0, 0), 'ff0000'\n GREEN = auto(), (0, 1, 0), '00ff00'\n BLUE = auto(), (0, 0, 1), '0000ff'\n\n# any named s() values in the Enum's inheritance become properties on\n# each value, and the enumeration value may be instantiated from the\n# property's value\n\nColor((1, 0, 0)) == Color.RED\nColor((0, 1, 0)) == Color.GREEN\nColor((0, 0, 1)) == Color.BLUE\n\nColor('ff0000') == Color.RED\nColor('FF0000') == Color.RED # case_fold makes mapping case insensitive\nColor('00ff00') == Color.GREEN\nColor('00FF00') == Color.GREEN\nColor('0000ff') == Color.BLUE\nColor('0000FF') == Color.BLUE\n\nColor.RED.hex == 'ff0000'\n\n"
] |
[
51,
36,
35,
24,
2,
2,
2,
1,
0
] |
[] |
[] |
[
"enums",
"python"
] |
stackoverflow_0012680080_enums_python.txt
|
Q:
Combine elements of a list of lists into a string
I have to combine these 2 lists:
dots = [['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.']]
spaces = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
I want every dot separeted by a space and turn them into string just like this:
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
I wrote this code but it only work for the first line:
lists = [a for b in zip(dots[0], spaces[0]) for a in b]
line = ''.join(liste)
I wanted to know how to loop in for every other sublist in these two lists.
A:
You know how to use zip to simultaneously iterate over two lists, so do that and create a list of strings containing a dot and space for each "row":
lines = [
"".join(
dot + space
for dot, space in zip(row_dots, row_spaces)
)
for row_dots, row_spaces in zip(dots, spaces)
]
Then join the individual lines using the newline character '\n'.
output = "\n".join(lines)
print(output)
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
Of course, you can combine both into a single statement so that you don't need to create the list of lines:
output = "\n".join(
"".join(
dot + space
for dot, space in zip(row_dots, row_spaces)
)
for row_dots, row_spaces in zip(dots, spaces)
)
A:
You solved your problem for list, last thing you need is to iterate over every list in dots and spaces
result = []
for i in range(len(dots)):
lists = [a for b in zip(dots[i], spaces[i]) for a in b]
line = ''.join(lists)
result.append(line)
Or just put it into your list comprehesion:
lists = [a for i in range(len(dots)) for b in zip(dots[i], spaces[i]) for a in b]
line = "".join(lists)
|
Combine elements of a list of lists into a string
|
I have to combine these 2 lists:
dots = [['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.']]
spaces = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
I want every dot separeted by a space and turn them into string just like this:
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
I wrote this code but it only work for the first line:
lists = [a for b in zip(dots[0], spaces[0]) for a in b]
line = ''.join(liste)
I wanted to know how to loop in for every other sublist in these two lists.
|
[
"You know how to use zip to simultaneously iterate over two lists, so do that and create a list of strings containing a dot and space for each \"row\":\nlines = [\n \"\".join(\n dot + space \n for dot, space in zip(row_dots, row_spaces)\n )\n for row_dots, row_spaces in zip(dots, spaces) \n ]\n\nThen join the individual lines using the newline character '\\n'.\noutput = \"\\n\".join(lines)\nprint(output)\n\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n. . . . . . . . .\n\nOf course, you can combine both into a single statement so that you don't need to create the list of lines:\noutput = \"\\n\".join(\n \"\".join(\n dot + space \n for dot, space in zip(row_dots, row_spaces)\n )\n for row_dots, row_spaces in zip(dots, spaces) \n )\n\n",
"You solved your problem for list, last thing you need is to iterate over every list in dots and spaces\nresult = []\nfor i in range(len(dots)):\n lists = [a for b in zip(dots[i], spaces[i]) for a in b]\n line = ''.join(lists)\n result.append(line)\n\nOr just put it into your list comprehesion:\nlists = [a for i in range(len(dots)) for b in zip(dots[i], spaces[i]) for a in b]\nline = \"\".join(lists)\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"list",
"list_comprehension",
"python"
] |
stackoverflow_0074512509_list_list_comprehension_python.txt
|
Q:
FIFO function - manual approach
Python novice here. I am working on an assignment that has me a bit stumped.
The goal is set up a simple FIFO system, without using any imported libraries.
My attempt so far is incorrect and I am looking for some suggestions on how to fix it.
Attempt:
requests = [4, 32, 5, 8, 7, 4, 8] # Will be any random integer inputted by user, provided this list as an example
cache = []
def fifo():
for page in requests:
if page not in cache:
print(page, "miss")
cache.append(page) # This isn't right but not sure where to add?
if page in cache:
print(page, "hit")
cache.remove(page) # If a page is already in the cache, it doesn't need to be added again - not sure if this is correct either?
if len(cache) > 4: # max size of cache = 4
cache.pop(0) # Removes first indexed item until cache = 4 elements
print(cache)
return
# Each page should be printed as a hit/miss if included/not included in the cache
# Ignoring hits/miss being printed, the required output = print(cache) = [32, 5, 7, 8]
# i.e. the most recent 4 requests, previously requested pages (e.g. 4) shouldn't be included
How should I go about correcting the above? Open to alternative suggestions as I appreciate the above is likely far away from the optimal solution.
Thanks
A:
Given the text in the comments at the bottom of your code, it would appear that this is closer to what is required:
def f(requests, cache):
for page in requests:
if page in cache:
cache.remove(page)
print(page, "hit")
else:
print(page, "miss")
if len(cache) > 3:
cache.pop(0)
cache.append(page)
requests = [4, 32, 5, 8, 7, 4, 8]
cache = []
f(requests, cache)
print(cache)
If would make a bit more sense for the function to operate on individual 'pages' though (also showing an approach using a global cache):
cache = []
def f(page):
global cache
if page in cache:
print(page, "hit")
cache.remove(page)
else:
print(page, "miss")
if len(cache) > 3:
cache.pop(0)
cache.append(page)
for page in [4, 32, 5, 8, 7, 4, 8]:
f(page)
print(cache)
However, note that both these solutions show a different outcome than the question: [5, 7, 4, 8] instead of [32, 5, 7, 8].
The question seems to get the answer wrong itself, unless the actual maximum cache size isn't 4, but 5. Consider this: how can the cache still contain 4, when it most recently got 32, 5, 8, and 7 and its size would be 4? So, when 4 comes around again, it has no memory of it and should update to [5, 7, 4, 8]. Where are you getting this assignment?
Also note that I wouldn't want to recommend using a global variable as in the second solution - however, all this seems to be a step up on the way to writing a Cache class of sorts, which would make the cache a variable internal to the class or object, instead of a global. Such a class could look like this:
class Cache:
def __init__(self, size=4):
self._size = size
self._cache = []
def hit(self, page):
if (result := (page in self._cache)):
self._cache.remove(page)
if self._cache.__len__() == self._size:
self._cache.pop(0)
self._cache.append(page)
return result
def __str__(self):
return str(self._cache)
c = Cache(4)
for p in [4, 32, 5, 8, 7, 4, 8]:
if c.hit(p):
print('hit', p)
else:
print('miss', p)
print(c)
|
FIFO function - manual approach
|
Python novice here. I am working on an assignment that has me a bit stumped.
The goal is set up a simple FIFO system, without using any imported libraries.
My attempt so far is incorrect and I am looking for some suggestions on how to fix it.
Attempt:
requests = [4, 32, 5, 8, 7, 4, 8] # Will be any random integer inputted by user, provided this list as an example
cache = []
def fifo():
for page in requests:
if page not in cache:
print(page, "miss")
cache.append(page) # This isn't right but not sure where to add?
if page in cache:
print(page, "hit")
cache.remove(page) # If a page is already in the cache, it doesn't need to be added again - not sure if this is correct either?
if len(cache) > 4: # max size of cache = 4
cache.pop(0) # Removes first indexed item until cache = 4 elements
print(cache)
return
# Each page should be printed as a hit/miss if included/not included in the cache
# Ignoring hits/miss being printed, the required output = print(cache) = [32, 5, 7, 8]
# i.e. the most recent 4 requests, previously requested pages (e.g. 4) shouldn't be included
How should I go about correcting the above? Open to alternative suggestions as I appreciate the above is likely far away from the optimal solution.
Thanks
|
[
"Given the text in the comments at the bottom of your code, it would appear that this is closer to what is required:\ndef f(requests, cache):\n for page in requests:\n if page in cache:\n cache.remove(page)\n print(page, \"hit\")\n else:\n print(page, \"miss\")\n if len(cache) > 3:\n cache.pop(0)\n cache.append(page)\n\n\nrequests = [4, 32, 5, 8, 7, 4, 8]\ncache = []\nf(requests, cache)\nprint(cache)\n\nIf would make a bit more sense for the function to operate on individual 'pages' though (also showing an approach using a global cache):\ncache = []\ndef f(page):\n global cache\n if page in cache:\n print(page, \"hit\")\n cache.remove(page)\n else:\n print(page, \"miss\")\n if len(cache) > 3:\n cache.pop(0)\n cache.append(page)\n\n\nfor page in [4, 32, 5, 8, 7, 4, 8]:\n f(page)\n\n\nprint(cache)\n\nHowever, note that both these solutions show a different outcome than the question: [5, 7, 4, 8] instead of [32, 5, 7, 8].\nThe question seems to get the answer wrong itself, unless the actual maximum cache size isn't 4, but 5. Consider this: how can the cache still contain 4, when it most recently got 32, 5, 8, and 7 and its size would be 4? So, when 4 comes around again, it has no memory of it and should update to [5, 7, 4, 8]. Where are you getting this assignment?\nAlso note that I wouldn't want to recommend using a global variable as in the second solution - however, all this seems to be a step up on the way to writing a Cache class of sorts, which would make the cache a variable internal to the class or object, instead of a global. Such a class could look like this:\nclass Cache:\n def __init__(self, size=4):\n self._size = size\n self._cache = []\n\n def hit(self, page):\n if (result := (page in self._cache)):\n self._cache.remove(page)\n if self._cache.__len__() == self._size:\n self._cache.pop(0)\n self._cache.append(page)\n return result\n\n def __str__(self):\n return str(self._cache)\n\n\nc = Cache(4)\nfor p in [4, 32, 5, 8, 7, 4, 8]:\n if c.hit(p):\n print('hit', p)\n else:\n print('miss', p)\nprint(c)\n\n"
] |
[
0
] |
[] |
[] |
[
"fifo",
"list",
"python"
] |
stackoverflow_0074512448_fifo_list_python.txt
|
Q:
Applying Functions in Python
I am an R User that is trying to learn more about Python.
I found this Python library that I would like to use for address parsing: https://github.com/zehengl/ez-address-parser
I was able to try an example over here:
from ez_address_parser import AddressParser
ap = AddressParser()
result = ap.parse("290 Bremner Blvd, Toronto, ON M5V 3L9")
print(results)
[('290', 'StreetNumber'), ('Bremner', 'StreetName'), ('Blvd', 'StreetType'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('M5V', 'PostalCode'), ('3L9', 'PostalCode')]
I have the following file that I imported:
df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')
name address
1 name1 290 Bremner Blvd, Toronto, ON M5V 3L9
2 name2 291 Bremner Blvd, Toronto, ON M5V 3L9
3 name3 292 Bremner Blvd, Toronto, ON M5V 3L9
I tried to apply the above function and export the file:
df['Address_Parse'] = df['ADDRESS'].apply(ap.parse)
df = pd.DataFrame(df)
df.to_csv(r'C:/Users/me/OneDrive/Documents/python_file.csv', index=False, header=True)
This seems to have worked - but everything appears to be in one line!
[('290', 'StreetNumber'), ('Bremner', 'StreetName'), ('Blvd', 'StreetType'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('M5V', 'PostalCode'), ('3L9', 'PostalCode')]
Is there a way in Python to make each of these "elements" (e.g. StreetNumber, StreetName, etc.) into a separate column?
Thank you!
A:
Define a custom function that returns a Series and join the output:
def parse(x):
return pd.Series({k:v for v,k in ap.parse(x)})
out = df.join(df['ADDRESS'].apply(parse))
print(out)
A:
If you use pd.DataFrame.apply, Then you don't have to remember to change it into a series!
But rather can use axis=1 and result_type='expand'
Given:
# df
name address
0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9
Doing:
def parse_address(row):
return {k:v for v,k in ap.parse(row.address)}
df = df.join(df.apply(parse_address, axis=1, result_type='expand'))
# OR Something like this would also work:
def parse_address(row):
return [x[0] for x in ap.parse(row.address)]
new_cols = [
'StreetNumber',
'StreetName',
'StreetType',
'Municipality',
'Province',
'PostalCode',
'PostalCode'
]
df[new_cols] = df.apply(parse_address, axis=1, result_type='expand')
Outputs:
# Method 1
name address Municipality PostalCode Province StreetName StreetNumber StreetType
0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9 Toronto 3L9 ON Bremner 290 Blvd
# Method 2
name address StreetNumber StreetName StreetType Municipality Province PostalCode
0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9 290 Bremner Blvd Toronto ON 3L9
As for dictionary comprehension:
# This:
out = {k:v for v,k in [('a', 'b')]}
# Is like writing this:
out = {}
for v, k in [('a', 'b')]:
out[k] = v
# Both result in:
{'b': 'a'}
|
Applying Functions in Python
|
I am an R User that is trying to learn more about Python.
I found this Python library that I would like to use for address parsing: https://github.com/zehengl/ez-address-parser
I was able to try an example over here:
from ez_address_parser import AddressParser
ap = AddressParser()
result = ap.parse("290 Bremner Blvd, Toronto, ON M5V 3L9")
print(results)
[('290', 'StreetNumber'), ('Bremner', 'StreetName'), ('Blvd', 'StreetType'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('M5V', 'PostalCode'), ('3L9', 'PostalCode')]
I have the following file that I imported:
df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv', encoding='latin-1')
name address
1 name1 290 Bremner Blvd, Toronto, ON M5V 3L9
2 name2 291 Bremner Blvd, Toronto, ON M5V 3L9
3 name3 292 Bremner Blvd, Toronto, ON M5V 3L9
I tried to apply the above function and export the file:
df['Address_Parse'] = df['ADDRESS'].apply(ap.parse)
df = pd.DataFrame(df)
df.to_csv(r'C:/Users/me/OneDrive/Documents/python_file.csv', index=False, header=True)
This seems to have worked - but everything appears to be in one line!
[('290', 'StreetNumber'), ('Bremner', 'StreetName'), ('Blvd', 'StreetType'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('M5V', 'PostalCode'), ('3L9', 'PostalCode')]
Is there a way in Python to make each of these "elements" (e.g. StreetNumber, StreetName, etc.) into a separate column?
Thank you!
|
[
"Define a custom function that returns a Series and join the output:\ndef parse(x):\n return pd.Series({k:v for v,k in ap.parse(x)})\n\nout = df.join(df['ADDRESS'].apply(parse))\n\nprint(out)\n\n",
"If you use pd.DataFrame.apply, Then you don't have to remember to change it into a series!\nBut rather can use axis=1 and result_type='expand'\nGiven:\n# df\n name address\n0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9\n\nDoing:\ndef parse_address(row):\n return {k:v for v,k in ap.parse(row.address)}\n\ndf = df.join(df.apply(parse_address, axis=1, result_type='expand'))\n\n# OR Something like this would also work:\n\ndef parse_address(row):\n return [x[0] for x in ap.parse(row.address)]\n\nnew_cols = [\n 'StreetNumber', \n 'StreetName',\n 'StreetType',\n 'Municipality',\n 'Province',\n 'PostalCode',\n 'PostalCode'\n]\n\ndf[new_cols] = df.apply(parse_address, axis=1, result_type='expand')\n\nOutputs:\n# Method 1\n name address Municipality PostalCode Province StreetName StreetNumber StreetType\n0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9 Toronto 3L9 ON Bremner 290 Blvd\n\n\n# Method 2\n name address StreetNumber StreetName StreetType Municipality Province PostalCode\n0 name1 290 Bremner Blvd, Toronto, ON M5V 3L9 290 Bremner Blvd Toronto ON 3L9\n\n\nAs for dictionary comprehension:\n# This:\nout = {k:v for v,k in [('a', 'b')]}\n\n# Is like writing this:\n\nout = {}\nfor v, k in [('a', 'b')]:\n out[k] = v\n\n# Both result in:\n{'b': 'a'}\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"data_manipulation",
"pandas",
"python"
] |
stackoverflow_0074512363_data_manipulation_pandas_python.txt
|
Q:
How to calculate percentage and average of test scores in a 2D list without using libraries like pandas or numpy
I have a csv data of a test scores. The current program is able to read this data into a 2D list with the test out of marks. I later created a function to remove test out of row so only the student's marks can be displayed. I'm now struggling to write a function which can print the scores so that each student's percentage appears on a separate line of output.
My code so far
def getData():
with open("testscores.csv","r") as file:
lineArray = file.read().splitlines()
matrix = []
for line in lineArray:
matrix.append(line.split(","))
return matrix
def fullScores(matrix):
matrix.pop(0)
return matrix
def printscores(matrix):
for counter in matrix:
for values in counter:
print(values, end= " ")
print()
matrix = getData()
matrix = fullScores(matrix)
print()
printscores(matrix)
output
Bob 10 9 7 8 10 9 9 9 10 8 8 10 9 9
Sue 8 8 8 9 4 8 9 7 8 3 10 10 7 9
Jan 6 6 0 5 7 9 4 7 8 5 7 1 5 9
Sam 8 8 8 7 7 7 9 9 9 9 8 9 10 8
Tom 9 9 9 9 9 9 9 9 9 10 9 9 9 9
expected output
Bob 100% 90% 70% 80% 100% 90% 90% 90% 100% 80% 80% 100% 90% 90% Average = 89%
Sue 80% 80% 80% 90% 40% 80% 90% 70% 80% 30% 100% 100% 70% 90% Average = 77%
...
csv data
Testoutof,10,11,12,11,10,11,9,10,10,11,10,12,10,9
Bob,10,9,7,8,10,9,9,9,10,8,8,10,9,9
Sue,8,8,8,9,4,8,9,7,8,3,10,10,7,9
Jan,6,6,0,5,7,9,4,7,8,5,7,1,5,9
Sam,8,8,8,7,7,7,9,9,9,9,8,9,10,8
Tom,9,9,9,9,9,9,9,9,9,10,9,9,9,9
A:
Of course, there are many ways to do this, but here is one possible solution. I used only Lists and Tuple. Using dictionaries you would have a more elegant way accessing data.
students = []
reference_scores = []
def get_data():
with open("./data/testscores.csv", "r") as file:
lineArray = file.read().splitlines()
for line in lineArray:
raw_data = line.split(",")
name = raw_data[0]
scores = []
percentages = []
average_percentage = 0
if name != 'Testoutof':
scores = raw_data[1:]
for index, score in enumerate(scores):
percentage = get_percentage(int(score), int(reference_scores[index]))
average_percentage += percentage
percentages.append(percentage)
average_percentage //= len(scores)
students.append( (name, percentages, average_percentage) )
else:
reference_scores = raw_data[1:]
return students
def get_percentage(score, reference):
return (score * 100) // reference
def print_scores(data):
for obj in data:
score_string = ''
for score in obj[1]:
score_string += f'{score}% '
print(f'{obj[0]} {score_string} Average = {obj[2]}')
students = get_data()
print_scores(students)
# Output
Bob 100% 81% 58% 72% 100% 81% 100% 90% 100% 72% 80% 83% 90% 100% Average = 86
Sue 80% 72% 66% 81% 40% 72% 100% 70% 80% 27% 100% 83% 70% 100% Average = 74
Jan 60% 54% 0% 45% 70% 81% 44% 70% 80% 45% 70% 8% 50% 100% Average = 55
Sam 80% 72% 66% 63% 70% 63% 100% 90% 90% 81% 80% 75% 100% 88% Average = 79
Tom 90% 81% 75% 81% 90% 81% 100% 90% 90% 90% 90% 75% 90% 100% Average = 87
A:
Using list comprehension can give you the same result, without any function definition:
file=open("testscores.csv","r")
matrix=[line.strip().split(",") for line in file.readlines()[1:]]
for row in matrix:
data=[int(i)*10 for i in row[1:]]
print(row[0], "% ".join(map(str, data))+"%", "Average =", sum(data)//len(data),"%")
Output:
Bob 100% 90% 70% 80% 100% 90% 90% 90% 100% 80% 80% 100% 90% 90% Average = 89 %
Sue 80% 80% 80% 90% 40% 80% 90% 70% 80% 30% 100% 100% 70% 90% Average = 77 %
Jan 60% 60% 0% 50% 70% 90% 40% 70% 80% 50% 70% 10% 50% 90% Average = 56 %
Sam 80% 80% 80% 70% 70% 70% 90% 90% 90% 90% 80% 90% 100% 80% Average = 82 %
Tom 90% 90% 90% 90% 90% 90% 90% 90% 90% 100% 90% 90% 90% 90% Average = 90 %
|
How to calculate percentage and average of test scores in a 2D list without using libraries like pandas or numpy
|
I have a csv data of a test scores. The current program is able to read this data into a 2D list with the test out of marks. I later created a function to remove test out of row so only the student's marks can be displayed. I'm now struggling to write a function which can print the scores so that each student's percentage appears on a separate line of output.
My code so far
def getData():
with open("testscores.csv","r") as file:
lineArray = file.read().splitlines()
matrix = []
for line in lineArray:
matrix.append(line.split(","))
return matrix
def fullScores(matrix):
matrix.pop(0)
return matrix
def printscores(matrix):
for counter in matrix:
for values in counter:
print(values, end= " ")
print()
matrix = getData()
matrix = fullScores(matrix)
print()
printscores(matrix)
output
Bob 10 9 7 8 10 9 9 9 10 8 8 10 9 9
Sue 8 8 8 9 4 8 9 7 8 3 10 10 7 9
Jan 6 6 0 5 7 9 4 7 8 5 7 1 5 9
Sam 8 8 8 7 7 7 9 9 9 9 8 9 10 8
Tom 9 9 9 9 9 9 9 9 9 10 9 9 9 9
expected output
Bob 100% 90% 70% 80% 100% 90% 90% 90% 100% 80% 80% 100% 90% 90% Average = 89%
Sue 80% 80% 80% 90% 40% 80% 90% 70% 80% 30% 100% 100% 70% 90% Average = 77%
...
csv data
Testoutof,10,11,12,11,10,11,9,10,10,11,10,12,10,9
Bob,10,9,7,8,10,9,9,9,10,8,8,10,9,9
Sue,8,8,8,9,4,8,9,7,8,3,10,10,7,9
Jan,6,6,0,5,7,9,4,7,8,5,7,1,5,9
Sam,8,8,8,7,7,7,9,9,9,9,8,9,10,8
Tom,9,9,9,9,9,9,9,9,9,10,9,9,9,9
|
[
"Of course, there are many ways to do this, but here is one possible solution. I used only Lists and Tuple. Using dictionaries you would have a more elegant way accessing data.\nstudents = []\nreference_scores = []\n\ndef get_data():\n with open(\"./data/testscores.csv\", \"r\") as file:\n lineArray = file.read().splitlines() \n\n for line in lineArray:\n raw_data = line.split(\",\")\n name = raw_data[0]\n scores = []\n percentages = []\n average_percentage = 0\n\n if name != 'Testoutof':\n scores = raw_data[1:]\n\n for index, score in enumerate(scores):\n percentage = get_percentage(int(score), int(reference_scores[index]))\n average_percentage += percentage\n percentages.append(percentage)\n average_percentage //= len(scores)\n students.append( (name, percentages, average_percentage) )\n else:\n reference_scores = raw_data[1:]\n return students\n\ndef get_percentage(score, reference):\n return (score * 100) // reference\n\ndef print_scores(data):\n for obj in data:\n score_string = ''\n for score in obj[1]:\n score_string += f'{score}% ' \n print(f'{obj[0]} {score_string} Average = {obj[2]}')\n\nstudents = get_data()\nprint_scores(students)\n\n# Output\nBob 100% 81% 58% 72% 100% 81% 100% 90% 100% 72% 80% 83% 90% 100% Average = 86\nSue 80% 72% 66% 81% 40% 72% 100% 70% 80% 27% 100% 83% 70% 100% Average = 74\nJan 60% 54% 0% 45% 70% 81% 44% 70% 80% 45% 70% 8% 50% 100% Average = 55 \nSam 80% 72% 66% 63% 70% 63% 100% 90% 90% 81% 80% 75% 100% 88% Average = 79 \nTom 90% 81% 75% 81% 90% 81% 100% 90% 90% 90% 90% 75% 90% 100% Average = 87\n\n",
"Using list comprehension can give you the same result, without any function definition:\nfile=open(\"testscores.csv\",\"r\")\nmatrix=[line.strip().split(\",\") for line in file.readlines()[1:]]\n\nfor row in matrix:\n data=[int(i)*10 for i in row[1:]]\n print(row[0], \"% \".join(map(str, data))+\"%\", \"Average =\", sum(data)//len(data),\"%\")\n\nOutput:\nBob 100% 90% 70% 80% 100% 90% 90% 90% 100% 80% 80% 100% 90% 90% Average = 89 %\nSue 80% 80% 80% 90% 40% 80% 90% 70% 80% 30% 100% 100% 70% 90% Average = 77 %\nJan 60% 60% 0% 50% 70% 90% 40% 70% 80% 50% 70% 10% 50% 90% Average = 56 %\nSam 80% 80% 80% 70% 70% 70% 90% 90% 90% 90% 80% 90% 100% 80% Average = 82 %\nTom 90% 90% 90% 90% 90% 90% 90% 90% 90% 100% 90% 90% 90% 90% Average = 90 %\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"csv",
"python"
] |
stackoverflow_0074511906_csv_python.txt
|
Q:
How to make recursive function hold it's original parameter value?
I'm trying to write a function that calculates the determinant of a square matrix using recursion.
The parameter of the oldest function - the first one called - changes to the matrix returned by scale_down() and I don't know why.
def la_place(matrix):
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
g = -1
det = 0
for i in range(len(matrix)):
g *= -1
var = scale_down(matrix, i)
det += g*matrix[0][i]*la_place(var)
return det
def scale_down(matrix, i):
var = matrix
if len(var) > 2:
var.pop(0)
for x in range(len(var)):
var[x].pop(i)
return var
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(la_place(a))
I tried substituting "matrix" with "var" in order not to use it directly, but it amounted to nothing.
The code would work fine, I think, if after every for loop iteration in the oldest la_place call, the parameter "matrix" would still equal the original 3x3 matrix. That was my original idea.
A:
I figured it out. It turns out that var = matrix does not make var independent of matrix. I imported the "copy" library and used var = copy.deepcopy(matrix) to make var independent of matrix. Here is the solution:
import copy
def la_place(matrix):
var = copy.deepcopy(matrix)
if len(var) == 2:
return var[0][0] * var[1][1] - var[0][1] * var[1][0]
g = -1
det = 0
for i in range(len(var)):
g *= -1
det += g * matrix[0][i] * la_place(scale_down(var, i))
return det
def scale_down(matrix, i):
var = copy.deepcopy(matrix)
if len(var) > 2:
var.pop(0)
for x in range(len(var)):
var[x].pop(i)
return var
a = [[9, 4, 2, 1, 1, 7],
[1, 3, 2, 2, 2, 5],
[9, 9, 9, 3, 3, 6],
[9, 9, 9, 4, 5, 7],
[1, 2, 3, 5, 4, 5],
[2, 6, 7, 9, 4, 1]]
print(la_place(a))
|
How to make recursive function hold it's original parameter value?
|
I'm trying to write a function that calculates the determinant of a square matrix using recursion.
The parameter of the oldest function - the first one called - changes to the matrix returned by scale_down() and I don't know why.
def la_place(matrix):
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
g = -1
det = 0
for i in range(len(matrix)):
g *= -1
var = scale_down(matrix, i)
det += g*matrix[0][i]*la_place(var)
return det
def scale_down(matrix, i):
var = matrix
if len(var) > 2:
var.pop(0)
for x in range(len(var)):
var[x].pop(i)
return var
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(la_place(a))
I tried substituting "matrix" with "var" in order not to use it directly, but it amounted to nothing.
The code would work fine, I think, if after every for loop iteration in the oldest la_place call, the parameter "matrix" would still equal the original 3x3 matrix. That was my original idea.
|
[
"I figured it out. It turns out that var = matrix does not make var independent of matrix. I imported the \"copy\" library and used var = copy.deepcopy(matrix) to make var independent of matrix. Here is the solution:\nimport copy\n\n\ndef la_place(matrix):\n var = copy.deepcopy(matrix)\n if len(var) == 2:\n return var[0][0] * var[1][1] - var[0][1] * var[1][0]\n\n g = -1\n det = 0\n\n for i in range(len(var)):\n g *= -1\n det += g * matrix[0][i] * la_place(scale_down(var, i))\n return det\n\n\ndef scale_down(matrix, i):\n var = copy.deepcopy(matrix)\n if len(var) > 2:\n var.pop(0)\n for x in range(len(var)):\n var[x].pop(i)\n return var\n\n\na = [[9, 4, 2, 1, 1, 7],\n [1, 3, 2, 2, 2, 5],\n [9, 9, 9, 3, 3, 6],\n [9, 9, 9, 4, 5, 7],\n [1, 2, 3, 5, 4, 5],\n [2, 6, 7, 9, 4, 1]]\nprint(la_place(a))\n\n\n"
] |
[
0
] |
[] |
[] |
[
"matrix",
"python",
"recursion"
] |
stackoverflow_0074512365_matrix_python_recursion.txt
|
Q:
How do I fetch the KML's style information using fastkml?
I am parsing a KML and need to split features depending on the style given to each feature.
I've managed to parse the features and grab the styleUrl of each feature.
Here is roughly how I grab the styleUrls as well as the attributes from the features :
from fastkml import kml
with open( os.path.join(tmp_root,'doc.kml')) as file:
for text in file :
#print (text). It's not "pretty print", all in one line.
k = kml.KML()
k.from_string(text)
document = list(k.features())
print(len(document)) #this is the "<Document id=xxx ", should be equal to 1
# Fetching styles code should go here
folders = list(document[0].features())
print(folders) # two folders, one for boundaries and one for points
for folder in folders :
features = list(folder.features())
for f in features :
print(f.name)
print(f.styleUrl)
print (f.extended_data.elements)
for attribute in f.extended_data.elements :
print(attribute.name, attribute.value)
# if styleUrl == style.id, do something
My issue is trying to fetch the information from the Styles section of the Document. I can access the style's ID, but that's about it.
stylesSection = document[0].styles() #similar to how I access folders
for style in stylesSection :
print(style) # <fastkml.styles.Style object at 0x0000029C0599CFD0>
print(style.id) #styleid
print(style.styles) # <bound method Style.styles of <fastkml.styles.Style object at 0x0000029C057A97C0>>
I believe that style.styles is the function found here
Here's what the beginning of the document looks like :
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document id="IDOFDOC">
<name>NAME</name>
<open>1</open>
<Style id="styleid">
<LineStyle>
<color>ff0000ff</color>
<width>5</width>
</LineStyle>
<PolyStyle>
<fill>0</fill>
</PolyStyle>
</Style>
How do I fetch the color, width and fill attributes of the Poly and Line Styles that are in the <Style> ? Would the process be the same for a <StyleMap> ?
A:
I believe you can say list(style.styles())[0].color in order to get what you want.
|
How do I fetch the KML's style information using fastkml?
|
I am parsing a KML and need to split features depending on the style given to each feature.
I've managed to parse the features and grab the styleUrl of each feature.
Here is roughly how I grab the styleUrls as well as the attributes from the features :
from fastkml import kml
with open( os.path.join(tmp_root,'doc.kml')) as file:
for text in file :
#print (text). It's not "pretty print", all in one line.
k = kml.KML()
k.from_string(text)
document = list(k.features())
print(len(document)) #this is the "<Document id=xxx ", should be equal to 1
# Fetching styles code should go here
folders = list(document[0].features())
print(folders) # two folders, one for boundaries and one for points
for folder in folders :
features = list(folder.features())
for f in features :
print(f.name)
print(f.styleUrl)
print (f.extended_data.elements)
for attribute in f.extended_data.elements :
print(attribute.name, attribute.value)
# if styleUrl == style.id, do something
My issue is trying to fetch the information from the Styles section of the Document. I can access the style's ID, but that's about it.
stylesSection = document[0].styles() #similar to how I access folders
for style in stylesSection :
print(style) # <fastkml.styles.Style object at 0x0000029C0599CFD0>
print(style.id) #styleid
print(style.styles) # <bound method Style.styles of <fastkml.styles.Style object at 0x0000029C057A97C0>>
I believe that style.styles is the function found here
Here's what the beginning of the document looks like :
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document id="IDOFDOC">
<name>NAME</name>
<open>1</open>
<Style id="styleid">
<LineStyle>
<color>ff0000ff</color>
<width>5</width>
</LineStyle>
<PolyStyle>
<fill>0</fill>
</PolyStyle>
</Style>
How do I fetch the color, width and fill attributes of the Poly and Line Styles that are in the <Style> ? Would the process be the same for a <StyleMap> ?
|
[
"I believe you can say list(style.styles())[0].color in order to get what you want.\n"
] |
[
0
] |
[] |
[] |
[
"kml",
"performance",
"python",
"xml_parsing"
] |
stackoverflow_0073463672_kml_performance_python_xml_parsing.txt
|
Q:
How do i sort my list of tuples in ascending order e.g. my_list = [(6,4), (3,4)] to produce (3,4) (4,6)
How can i sort the below list of tuples to produce tuples of (3,4) (4,6)
my_list = [(6,4), (3,4)]
I have tried the following
items= [(3,4),(6,4)]
sorted_items= sorted(items)
print(sorted_items)
and
my_list = [(6,4), (3,4)]
my_list.sort(key=lambda tup: (tup[0], tup[1]), reverse=False)
print(my_list)
Thanks
A:
You can use two calls to sorted() to generate the desired output:
sorted(tuple(sorted(tup)) for tup in my_list)
This outputs:
[(3, 4), (4, 6)]
|
How do i sort my list of tuples in ascending order e.g. my_list = [(6,4), (3,4)] to produce (3,4) (4,6)
|
How can i sort the below list of tuples to produce tuples of (3,4) (4,6)
my_list = [(6,4), (3,4)]
I have tried the following
items= [(3,4),(6,4)]
sorted_items= sorted(items)
print(sorted_items)
and
my_list = [(6,4), (3,4)]
my_list.sort(key=lambda tup: (tup[0], tup[1]), reverse=False)
print(my_list)
Thanks
|
[
"You can use two calls to sorted() to generate the desired output:\nsorted(tuple(sorted(tup)) for tup in my_list)\n\nThis outputs:\n[(3, 4), (4, 6)]\n\n"
] |
[
0
] |
[] |
[] |
[
"function",
"python",
"sorting",
"tuples"
] |
stackoverflow_0074512668_function_python_sorting_tuples.txt
|
Q:
Getting a bug when trying to add two lists in Python
I've been trying to debug this simple code for 20 minutes and it's driving me crazy, I'm starting to think there's a bug in Python.
What I want to do is add two lists, element by element (there probably is some more efficient way to do this or even an in-build function, I'm just doing it as an exercise):
def add(l1,l2):
if l1>=l2:
l=l1
for i in range(len(l2)):
l1[i]+=l2[i]
else:
l=l2
for i in range(len(l1)):
l2[i]+=l1[i]
return l
Now for example:
add([1,2],[2,6,5])
[3, 8, 5]
But when the first number of the second list is negative, I get an error message:
add([1,2],[-2,6,5])
l1[i]+=l2[i]
IndexError: list index out of range
How can the sign of one element affect the index whatsoever?
To make things weirder, the code works just fine if I take out the if condition (I assume that the second list is longer here):
def add(l1,l2):
l=l2
for i in range(len(l1)):
l2[i]+=l1[i]
return l
Then:
>>> add([1,2],[-2,6,5])
[-1, 8, 5]
A:
When you use comparison operators on lists you do not compare the length of them but the content, look:
l1 = [1, 2]
l2 = [2, 1]
assert l1 < l2 (because l1[0] < l2[0])
What you want to use is len builtin:
if len(l1) >= len(l2):
...
A:
You did an elementwise compare when really you wanted to know which was the shortest list for indexing. So, compare the lengths of the lists, not the contents. To avoid duplicating the logic, setup the relationship once for the rest of the function.
def add(l1,l2):
large, small = (l1, l2) if len(l1) >= len(l2) else (l2, l1)
for i in range(len(small)):
large[i] += small[i]
return large
print(add([1,2], [2,6,5]))
print(add([1,2], [-2,6,5]))
|
Getting a bug when trying to add two lists in Python
|
I've been trying to debug this simple code for 20 minutes and it's driving me crazy, I'm starting to think there's a bug in Python.
What I want to do is add two lists, element by element (there probably is some more efficient way to do this or even an in-build function, I'm just doing it as an exercise):
def add(l1,l2):
if l1>=l2:
l=l1
for i in range(len(l2)):
l1[i]+=l2[i]
else:
l=l2
for i in range(len(l1)):
l2[i]+=l1[i]
return l
Now for example:
add([1,2],[2,6,5])
[3, 8, 5]
But when the first number of the second list is negative, I get an error message:
add([1,2],[-2,6,5])
l1[i]+=l2[i]
IndexError: list index out of range
How can the sign of one element affect the index whatsoever?
To make things weirder, the code works just fine if I take out the if condition (I assume that the second list is longer here):
def add(l1,l2):
l=l2
for i in range(len(l1)):
l2[i]+=l1[i]
return l
Then:
>>> add([1,2],[-2,6,5])
[-1, 8, 5]
|
[
"When you use comparison operators on lists you do not compare the length of them but the content, look:\nl1 = [1, 2]\nl2 = [2, 1]\nassert l1 < l2 (because l1[0] < l2[0])\n\nWhat you want to use is len builtin:\nif len(l1) >= len(l2):\n ...\n\n",
"You did an elementwise compare when really you wanted to know which was the shortest list for indexing. So, compare the lengths of the lists, not the contents. To avoid duplicating the logic, setup the relationship once for the rest of the function.\ndef add(l1,l2):\n large, small = (l1, l2) if len(l1) >= len(l2) else (l2, l1)\n for i in range(len(small)):\n large[i] += small[i]\n return large\n\nprint(add([1,2], [2,6,5]))\nprint(add([1,2], [-2,6,5]))\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0074512645_list_python.txt
|
Q:
Flask Rest API View Returning Invalid Response
I am trying to test an endpoint in postman for a flask API, and I am having this error below
TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers).
The function is given below
auth = Blueprint("auth", __name__, url_prefix="/api/v1/auth")
@auth.post('/register')
def register():
username = request.json['username']
password = request.json['password']
email = request.json['email']
if len(password) < 6:
return jsonify({'error': "Password is too short"}),
HTTP_400_BAD_REQUEST
if len(username) < 3:
return jsonify({'error': "User is too short"}),
HTTP_400_BAD_REQUEST
if username.isalnum() or " " in username:
return jsonify({'error': "User is too short"}),
HTTP_400_BAD_REQUEST
if not username.isalnum() or " " in username:
return jsonify({'error': "Username should be alphanumeric, also no spaces"}),
HTTP_400_BAD_REQUEST
if not validators.email(email):
return jsonify({'error': "Email is not valid"})
HTTP_400_BAD_REQUEST
if User.query.filter_by(email=email).first() is not None:
return jsonify({'error': "Email is taken"}), HTTP_409_CONFLICT
if User.query.filter_by(username=username).first() is not None:
return jsonify({'error': "username is taken"}), HTTP_409_CONFLICT
pwd_hash=generate_password_hash(password)
user = User(username=username, password=pwd_hash, email=email)
db.session.add(user)
db.session.commit()
return jsonify({
'message': "User created",
'user': {
'username': username, 'email': email
}
}), HTTP_201_CREATED
The test input on postman to the route http://127.0.0.1:5000/api/v1/auth/test is :
{
"username": "username",
"password": "password",
"email": "email@app.com"
}
A:
well you forgot to add a , in the below code
if not validators.email(email):
return jsonify({'error': "Email is not valid"})
HTTP_400_BAD_REQUEST
this is causing this Typeerror
just change this to
return jsonify({'error': "Email is not valid"}),
HTTP_400_BAD_REQUEST
|
Flask Rest API View Returning Invalid Response
|
I am trying to test an endpoint in postman for a flask API, and I am having this error below
TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers).
The function is given below
auth = Blueprint("auth", __name__, url_prefix="/api/v1/auth")
@auth.post('/register')
def register():
username = request.json['username']
password = request.json['password']
email = request.json['email']
if len(password) < 6:
return jsonify({'error': "Password is too short"}),
HTTP_400_BAD_REQUEST
if len(username) < 3:
return jsonify({'error': "User is too short"}),
HTTP_400_BAD_REQUEST
if username.isalnum() or " " in username:
return jsonify({'error': "User is too short"}),
HTTP_400_BAD_REQUEST
if not username.isalnum() or " " in username:
return jsonify({'error': "Username should be alphanumeric, also no spaces"}),
HTTP_400_BAD_REQUEST
if not validators.email(email):
return jsonify({'error': "Email is not valid"})
HTTP_400_BAD_REQUEST
if User.query.filter_by(email=email).first() is not None:
return jsonify({'error': "Email is taken"}), HTTP_409_CONFLICT
if User.query.filter_by(username=username).first() is not None:
return jsonify({'error': "username is taken"}), HTTP_409_CONFLICT
pwd_hash=generate_password_hash(password)
user = User(username=username, password=pwd_hash, email=email)
db.session.add(user)
db.session.commit()
return jsonify({
'message': "User created",
'user': {
'username': username, 'email': email
}
}), HTTP_201_CREATED
The test input on postman to the route http://127.0.0.1:5000/api/v1/auth/test is :
{
"username": "username",
"password": "password",
"email": "email@app.com"
}
|
[
"well you forgot to add a , in the below code\n if not validators.email(email):\n return jsonify({'error': \"Email is not valid\"})\n HTTP_400_BAD_REQUEST\n\nthis is causing this Typeerror\njust change this to\nreturn jsonify({'error': \"Email is not valid\"}),\n HTTP_400_BAD_REQUEST\n\n"
] |
[
2
] |
[] |
[] |
[
"flask",
"python"
] |
stackoverflow_0074512567_flask_python.txt
|
Q:
Merging pandas dataframes on potentially different join keys
I have a dataframe A with columns like so:
ACCOUNT_NAME
SFDC_ACCOUNT_NAME
COMPANY_NAME
Acme Inc
Acme, Inc.
Acme
Donut Heaven
None
Doughnut Heaven
Super Foods
Sooper Foods
None
I want to merge on additional columns but I am not sure if this additional data was captured using ACCOUNT_NAME, SFDC_ACCOUNT_NAME, or COMPANY_NAME. This data looks like the table below. There is a join key column that could represent either ACCOUNT_NAME, SFDC_ACCOUNT_NAME, or COMPANY_NAME.
CAPTURED_COMPANY_NAME
value1
value2
Acme Inc
2
3
Sooper Foods
6
7
Doughnut Heaven
5
8
I want the final table to look like this:
ACCOUNT_NAME
SFDC_ACCOUNT_NAME
COMPANY_NAME
value1
value2
Acme Inc
Acme, Inc.
Acme
2
3
Donut Heaven
None
Doughnut Heaven
5
8
Super Foods
Sooper Foods
None
6
7
I could merge this second dataset onto the first three times (one for each join key) but then of course columns value1 and value2 would be repeated three times. What is the best way to achieve this?
A:
Given:
# df
ACCOUNT_NAME SFDC_ACCOUNT_NAME COMPANY_NAME
0 Acme Inc Acme, Inc. Acme
1 Donut Heaven NaN Doughnut Heaven
2 Super Foods Sooper Foods NaN
# df1
CAPTURED_COMPANY_NAME value1 value2
0 Acme Inc 2 3
1 Sooper Foods 6 7
2 Doughnut Heaven 5 8
Doing:
# Merge each individually, and concat the results:
out = pd.concat([df.merge(df1, left_on=x, right_on='CAPTURED_COMPANY_NAME') for x in df.columns], ignore_index=True)
# Left Merge:
# out = df.merge(pd.concat([df.merge(df1, left_on=x, right_on='CAPTURED_COMPANY_NAME') for x in df.columns], ignore_index=True), how='left')
print(out)
Output:
ACCOUNT_NAME SFDC_ACCOUNT_NAME COMPANY_NAME CAPTURED_COMPANY_NAME value1 value2
0 Acme Inc Acme, Inc. Acme Acme Inc 2 3
1 Super Foods Sooper Foods NaN Sooper Foods 6 7
2 Donut Heaven NaN Doughnut Heaven Doughnut Heaven 5 8
|
Merging pandas dataframes on potentially different join keys
|
I have a dataframe A with columns like so:
ACCOUNT_NAME
SFDC_ACCOUNT_NAME
COMPANY_NAME
Acme Inc
Acme, Inc.
Acme
Donut Heaven
None
Doughnut Heaven
Super Foods
Sooper Foods
None
I want to merge on additional columns but I am not sure if this additional data was captured using ACCOUNT_NAME, SFDC_ACCOUNT_NAME, or COMPANY_NAME. This data looks like the table below. There is a join key column that could represent either ACCOUNT_NAME, SFDC_ACCOUNT_NAME, or COMPANY_NAME.
CAPTURED_COMPANY_NAME
value1
value2
Acme Inc
2
3
Sooper Foods
6
7
Doughnut Heaven
5
8
I want the final table to look like this:
ACCOUNT_NAME
SFDC_ACCOUNT_NAME
COMPANY_NAME
value1
value2
Acme Inc
Acme, Inc.
Acme
2
3
Donut Heaven
None
Doughnut Heaven
5
8
Super Foods
Sooper Foods
None
6
7
I could merge this second dataset onto the first three times (one for each join key) but then of course columns value1 and value2 would be repeated three times. What is the best way to achieve this?
|
[
"Given:\n# df\n\n ACCOUNT_NAME SFDC_ACCOUNT_NAME COMPANY_NAME\n0 Acme Inc Acme, Inc. Acme\n1 Donut Heaven NaN Doughnut Heaven\n2 Super Foods Sooper Foods NaN\n\n# df1\n\n CAPTURED_COMPANY_NAME value1 value2\n0 Acme Inc 2 3\n1 Sooper Foods 6 7\n2 Doughnut Heaven 5 8\n\nDoing:\n# Merge each individually, and concat the results:\nout = pd.concat([df.merge(df1, left_on=x, right_on='CAPTURED_COMPANY_NAME') for x in df.columns], ignore_index=True)\n# Left Merge:\n# out = df.merge(pd.concat([df.merge(df1, left_on=x, right_on='CAPTURED_COMPANY_NAME') for x in df.columns], ignore_index=True), how='left')\nprint(out)\n\nOutput:\n ACCOUNT_NAME SFDC_ACCOUNT_NAME COMPANY_NAME CAPTURED_COMPANY_NAME value1 value2\n0 Acme Inc Acme, Inc. Acme Acme Inc 2 3\n1 Super Foods Sooper Foods NaN Sooper Foods 6 7\n2 Donut Heaven NaN Doughnut Heaven Doughnut Heaven 5 8\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074512686_pandas_python.txt
|
Q:
python subprocess.call() doesn't work with multiline shell commands
I would like to run this multiline shell commands:
echo 'a=?'
read a
echo "a=$a"
from a python script, using the subprocess.call() method.
I wrote this, in test.py file:
import shlex, subprocess
args = ["echo", 'a=?',"read", "a", "echo", "a=$a"]
subprocess.call(args)
and when I execute it, I have in terminal this report:
Armonicus@MyMacs-iMac MyNewFolder % python test.py
a=? read a echo a=$a
which is not at least close to what I expect.
Can I have some support from anyone, please?
A:
There are a couple of issues with your approach here.
First, if what you're trying to do is prompt the user for input from the command line, then you can use Python builtins instead of a subprocess:
a = input('a=?')
print(a)
If you do want to call a subprocess with multiple commands, you need to either make separate calls for each command, or invoke a shell and execute the commands within it. For example:
subprocess.call("echo 'a=?'; read a; echo $a", shell=True)
|
python subprocess.call() doesn't work with multiline shell commands
|
I would like to run this multiline shell commands:
echo 'a=?'
read a
echo "a=$a"
from a python script, using the subprocess.call() method.
I wrote this, in test.py file:
import shlex, subprocess
args = ["echo", 'a=?',"read", "a", "echo", "a=$a"]
subprocess.call(args)
and when I execute it, I have in terminal this report:
Armonicus@MyMacs-iMac MyNewFolder % python test.py
a=? read a echo a=$a
which is not at least close to what I expect.
Can I have some support from anyone, please?
|
[
"There are a couple of issues with your approach here.\nFirst, if what you're trying to do is prompt the user for input from the command line, then you can use Python builtins instead of a subprocess:\na = input('a=?')\nprint(a)\n\nIf you do want to call a subprocess with multiple commands, you need to either make separate calls for each command, or invoke a shell and execute the commands within it. For example:\nsubprocess.call(\"echo 'a=?'; read a; echo $a\", shell=True)\n\n"
] |
[
0
] |
[] |
[] |
[
"multiline",
"python",
"shell",
"subprocess"
] |
stackoverflow_0074512575_multiline_python_shell_subprocess.txt
|
Q:
Defining a function that only accepts an integer as an input
My approach with this function is that it only accepts an integer as an input, otherwise if the person enters a letter or something else it goes back to the while loop and continues asking for the input until it receives the correct input which in this case it can only be 1-9.
import string
string.ascii_letters
def player_choice(board):
position = 0
while position not in list(range(1,10)) or space_check(board, position) or position in list[string.ascii_letters]:
if position in list[string.ascii_letters]:
pass
position = int(input("Please enter a position(1-9): "))
return position
I tried importing ascii_letters from the string library to tell python that if the input is inside of the that list to go back to the while loop, but everytime I run the code i get a syntax error saying that the input only accepts an integer.
A:
First solution using simple checkings
def player_choice(board):
while True:
position = input("Please enter a position(1-9): ")
if position.isdecimal() and len(position) == 1 and position != '0':
position = int(position)
break
return position
Second solution using regex
import re
def player_choice(board):
while True:
position = input("Please enter a position(1-9): ")
if re.match('^[1-9]$', position):
position = int(position)
break
return position
|
Defining a function that only accepts an integer as an input
|
My approach with this function is that it only accepts an integer as an input, otherwise if the person enters a letter or something else it goes back to the while loop and continues asking for the input until it receives the correct input which in this case it can only be 1-9.
import string
string.ascii_letters
def player_choice(board):
position = 0
while position not in list(range(1,10)) or space_check(board, position) or position in list[string.ascii_letters]:
if position in list[string.ascii_letters]:
pass
position = int(input("Please enter a position(1-9): "))
return position
I tried importing ascii_letters from the string library to tell python that if the input is inside of the that list to go back to the while loop, but everytime I run the code i get a syntax error saying that the input only accepts an integer.
|
[
"First solution using simple checkings\ndef player_choice(board):\n while True:\n position = input(\"Please enter a position(1-9): \")\n if position.isdecimal() and len(position) == 1 and position != '0':\n position = int(position)\n break\n return position\n\nSecond solution using regex\nimport re\n\ndef player_choice(board):\n while True:\n position = input(\"Please enter a position(1-9): \")\n if re.match('^[1-9]$', position):\n position = int(position)\n break\n return position\n\n"
] |
[
1
] |
[
"Use typing.\ndef whatever(param: int):\n"
] |
[
-2
] |
[
"python"
] |
stackoverflow_0074512558_python.txt
|
Q:
mqtt paho library running test with docker
i've been trying to make this example running for many hours. I was building an example so my friend can learn some python but i've end up frustrated on my own.
My python knowledge is quite limited. Something is causing the program thread to finish no matter how much I try delaying the execution with time.sleep (i've removed that part of the code).
Expect result: sender container should be started after the receiver one. So the receiver is subscribed to the broker and waiting for messages.
Given result: receiver container starts and then dies.
Thanks in advance.
I have a docker compose as follows:
services:
mqtt_broker:
image: eclipse-mosquitto
volumes:
- "./mosquitto.conf:/mosquitto/config/mosquitto.conf"
client_send:
build:
context: ./client_send/
environment:
BROKER_HOST: mqtt_broker
depends_on:
- client_receive
client_receive:
build:
context: ./client_receive/
environment:
BROKER_HOST: mqtt_broker
depends_on:
- mqtt_broker
Then I have client code for each of these clients:
Receiver:
import os
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("[receiver] Connected with result code " + str(rc))
client.subscribe("sample_topic")
def on_message(client, userdata, msg):
print("[receiver] got a message: " + str(msg.payload.decode()))
client.loop_stop()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(os.environ["BROKER_HOST"], 1883, 60)
client.loop_start()
Sender:
import os
import paho.mqtt.client as mqtt
def run():
print("[sender] will send a message")
client.publish("sample_topic", "message from sender")
client.loop_stop()
def on_connect(client, userdata, flags, rc):
print("[sender] Connected with result code " + str(rc))
run()
client = mqtt.Client()
client.on_connect = on_connect
client.connect(os.environ["BROKER_HOST"], 1883, 60)
client.loop_start()
A:
I was using loop_forever without too much success bcoz print() calls were not logging anything since the main thread was blocked so I couldn't see if my code was working.
EDIT: previous paragraph is just not correct. loop_forever will work taking this into account: Python app does not print anything when running detached in docker
Finally got it working as suggested by @Brits (see comments) just by running exit or disconnecting the client (works using exit too)
I also keep the depends_on so the docker-compose.yml was not changed
This is the receiver:
import os
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("[receiver] Connected with result code " + str(rc))
client.subscribe("sample_topic")
def on_message(client, userdata, msg):
print("[receiver] got a message: " + str(msg.payload.decode()))
client.disconnect()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(os.environ["BROKER_HOST"], 1883, 60)
client.loop_forever()
As a side note, if the main thread is blocked you will never be able to see the output of the program even if you got the message back from the sender. If you don't disconnect the client it might actually work if your application does not rely on console output. Soo freeing the main thread allows for the system to release the output logs to docker.
|
mqtt paho library running test with docker
|
i've been trying to make this example running for many hours. I was building an example so my friend can learn some python but i've end up frustrated on my own.
My python knowledge is quite limited. Something is causing the program thread to finish no matter how much I try delaying the execution with time.sleep (i've removed that part of the code).
Expect result: sender container should be started after the receiver one. So the receiver is subscribed to the broker and waiting for messages.
Given result: receiver container starts and then dies.
Thanks in advance.
I have a docker compose as follows:
services:
mqtt_broker:
image: eclipse-mosquitto
volumes:
- "./mosquitto.conf:/mosquitto/config/mosquitto.conf"
client_send:
build:
context: ./client_send/
environment:
BROKER_HOST: mqtt_broker
depends_on:
- client_receive
client_receive:
build:
context: ./client_receive/
environment:
BROKER_HOST: mqtt_broker
depends_on:
- mqtt_broker
Then I have client code for each of these clients:
Receiver:
import os
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("[receiver] Connected with result code " + str(rc))
client.subscribe("sample_topic")
def on_message(client, userdata, msg):
print("[receiver] got a message: " + str(msg.payload.decode()))
client.loop_stop()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(os.environ["BROKER_HOST"], 1883, 60)
client.loop_start()
Sender:
import os
import paho.mqtt.client as mqtt
def run():
print("[sender] will send a message")
client.publish("sample_topic", "message from sender")
client.loop_stop()
def on_connect(client, userdata, flags, rc):
print("[sender] Connected with result code " + str(rc))
run()
client = mqtt.Client()
client.on_connect = on_connect
client.connect(os.environ["BROKER_HOST"], 1883, 60)
client.loop_start()
|
[
"I was using loop_forever without too much success bcoz print() calls were not logging anything since the main thread was blocked so I couldn't see if my code was working.\nEDIT: previous paragraph is just not correct. loop_forever will work taking this into account: Python app does not print anything when running detached in docker\nFinally got it working as suggested by @Brits (see comments) just by running exit or disconnecting the client (works using exit too)\nI also keep the depends_on so the docker-compose.yml was not changed\nThis is the receiver:\nimport os\nimport paho.mqtt.client as mqtt\n\ndef on_connect(client, userdata, flags, rc):\n print(\"[receiver] Connected with result code \" + str(rc))\n client.subscribe(\"sample_topic\")\n\ndef on_message(client, userdata, msg):\n print(\"[receiver] got a message: \" + str(msg.payload.decode()))\n client.disconnect()\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(os.environ[\"BROKER_HOST\"], 1883, 60)\nclient.loop_forever()\n\nAs a side note, if the main thread is blocked you will never be able to see the output of the program even if you got the message back from the sender. If you don't disconnect the client it might actually work if your application does not rely on console output. Soo freeing the main thread allows for the system to release the output logs to docker.\n"
] |
[
0
] |
[] |
[] |
[
"docker",
"mosquitto",
"mqtt",
"paho",
"python"
] |
stackoverflow_0074510148_docker_mosquitto_mqtt_paho_python.txt
|
Q:
How to detect in Tkinter that whole window is moved (esspecially to the other screen)?
I want to change scaling depend on screen. I know how to scale but I do not know how to detect that windows is move from screen 1 to screen 2.
What event and bind is need for it?
A:
Basically I have to disappointing you, there is no such binding to detect that. There is however a long history of trying to get a cross platform specific solution working, without fully success. You can read something about it in the tcler's-wiki where I have the basic idea from.
The only way to track your window by moving is by a binding to '<Configure>', this event is fired when you move the window. Within a event-handler you can track the position with event.root_x and event.root_y. These coordinates are screencoordinates from the window. So far so good, we can know when we are moving and where we are.
A useful insight is that the first screen, most often the left one, has always the coordinate 0,0 as the upper left corner. Place your window there with window.geometry('+0+0') ensure the window is placed there via window.update_idletasks() ask for wm_maxsize, that is the width and height of the current screen and usually used to zoom your window. The next thing you have to do is a little bit of math against winfo_screenwidth() and winfo_screenheight() that usually gives you all the available space on the screen.
EDIT: Also try winfo_vrootwidth() and winfo_vrootheight()
There you have it, you know where the second screen begins and how to track the window movement. I think you are good to go with that and try it out, but keep in mind that this technique is not OS-independent.
An additional thought that I had was to invoke that procedure in a loop and to search for more screens, but never actual coded it.
Pro tip: when you do window.wm_attributes('-alpha', 0) you don't have to watch your window jumping around by gathering the needed information.
|
How to detect in Tkinter that whole window is moved (esspecially to the other screen)?
|
I want to change scaling depend on screen. I know how to scale but I do not know how to detect that windows is move from screen 1 to screen 2.
What event and bind is need for it?
|
[
"Basically I have to disappointing you, there is no such binding to detect that. There is however a long history of trying to get a cross platform specific solution working, without fully success. You can read something about it in the tcler's-wiki where I have the basic idea from.\nThe only way to track your window by moving is by a binding to '<Configure>', this event is fired when you move the window. Within a event-handler you can track the position with event.root_x and event.root_y. These coordinates are screencoordinates from the window. So far so good, we can know when we are moving and where we are.\nA useful insight is that the first screen, most often the left one, has always the coordinate 0,0 as the upper left corner. Place your window there with window.geometry('+0+0') ensure the window is placed there via window.update_idletasks() ask for wm_maxsize, that is the width and height of the current screen and usually used to zoom your window. The next thing you have to do is a little bit of math against winfo_screenwidth() and winfo_screenheight() that usually gives you all the available space on the screen.\nEDIT: Also try winfo_vrootwidth() and winfo_vrootheight()\nThere you have it, you know where the second screen begins and how to track the window movement. I think you are good to go with that and try it out, but keep in mind that this technique is not OS-independent.\nAn additional thought that I had was to invoke that procedure in a loop and to search for more screens, but never actual coded it.\nPro tip: when you do window.wm_attributes('-alpha', 0) you don't have to watch your window jumping around by gathering the needed information.\n"
] |
[
1
] |
[] |
[] |
[
"dpi",
"python",
"python_3.x",
"tk_toolkit",
"tkinter"
] |
stackoverflow_0074512770_dpi_python_python_3.x_tk_toolkit_tkinter.txt
|
Q:
Behaviour of set-intersection of objects
I stumbled upon this uncertainty in one of my programs:
Suppose we have a Class deriving from int with a custom attribute.
class A(int):
def __new__(cls, value, *args, **kwargs):
return super(cls, cls).__new__(cls, value)
def __init__(self, _, a):
self.a = a
Objects of this class are now used in a Set.
set1 = {A(2, 5), A(3, 2)}
set2 = {A(3, 7), A(5, 5)}
How would I now know the output of the following operations?
x, = set1 & set2
print(x.a)
x, = set2 & set1
print(x.a)
x, = set1.intersection(set2)
print(x.a)
...
It appeared to me in various tests that the result is rather random, could somebody explain this behaviour?
Thank you in advance :)
A:
You intrigued me so much that I looked into source code and it became quite logical. We looped over smaller set and search every element in bigger one. When both sets has equal size, the order matters (that's why you get different results in your case), otherwise the elements taken will always belong to smaller set.
|
Behaviour of set-intersection of objects
|
I stumbled upon this uncertainty in one of my programs:
Suppose we have a Class deriving from int with a custom attribute.
class A(int):
def __new__(cls, value, *args, **kwargs):
return super(cls, cls).__new__(cls, value)
def __init__(self, _, a):
self.a = a
Objects of this class are now used in a Set.
set1 = {A(2, 5), A(3, 2)}
set2 = {A(3, 7), A(5, 5)}
How would I now know the output of the following operations?
x, = set1 & set2
print(x.a)
x, = set2 & set1
print(x.a)
x, = set1.intersection(set2)
print(x.a)
...
It appeared to me in various tests that the result is rather random, could somebody explain this behaviour?
Thank you in advance :)
|
[
"You intrigued me so much that I looked into source code and it became quite logical. We looped over smaller set and search every element in bigger one. When both sets has equal size, the order matters (that's why you get different results in your case), otherwise the elements taken will always belong to smaller set.\n"
] |
[
1
] |
[] |
[] |
[
"class",
"python",
"set"
] |
stackoverflow_0074512734_class_python_set.txt
|
Q:
Python - trouble pivoting, grouping, and summing dataframe columns
I have this code. I need to group by CustomerName and then sum the filegroups.
def consolidated_df():
df = breakdown_df()
df.pivot_table(index='CustomerName', columns='FileGroup', aggfunc="sum")
return df
breakdown_df() looks like
ID CustomerName FileGroup Size Size(Bytes)
1 CustomerA Database 99.8 M 104667648
1 CustomerA Database 99.8 M 104667648
1 CustomerA Backup 99.8 M 104667648
1 CustomerA Backup 99.8 M 104667648
1 CustomerA Site 99.8 M 104667648
1 CustomerA Site 99.8 M 104667648
2 CustomerB Database 99.8 M 104667648
2 CustomerB Database 99.8 M 104667648
2 CustomerB Backup 99.8 M 104667648
2 CustomerB Backup 99.8 M 104667648
2 CustomerB Site 99.8 M 104667648
2 CustomerB Site 99.8 M 104667648
I am trying to roll it up into
ID CustomerName DatabaseSize DatabaseSizeBytes BackupSize BackupSizeBytes SiteSize SiteSizeByte TotalSize
1 CustomerA [Total Size] [Total Size Bytes] [TotalSize] [Total Size Bites] [Total Site Size] [Total Site Bites] [Total Bytes for everything]
2 CustomerB [Total Size] [Total Size Bytes] [TotalSize] [Total Size Bites] [Total Site Size] [Total Site Bites] [Total Bytes for everything]
I'm not so worried about actually summing Size because I can convert the bites. I just can't seem to get my pivot to work and unsure where I am going wrong.
A:
If you don't explicitly set values, it'll try to use all remaining columns...
out = df.pivot_table(index='CustomerName', columns='FileGroup', values='Size(Bytes)', aggfunc='sum')
print(out)
Output:
FileGroup Backup Database Site
CustomerName
CustomerA 209335296 209335296 209335296
CustomerB 209335296 209335296 209335296
You can also have margins if desired:
df.pivot_table(index='CustomerName',
columns='FileGroup',
values='Size(Bytes)',
aggfunc='sum',
margins=True,
margins_name='TotalSize').drop('TotalSize')
# Output:
FileGroup Backup Database Site TotalSize
CustomerName
CustomerA 209335296 209335296 209335296 628005888
CustomerB 209335296 209335296 209335296 628005888
A:
With help of another StackOverflow answer:
# https://stackoverflow.com/a/23773174/10035985
def sizeof_fmt(num, use_kibibyte=True):
base, suffix = [(1000.0, "B"), (1024.0, "iB")][use_kibibyte]
for x in ["B", *map(lambda x: x + suffix, list("kMGTP"))]:
if -base < num < base:
return "%3.1f %s" % (num, x)
num /= base
return "%3.1f %s" % (num, x)
x = df.pivot_table(
index=["ID", "CustomerName"],
columns=["FileGroup"],
values="Size(Bytes)",
aggfunc="sum",
)
columns_to_convert = list(x.columns)
x = pd.concat([x, x.add_suffix("SizeBytes")], axis=1)
x["TotalSize"] = x[columns_to_convert].sum(axis=1).apply(sizeof_fmt)
for c in columns_to_convert:
x[c] = x[c].apply(sizeof_fmt)
x.columns.name, x.index.name = None, None
print(x.reset_index())
Prints:
ID CustomerName Backup Database Site BackupSizeBytes DatabaseSizeBytes SiteSizeBytes TotalSize
0 1 CustomerA 199.6 MiB 199.6 MiB 199.6 MiB 209335296 209335296 209335296 598.9 MiB
1 2 CustomerB 199.6 MiB 199.6 MiB 199.6 MiB 209335296 209335296 209335296 598.9 MiB
|
Python - trouble pivoting, grouping, and summing dataframe columns
|
I have this code. I need to group by CustomerName and then sum the filegroups.
def consolidated_df():
df = breakdown_df()
df.pivot_table(index='CustomerName', columns='FileGroup', aggfunc="sum")
return df
breakdown_df() looks like
ID CustomerName FileGroup Size Size(Bytes)
1 CustomerA Database 99.8 M 104667648
1 CustomerA Database 99.8 M 104667648
1 CustomerA Backup 99.8 M 104667648
1 CustomerA Backup 99.8 M 104667648
1 CustomerA Site 99.8 M 104667648
1 CustomerA Site 99.8 M 104667648
2 CustomerB Database 99.8 M 104667648
2 CustomerB Database 99.8 M 104667648
2 CustomerB Backup 99.8 M 104667648
2 CustomerB Backup 99.8 M 104667648
2 CustomerB Site 99.8 M 104667648
2 CustomerB Site 99.8 M 104667648
I am trying to roll it up into
ID CustomerName DatabaseSize DatabaseSizeBytes BackupSize BackupSizeBytes SiteSize SiteSizeByte TotalSize
1 CustomerA [Total Size] [Total Size Bytes] [TotalSize] [Total Size Bites] [Total Site Size] [Total Site Bites] [Total Bytes for everything]
2 CustomerB [Total Size] [Total Size Bytes] [TotalSize] [Total Size Bites] [Total Site Size] [Total Site Bites] [Total Bytes for everything]
I'm not so worried about actually summing Size because I can convert the bites. I just can't seem to get my pivot to work and unsure where I am going wrong.
|
[
"If you don't explicitly set values, it'll try to use all remaining columns...\nout = df.pivot_table(index='CustomerName', columns='FileGroup', values='Size(Bytes)', aggfunc='sum')\nprint(out)\n\nOutput:\nFileGroup Backup Database Site\nCustomerName \nCustomerA 209335296 209335296 209335296\nCustomerB 209335296 209335296 209335296\n\n\nYou can also have margins if desired:\ndf.pivot_table(index='CustomerName', \n columns='FileGroup', \n values='Size(Bytes)', \n aggfunc='sum', \n margins=True, \n margins_name='TotalSize').drop('TotalSize')\n\n# Output:\n\nFileGroup Backup Database Site TotalSize\nCustomerName \nCustomerA 209335296 209335296 209335296 628005888\nCustomerB 209335296 209335296 209335296 628005888\n\n",
"With help of another StackOverflow answer:\n# https://stackoverflow.com/a/23773174/10035985\ndef sizeof_fmt(num, use_kibibyte=True):\n base, suffix = [(1000.0, \"B\"), (1024.0, \"iB\")][use_kibibyte]\n for x in [\"B\", *map(lambda x: x + suffix, list(\"kMGTP\"))]:\n if -base < num < base:\n return \"%3.1f %s\" % (num, x)\n num /= base\n return \"%3.1f %s\" % (num, x)\n\n\nx = df.pivot_table(\n index=[\"ID\", \"CustomerName\"],\n columns=[\"FileGroup\"],\n values=\"Size(Bytes)\",\n aggfunc=\"sum\",\n)\n\ncolumns_to_convert = list(x.columns)\nx = pd.concat([x, x.add_suffix(\"SizeBytes\")], axis=1)\n\nx[\"TotalSize\"] = x[columns_to_convert].sum(axis=1).apply(sizeof_fmt)\n\nfor c in columns_to_convert:\n x[c] = x[c].apply(sizeof_fmt)\n\nx.columns.name, x.index.name = None, None\nprint(x.reset_index())\n\nPrints:\n ID CustomerName Backup Database Site BackupSizeBytes DatabaseSizeBytes SiteSizeBytes TotalSize\n0 1 CustomerA 199.6 MiB 199.6 MiB 199.6 MiB 209335296 209335296 209335296 598.9 MiB\n1 2 CustomerB 199.6 MiB 199.6 MiB 199.6 MiB 209335296 209335296 209335296 598.9 MiB\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"pandas",
"pivot",
"python"
] |
stackoverflow_0074512819_pandas_pivot_python.txt
|
Q:
How to get raw value of the QuerySet
I'm trying to return the raw value "Alberto Santos", but in my HTML, the function returns a array. <QuerySet [<Funcionarios: Alberto Santos>]>
My function "funcionarios_nome"
class ListaFuncionariosView(ListView):
model = Funcionarios
template_name = '../templates/funcionarios/lista_funcionarios.html'
paginate_by = 10
ordering = ['FuncionarioCartao']
queryset = Funcionarios.objects.filter(EmpresaCodigo=1)
def funcionarios_nome(self):
funcionarios = Funcionarios.objects.filter(FuncionarioNome='Alberto Santos')
return funcionarios
MY HTML
<p>{{ view.funcionarios_nome }}</p>
I Tried to use .values() function, but i'dont know how to use
A:
if you are passing data from views to template , it's recommend to use a context
useful links :
What is a context in Django?
If you expect a queryset to already return one row, you can use get() without any arguments to return the object for that row:
ex:
Funcionarios.objects.filter(EmpresaCodigo=1).get()
source : https://docs.djangoproject.com/en/4.1/ref/models/querysets/#get
|
How to get raw value of the QuerySet
|
I'm trying to return the raw value "Alberto Santos", but in my HTML, the function returns a array. <QuerySet [<Funcionarios: Alberto Santos>]>
My function "funcionarios_nome"
class ListaFuncionariosView(ListView):
model = Funcionarios
template_name = '../templates/funcionarios/lista_funcionarios.html'
paginate_by = 10
ordering = ['FuncionarioCartao']
queryset = Funcionarios.objects.filter(EmpresaCodigo=1)
def funcionarios_nome(self):
funcionarios = Funcionarios.objects.filter(FuncionarioNome='Alberto Santos')
return funcionarios
MY HTML
<p>{{ view.funcionarios_nome }}</p>
I Tried to use .values() function, but i'dont know how to use
|
[
"if you are passing data from views to template , it's recommend to use a context\nuseful links :\nWhat is a context in Django?\nIf you expect a queryset to already return one row, you can use get() without any arguments to return the object for that row:\nex:\n Funcionarios.objects.filter(EmpresaCodigo=1).get()\n\nsource : https://docs.djangoproject.com/en/4.1/ref/models/querysets/#get\n"
] |
[
2
] |
[] |
[] |
[
"django",
"django_views",
"python"
] |
stackoverflow_0074512834_django_django_views_python.txt
|
Q:
Returning a subset of list and dictionaries, from a list of dictionaries
Im trying to return a subset of list of dictionaries, derived from a list of dictionaries.
Input:
dicts = [
{'name': 'Sam', 'age': 12},
{'name': 'Pete', 'age': 14},
{'name': 'Sarah', 'age': 16}
]
Im trying to get this output:
res = [
{'name': 'Sam'},
{'name': 'Pete'},
{'name': 'Sarah'}
]
So far i've been trying with this approach:
res = []
def new_dict(dicts):
for i in range(len(dicts)):
for k, v in dicts[i]:
if dicts[i][k] == 'name'
res.append(dicts[i][k] = v)
print(new_dict(dicts))
A:
With list comprehension you can do:
[{'name': x['name']} for x in dicts]
A:
The safer method (That won't fail if one of your dicts doesn't have a name value):
[{'name': x['name']} for x in dicts if 'name' in x]
|
Returning a subset of list and dictionaries, from a list of dictionaries
|
Im trying to return a subset of list of dictionaries, derived from a list of dictionaries.
Input:
dicts = [
{'name': 'Sam', 'age': 12},
{'name': 'Pete', 'age': 14},
{'name': 'Sarah', 'age': 16}
]
Im trying to get this output:
res = [
{'name': 'Sam'},
{'name': 'Pete'},
{'name': 'Sarah'}
]
So far i've been trying with this approach:
res = []
def new_dict(dicts):
for i in range(len(dicts)):
for k, v in dicts[i]:
if dicts[i][k] == 'name'
res.append(dicts[i][k] = v)
print(new_dict(dicts))
|
[
"With list comprehension you can do:\n[{'name': x['name']} for x in dicts]\n\n",
"The safer method (That won't fail if one of your dicts doesn't have a name value):\n[{'name': x['name']} for x in dicts if 'name' in x]\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074510706_pandas_python.txt
|
Q:
What is the use of python-dotenv?
Need an example and please explain me the purpose of python-dotenv.
I am kind of confused with the documentation.
A:
From the Github page:
Reads the key,value pair from .env and adds them to environment variable. It is great of managing app settings during development and in production using 12-factor principles.
Assuming you have created the .env file along-side your settings module.
.
├── .env
└── settings.py
Add the following code to your settings.py:
# settings.py
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
SECRET_KEY = os.environ.get("SECRET_KEY")
DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD")
.env is a simple text file with each environment variable listed one per line, in the format of KEY="Value". The lines starting with # are ignored.
SOME_VAR=someval
# I am a comment and that is OK
FOO="BAR"
A:
In addition to @Will's answer, the python-dotenv module comes with a find_dotenv() that will try to find the .env file.
# settings.py
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
SECRET_KEY = os.environ.get("SECRET_KEY")
DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD")
A:
You could set the env variables like this:
export PRIVATE_KEY=0X32323
and then read it with os module.
import os
private_key=os.getenv("PRIVATE_KEY")
But this way, environment variable works only for the duration that shell is live. If you close the shell and restart it, you have to set environmental variable again. python-dotenv prevents us from doing this repetitive work.For this create .env file and add variables in this format
PRIVATE_KEY=fb6b05d6e75a93e30e22334443379292ccd29f5d815ad93a86ee23e749227
then in the file u want to access anv variables
import os
from dotenv import load_dotenv
#default directory for .env file is the current directory
#if you set .env in different directory, put the directory address load_dotenv("directory_of_.env)
load_dotenv()
load_dotenv() will set the environment variables from .env and we access with os module
private_key=os.getenv("PRIVATE_KEY")
A:
Just to add to @cannin, if you want to specify the which file you want to find:
from dotenv import find_dotenv
from dotenv import load_dotenv
env_file = find_dotenv(".env.dev")
load_dotenv(env_file)
A:
To be honest, the whole thing with dotenv utilities is a real mystery to me. I must certainly be in the minority that still doesn't get it, because after all the tutorials I still have a hard time finding a use case for them.
This is how I typically work with .env in Python. Given a "foobar" project, the .env file (actually a symlink to ~/.envs/foobar/dev) may look something like this:
set -a
PROJECT=foobar
DB_NAME=foobar
DB_PASSWORD=5ecret
CACHE_ENABLED=
DEBUG=yes
LOG=/tmp/foobar.log
...
set +a
When I source this, all variables between set -a and set +a are exported to the environment.
$ cd ~/projects/foobar
$ ln -s ~/.envs/foobar/dev .env
$ source .env
And voila! If I run python from the same shell, I can retrieve the environment and update my config with it:
import os
config.update(os.environ)
.env is made a symlink to ~/.envs/foobar/dev as an added precaution to listing it in .gititgnore. If for whatever reasons the file were to be checked in the VC repo, its contents would just show that it's a link to another file.
Also, being essentially a bash compatible script, one file can include and extend (or override) another. For instance, you could have sibling configurations ~/.envs/foobar/{base,dev,alt}:
# ~/.envs/foobar/alt
# import the common base
source ~/.envs/foobar/base
# override
DB_NAME="altdb"
set -a
# extend
EMAIL=admin@example.org
set +a
The above doesn't seem too overwhelming or cumbersome to me and I can't quite justify the use of python-dotenv for myself. The library is a nice enough solution, I just fail to see the real problem.
|
What is the use of python-dotenv?
|
Need an example and please explain me the purpose of python-dotenv.
I am kind of confused with the documentation.
|
[
"From the Github page:\n\nReads the key,value pair from .env and adds them to environment variable. It is great of managing app settings during development and in production using 12-factor principles.\n\nAssuming you have created the .env file along-side your settings module.\n.\n├── .env\n└── settings.py\n\nAdd the following code to your settings.py:\n# settings.py\nimport os\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\nSECRET_KEY = os.environ.get(\"SECRET_KEY\")\nDATABASE_PASSWORD = os.environ.get(\"DATABASE_PASSWORD\")\n\n.env is a simple text file with each environment variable listed one per line, in the format of KEY=\"Value\". The lines starting with # are ignored.\nSOME_VAR=someval\n# I am a comment and that is OK\nFOO=\"BAR\"\n\n",
"In addition to @Will's answer, the python-dotenv module comes with a find_dotenv() that will try to find the .env file.\n# settings.py\nimport os\nfrom dotenv import load_dotenv, find_dotenv\n\nload_dotenv(find_dotenv())\n\nSECRET_KEY = os.environ.get(\"SECRET_KEY\")\nDATABASE_PASSWORD = os.environ.get(\"DATABASE_PASSWORD\")\n\n",
"You could set the env variables like this:\n export PRIVATE_KEY=0X32323\n\nand then read it with os module.\nimport os\n\nprivate_key=os.getenv(\"PRIVATE_KEY\")\n\nBut this way, environment variable works only for the duration that shell is live. If you close the shell and restart it, you have to set environmental variable again. python-dotenv prevents us from doing this repetitive work.For this create .env file and add variables in this format\n PRIVATE_KEY=fb6b05d6e75a93e30e22334443379292ccd29f5d815ad93a86ee23e749227\n\nthen in the file u want to access anv variables\nimport os\nfrom dotenv import load_dotenv \n\n#default directory for .env file is the current directory\n#if you set .env in different directory, put the directory address load_dotenv(\"directory_of_.env)\nload_dotenv()\n\nload_dotenv() will set the environment variables from .env and we access with os module\n private_key=os.getenv(\"PRIVATE_KEY\")\n\n",
"Just to add to @cannin, if you want to specify the which file you want to find:\nfrom dotenv import find_dotenv\nfrom dotenv import load_dotenv\n\nenv_file = find_dotenv(\".env.dev\")\nload_dotenv(env_file)\n\n",
"To be honest, the whole thing with dotenv utilities is a real mystery to me. I must certainly be in the minority that still doesn't get it, because after all the tutorials I still have a hard time finding a use case for them.\nThis is how I typically work with .env in Python. Given a \"foobar\" project, the .env file (actually a symlink to ~/.envs/foobar/dev) may look something like this:\nset -a\n\nPROJECT=foobar\nDB_NAME=foobar\nDB_PASSWORD=5ecret\nCACHE_ENABLED=\nDEBUG=yes\nLOG=/tmp/foobar.log\n...\n\nset +a\n\nWhen I source this, all variables between set -a and set +a are exported to the environment.\n$ cd ~/projects/foobar\n$ ln -s ~/.envs/foobar/dev .env\n$ source .env\n\nAnd voila! If I run python from the same shell, I can retrieve the environment and update my config with it:\nimport os\nconfig.update(os.environ)\n\n.env is made a symlink to ~/.envs/foobar/dev as an added precaution to listing it in .gititgnore. If for whatever reasons the file were to be checked in the VC repo, its contents would just show that it's a link to another file.\nAlso, being essentially a bash compatible script, one file can include and extend (or override) another. For instance, you could have sibling configurations ~/.envs/foobar/{base,dev,alt}:\n# ~/.envs/foobar/alt\n\n# import the common base\nsource ~/.envs/foobar/base\n\n# override\nDB_NAME=\"altdb\"\n\nset -a\n\n# extend\nEMAIL=admin@example.org\n\nset +a\n\nThe above doesn't seem too overwhelming or cumbersome to me and I can't quite justify the use of python-dotenv for myself. The library is a nice enough solution, I just fail to see the real problem.\n"
] |
[
211,
68,
9,
0,
0
] |
[] |
[] |
[
"environment_variables",
"python"
] |
stackoverflow_0041546883_environment_variables_python.txt
|
Q:
Dropping rows based on a string in a table
Code to drop rows based on a partial string is not working.
Very simple code, and it runs fine but doesn't drop the rows I want.
The original table in the pdf looks like this:
Chemical
Value
Unit
Type
Fluoride
0.23
ug/L
Lab
Mercury
0.15
ug/L
Lab
Sum of Long Chained Polymers
0.33
Partialsum of Short Chained Polymers
0.40
What I did:
import csv
import tabula
dfs = tabula.read _pdf("Test.pdf", pages= 'all')
file = "Test.pdf"
tables = tabula.read_pdf(file, pages=2, stream=True, multiple_tables=True)
table1 = tables[1]
table1.drop('Unit', axis=1, inplace=True)
table1.drop('Type', axis=1, inplace=True)
discard = ['sum','Sum']
table1[~table1.Chemical.str.contains('|'.join(discard))]
print(table1)
table1.to_csv('test.csv')
The results are that it drops the 2 columns I don't want, so that's fine. But it did not delete the rows with the words "sum" or "Sum" in them. Any insights?
A:
You are close. You did drop the rows, but you didn't save the result.
import pandas as pd
example = {'Chemical': ['Fluoride', 'Mercury', 'Sum of Long Chained Polymers',
'Partialsum of Short Chained Polymers'],
'Value': [0.23, 0.15, 0.33, 0.4],
'Unit': ['ug/L', 'ug/L', '', ''],
'Type': ['Lab', 'Lab', '', '']}
table1 = pd.DataFrame(example)
table1.drop('Unit', axis=1, inplace=True)
table1.drop('Type', axis=1, inplace=True)
discard = ['sum','Sum']
table1 = table1[~table1.Chemical.str.contains('|'.join(discard))]
print(table1)
A:
You can use pd.Series.str.contains with the argument case=False to ignore case:
Also, it's not law, but often considered poor practice to use inplace=True... because in part it leads to confusions like the one you're experiencing.
Given df:
Chemical Value Unit Type
0 Fluoride 0.23 ug/L Lab
1 Mercury 0.15 ug/L Lab
2 Sum of Long Chained Polymers 0.33 NaN NaN
3 Partialsum of Short Chained Polymers 0.40 NaN NaN
Doing:
df = (df.drop(['Unit', 'Type'], axis=1)
.loc[~df.Chemical.str.contains('sum', case=False)])
Output:
Chemical Value
0 Fluoride 0.23
1 Mercury 0.15
|
Dropping rows based on a string in a table
|
Code to drop rows based on a partial string is not working.
Very simple code, and it runs fine but doesn't drop the rows I want.
The original table in the pdf looks like this:
Chemical
Value
Unit
Type
Fluoride
0.23
ug/L
Lab
Mercury
0.15
ug/L
Lab
Sum of Long Chained Polymers
0.33
Partialsum of Short Chained Polymers
0.40
What I did:
import csv
import tabula
dfs = tabula.read _pdf("Test.pdf", pages= 'all')
file = "Test.pdf"
tables = tabula.read_pdf(file, pages=2, stream=True, multiple_tables=True)
table1 = tables[1]
table1.drop('Unit', axis=1, inplace=True)
table1.drop('Type', axis=1, inplace=True)
discard = ['sum','Sum']
table1[~table1.Chemical.str.contains('|'.join(discard))]
print(table1)
table1.to_csv('test.csv')
The results are that it drops the 2 columns I don't want, so that's fine. But it did not delete the rows with the words "sum" or "Sum" in them. Any insights?
|
[
"You are close. You did drop the rows, but you didn't save the result.\nimport pandas as pd\n\nexample = {'Chemical': ['Fluoride', 'Mercury', 'Sum of Long Chained Polymers',\n 'Partialsum of Short Chained Polymers'], \n 'Value': [0.23, 0.15, 0.33, 0.4], \n 'Unit': ['ug/L', 'ug/L', '', ''], \n 'Type': ['Lab', 'Lab', '', '']}\n\ntable1 = pd.DataFrame(example)\ntable1.drop('Unit', axis=1, inplace=True)\ntable1.drop('Type', axis=1, inplace=True)\ndiscard = ['sum','Sum']\ntable1 = table1[~table1.Chemical.str.contains('|'.join(discard))]\nprint(table1)\n\n",
"You can use pd.Series.str.contains with the argument case=False to ignore case:\nAlso, it's not law, but often considered poor practice to use inplace=True... because in part it leads to confusions like the one you're experiencing.\nGiven df:\n Chemical Value Unit Type\n0 Fluoride 0.23 ug/L Lab\n1 Mercury 0.15 ug/L Lab\n2 Sum of Long Chained Polymers 0.33 NaN NaN\n3 Partialsum of Short Chained Polymers 0.40 NaN NaN\n\nDoing:\ndf = (df.drop(['Unit', 'Type'], axis=1)\n .loc[~df.Chemical.str.contains('sum', case=False)])\n\nOutput:\n Chemical Value\n0 Fluoride 0.23\n1 Mercury 0.15\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"pdf",
"python",
"tabula"
] |
stackoverflow_0074510620_dataframe_pandas_pdf_python_tabula.txt
|
Q:
Extracting duplicates from a list of dictionaries in Python
I have a huge list of dictionaries (I have shortened it here for clarity), where some values are duplicates (let's assume 'ID' is my target). How can I print the dictionary/ies where the ID occurs more than once?
[{'ID': 2501,
'First Name': 'Edward',
'Last Name': 'Crawford',
'Email': 'c.crawford@randatmail.com',
'Location': '[1.24564352 0.94323637]',
'Registration': '12/12/2000',
'Phone': '398-2890-30'},
{'ID': 3390936,
'First Name': 'Pepe',
'Last Name': 'Slim',
'Email': 'pepe.slim@somemail.com',
'Location': '[1.7297525 0.54631239]',
'Registration': '3/8/2020',
'Phone': '341-3456-85'}]
I have only been able to print certain values from the list of dict, but unable to parse through and identify duplicates.
all_phone = [i['Phone'] for i in comments]
all_email = [i['Email'] for i in comments]
A:
I'd suggest constructing a helper function where you have the flexibility of choosing the field that you're looking for duplicates in. Incorporating an intermediate dictionary (such as that from @Andrej Kesely's answer) is an efficient way of searching for duplicates, and this can be generalized in a function. In this case I've used a simple dictionary rather than Counter from the collections library.
def find_duplicates(dicts, field):
counts = {}
for d in dicts:
counts[d[field]] = counts.get(d[field], 0) + 1
return [d for d in dicts if counts[d[field]]>1]
phone_duplicates = find_duplicates(comments, 'Phone')
A:
You can use collections.Counter to create a counter where keys will be IDs from your dictionary. Then you can filter your list according this counter:
lst = [
{
"ID": 2501,
"First Name": "Edward",
"Last Name": "Crawford",
"Email": "c.crawford@randatmail.com",
"Location": "[1.24564352 0.94323637]",
"Registration": "12/12/2000",
"Phone": "398-2890-30",
},
{
"ID": 3390936,
"First Name": "Pepe",
"Last Name": "Slim",
"Email": "pepe.slim@somemail.com",
"Location": "[1.7297525 0.54631239]",
"Registration": "3/8/2020",
"Phone": "341-3456-85",
},
# duplicate ID here:
{
"ID": 2501,
"First Name": "XXX",
"Last Name": "XXX",
},
]
from collections import Counter
# create a counter:
c = Counter(d["ID"] for d in lst)
# print duplicated dictionaries:
for d in lst:
if c[d["ID"]] > 1:
print(d)
prints:
{
"ID": 2501,
"First Name": "Edward",
"Last Name": "Crawford",
"Email": "c.crawford@randatmail.com",
"Location": "[1.24564352 0.94323637]",
"Registration": "12/12/2000",
"Phone": "398-2890-30",
}
{"ID": 2501, "First Name": "XXX", "Last Name": "XXX"}
A:
You could loop through the list and create a new dictionary as you go and catch when you run into a duplicate
if key not in d:
d[key] = value
else:
# you have a duplicate
A:
Using a list comprehension:
comments=[{'ID': 1111,
'First Name': 'foo1',
'Last Name': 'bar1'},
{'ID': 2222,
'First Name': 'foo2',
'Last Name': 'bar2'},
{'ID': 1111,
'First Name': 'foo3',
'Last Name': 'bar3'},
{'ID': 3333,
'First Name': 'foo4',
'Last Name': 'bar4'},
{'ID': 2222,
'First Name': 'foo5',
'Last Name': 'bar5'},]
all_ID = [i['ID'] for i in comments]
Duplicates =list(set([x for x in all_ID if all_ID.count(x) > 1]))
print("Duplicates found! =>", Duplicates )
Output:
Duplicates found! => [2222, 1111]
|
Extracting duplicates from a list of dictionaries in Python
|
I have a huge list of dictionaries (I have shortened it here for clarity), where some values are duplicates (let's assume 'ID' is my target). How can I print the dictionary/ies where the ID occurs more than once?
[{'ID': 2501,
'First Name': 'Edward',
'Last Name': 'Crawford',
'Email': 'c.crawford@randatmail.com',
'Location': '[1.24564352 0.94323637]',
'Registration': '12/12/2000',
'Phone': '398-2890-30'},
{'ID': 3390936,
'First Name': 'Pepe',
'Last Name': 'Slim',
'Email': 'pepe.slim@somemail.com',
'Location': '[1.7297525 0.54631239]',
'Registration': '3/8/2020',
'Phone': '341-3456-85'}]
I have only been able to print certain values from the list of dict, but unable to parse through and identify duplicates.
all_phone = [i['Phone'] for i in comments]
all_email = [i['Email'] for i in comments]
|
[
"I'd suggest constructing a helper function where you have the flexibility of choosing the field that you're looking for duplicates in. Incorporating an intermediate dictionary (such as that from @Andrej Kesely's answer) is an efficient way of searching for duplicates, and this can be generalized in a function. In this case I've used a simple dictionary rather than Counter from the collections library.\ndef find_duplicates(dicts, field):\n counts = {}\n for d in dicts:\n counts[d[field]] = counts.get(d[field], 0) + 1\n return [d for d in dicts if counts[d[field]]>1]\n\nphone_duplicates = find_duplicates(comments, 'Phone')\n\n",
"You can use collections.Counter to create a counter where keys will be IDs from your dictionary. Then you can filter your list according this counter:\nlst = [\n {\n \"ID\": 2501,\n \"First Name\": \"Edward\",\n \"Last Name\": \"Crawford\",\n \"Email\": \"c.crawford@randatmail.com\",\n \"Location\": \"[1.24564352 0.94323637]\",\n \"Registration\": \"12/12/2000\",\n \"Phone\": \"398-2890-30\",\n },\n {\n \"ID\": 3390936,\n \"First Name\": \"Pepe\",\n \"Last Name\": \"Slim\",\n \"Email\": \"pepe.slim@somemail.com\",\n \"Location\": \"[1.7297525 0.54631239]\",\n \"Registration\": \"3/8/2020\",\n \"Phone\": \"341-3456-85\",\n },\n # duplicate ID here:\n {\n \"ID\": 2501,\n \"First Name\": \"XXX\",\n \"Last Name\": \"XXX\",\n },\n]\n\nfrom collections import Counter\n\n# create a counter:\nc = Counter(d[\"ID\"] for d in lst)\n\n# print duplicated dictionaries:\nfor d in lst:\n if c[d[\"ID\"]] > 1:\n print(d)\n\nprints:\n{\n \"ID\": 2501,\n \"First Name\": \"Edward\",\n \"Last Name\": \"Crawford\",\n \"Email\": \"c.crawford@randatmail.com\",\n \"Location\": \"[1.24564352 0.94323637]\",\n \"Registration\": \"12/12/2000\",\n \"Phone\": \"398-2890-30\",\n}\n{\"ID\": 2501, \"First Name\": \"XXX\", \"Last Name\": \"XXX\"}\n\n",
"You could loop through the list and create a new dictionary as you go and catch when you run into a duplicate\nif key not in d:\n d[key] = value\nelse:\n # you have a duplicate\n\n",
"Using a list comprehension:\ncomments=[{'ID': 1111,\n 'First Name': 'foo1',\n 'Last Name': 'bar1'},\n {'ID': 2222,\n 'First Name': 'foo2',\n 'Last Name': 'bar2'},\n {'ID': 1111,\n 'First Name': 'foo3',\n 'Last Name': 'bar3'},\n {'ID': 3333,\n 'First Name': 'foo4',\n 'Last Name': 'bar4'},\n {'ID': 2222,\n 'First Name': 'foo5',\n 'Last Name': 'bar5'},]\n \nall_ID = [i['ID'] for i in comments]\n\nDuplicates =list(set([x for x in all_ID if all_ID.count(x) > 1]))\n \nprint(\"Duplicates found! =>\", Duplicates )\n\nOutput:\nDuplicates found! => [2222, 1111]\n\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"dictionary",
"list_comprehension",
"python"
] |
stackoverflow_0074512771_dictionary_list_comprehension_python.txt
|
Q:
Read excel autofilter with python
I'd like to read the autofilter rules from an excel sheet in python.
Suppose this kind of input:
original input
then I filter with excel autofilter one column, for example:
filtered input
Is there a way to retrieve the applied autofilter rule in python?
Currently the only option I know, it is to set the autofilter via xlwings:
import xlwings as xw
# Open the workbook
workbook = xw.Book(r"C:\Users\Desktop\Example.xlsx")
# Set Autofilter
workbook.sheets[0].api.Range("A1:D4").AutoFilter(4,"Yes")
but does it exist the "inverse" function?
It could be fine also with other way like pandas, openpyxl, xlsxwriter and so on.
A:
With Xlwings you should be able to duplicate what VBA can do so it's usually the better for this type of query.
You should be able to show the Filter set from Criteria1 as shown below;
import xlwings as xw
# Open the workbook
workbook = xw.Book(r"C:\Users\Desktop\Example.xlsx")
# Set Autofilter
workbook.sheets[0].api.Range("A1:D4").AutoFilter(4,"Yes")
for count, item in enumerate(workbook.sheets[0].api.AutoFilter.Filters,1):
if item.On:
print(f'{count}, {item.Criteria1}')
Output would be
4, =Yes
|
Read excel autofilter with python
|
I'd like to read the autofilter rules from an excel sheet in python.
Suppose this kind of input:
original input
then I filter with excel autofilter one column, for example:
filtered input
Is there a way to retrieve the applied autofilter rule in python?
Currently the only option I know, it is to set the autofilter via xlwings:
import xlwings as xw
# Open the workbook
workbook = xw.Book(r"C:\Users\Desktop\Example.xlsx")
# Set Autofilter
workbook.sheets[0].api.Range("A1:D4").AutoFilter(4,"Yes")
but does it exist the "inverse" function?
It could be fine also with other way like pandas, openpyxl, xlsxwriter and so on.
|
[
"With Xlwings you should be able to duplicate what VBA can do so it's usually the better for this type of query.\nYou should be able to show the Filter set from Criteria1 as shown below;\nimport xlwings as xw\n\n# Open the workbook\nworkbook = xw.Book(r\"C:\\Users\\Desktop\\Example.xlsx\")\n\n# Set Autofilter\nworkbook.sheets[0].api.Range(\"A1:D4\").AutoFilter(4,\"Yes\")\n\nfor count, item in enumerate(workbook.sheets[0].api.AutoFilter.Filters,1):\n if item.On:\n print(f'{count}, {item.Criteria1}')\n\nOutput would be \n4, =Yes\n\n"
] |
[
0
] |
[] |
[] |
[
"excel",
"filter",
"pandas",
"python",
"xlwings"
] |
stackoverflow_0074510217_excel_filter_pandas_python_xlwings.txt
|
Q:
How can I make it loop properly?
It won't work when trying to loop so it can restart at the end when asked.
def inputPass(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
def inputDefer(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
def inputFail(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
Pass = inputPass("Enter how many passes you got")
if((Pass) != 0 and (Pass != 20) and (Pass != 40) and (Pass != 60) and (Pass != 80) and (Pass != 100) and ( Pass != 120)):
print("Out of range")
exit()
Defer = inputDefer("Enter how many defers you got")
if ((Defer != 0) and (Defer != 20) and (Defer != 40) and (Defer != 60) and (Defer != 80) and (Defer != 100) and (Defer != 120)):
print("out of range")
exit()
Fail = inputFail("Enter how many fails you got")
if ((Fail != 0) and (Fail != 20) and (Fail != 40) and (Fail != 60) and (Fail != 80) and (Fail != 100) and (Fail != 120)):
print("out of range")
exit()
PDF = (Pass + Defer + Fail)
if PDF != 120:
print("Total incorrect")
exit()
if Pass == 120:
print ("Progress")
elif Pass == 100:
print("Progress (module trailer)")
elif Fail >= 80:
print("Exclude")
else:
print("Do not progress – module retriever")
I tried using a while loop and a function so I can recall back to it but it won't do so and I don't know why.
A:
Its kind of difficult to answer since your question is very unclear. You have a lot of repeated code which can be tided up. If the code below doesnt answer your question hopefully it puts you on the right track to solve your problem. If your still struggling please update the question with more clear details.
VAL_RANGES = [0, 20, 40, 60, 80, 100, 120]
def get_input(result: str) -> int:
while True:
try:
val = int(input(f"Enter how many {result} you got? {VAL_RANGES}:"))
if val in VAL_RANGES:
return val
print("out of range")
except ValueError:
print("Not an integer! Try again.")
while True:
Pass = get_input("passes")
Defer = get_input("defers")
Fail = get_input("fails")
PDF = Pass + Defer + Fail
if Pass == 120:
print("Progress")
elif Pass == 100:
print("Progress (module trailer)")
elif Fail >= 80:
print("Exclude")
else:
print("Do not progress – module retriever")
if input("Finished? (Y/N):").upper() == "Y":
break
OUTPUT
Enter how many passes you got? [0, 20, 40, 60, 80, 100, 120]:5
out of range
Enter how many passes you got? [0, 20, 40, 60, 80, 100, 120]:120
Enter how many defers you got? [0, 20, 40, 60, 80, 100, 120]:40
Enter how many fails you got? [0, 20, 40, 60, 80, 100, 120]:20
Progress
Finished? (Y/N):n
Enter how many passes you got? [0, 20, 40, 60, 80, 100, 120]:120
Enter how many defers you got? [0, 20, 40, 60, 80, 100, 120]:0
Enter how many fails you got? [0, 20, 40, 60, 80, 100, 120]:0
Progress
Finished? (Y/N):y
Process finished with exit code 0
|
How can I make it loop properly?
|
It won't work when trying to loop so it can restart at the end when asked.
def inputPass(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
def inputDefer(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
def inputFail(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
Pass = inputPass("Enter how many passes you got")
if((Pass) != 0 and (Pass != 20) and (Pass != 40) and (Pass != 60) and (Pass != 80) and (Pass != 100) and ( Pass != 120)):
print("Out of range")
exit()
Defer = inputDefer("Enter how many defers you got")
if ((Defer != 0) and (Defer != 20) and (Defer != 40) and (Defer != 60) and (Defer != 80) and (Defer != 100) and (Defer != 120)):
print("out of range")
exit()
Fail = inputFail("Enter how many fails you got")
if ((Fail != 0) and (Fail != 20) and (Fail != 40) and (Fail != 60) and (Fail != 80) and (Fail != 100) and (Fail != 120)):
print("out of range")
exit()
PDF = (Pass + Defer + Fail)
if PDF != 120:
print("Total incorrect")
exit()
if Pass == 120:
print ("Progress")
elif Pass == 100:
print("Progress (module trailer)")
elif Fail >= 80:
print("Exclude")
else:
print("Do not progress – module retriever")
I tried using a while loop and a function so I can recall back to it but it won't do so and I don't know why.
|
[
"Its kind of difficult to answer since your question is very unclear. You have a lot of repeated code which can be tided up. If the code below doesnt answer your question hopefully it puts you on the right track to solve your problem. If your still struggling please update the question with more clear details.\nVAL_RANGES = [0, 20, 40, 60, 80, 100, 120]\n\n\ndef get_input(result: str) -> int:\n while True:\n try:\n val = int(input(f\"Enter how many {result} you got? {VAL_RANGES}:\"))\n if val in VAL_RANGES:\n return val\n print(\"out of range\")\n except ValueError:\n print(\"Not an integer! Try again.\")\n\n\nwhile True:\n Pass = get_input(\"passes\")\n Defer = get_input(\"defers\")\n Fail = get_input(\"fails\")\n PDF = Pass + Defer + Fail\n\n if Pass == 120:\n print(\"Progress\")\n elif Pass == 100:\n print(\"Progress (module trailer)\")\n elif Fail >= 80:\n print(\"Exclude\")\n else:\n print(\"Do not progress – module retriever\")\n\n if input(\"Finished? (Y/N):\").upper() == \"Y\":\n break\n\nOUTPUT\nEnter how many passes you got? [0, 20, 40, 60, 80, 100, 120]:5\nout of range\nEnter how many passes you got? [0, 20, 40, 60, 80, 100, 120]:120\nEnter how many defers you got? [0, 20, 40, 60, 80, 100, 120]:40\nEnter how many fails you got? [0, 20, 40, 60, 80, 100, 120]:20\nProgress\nFinished? (Y/N):n\nEnter how many passes you got? [0, 20, 40, 60, 80, 100, 120]:120\nEnter how many defers you got? [0, 20, 40, 60, 80, 100, 120]:0\nEnter how many fails you got? [0, 20, 40, 60, 80, 100, 120]:0\nProgress\nFinished? (Y/N):y\n\nProcess finished with exit code 0\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074512984_python_python_3.x.txt
|
Q:
how to merge pd.to_json file and dictionary?
this is the transformed json file that using pd.to_json
and this is dictionary format
I want these two looks like this
I forced to merge those with like
print('['+str(dict({'Message1':'Hello','Message2':'word'}))+','+df1[1:])
but the java won't accept this format. Maybe I have to send the format with pd.to_json..
A:
Use pd.DataFrame.to_dict not pd.DataFrame.to_json, then it's simply a matter of:
print([{'Message1':'Hello','Message2':'word'}, *df.to_dict('records')])
Or if it's very particular about the output:
import json
d = {'Message1':'Hello','Message2':'word'}
out = [d, *df.to_dict('records')]
print(json.dumps(out))
|
how to merge pd.to_json file and dictionary?
|
this is the transformed json file that using pd.to_json
and this is dictionary format
I want these two looks like this
I forced to merge those with like
print('['+str(dict({'Message1':'Hello','Message2':'word'}))+','+df1[1:])
but the java won't accept this format. Maybe I have to send the format with pd.to_json..
|
[
"Use pd.DataFrame.to_dict not pd.DataFrame.to_json, then it's simply a matter of:\nprint([{'Message1':'Hello','Message2':'word'}, *df.to_dict('records')])\n\nOr if it's very particular about the output:\nimport json\n\nd = {'Message1':'Hello','Message2':'word'}\n\nout = [d, *df.to_dict('records')]\nprint(json.dumps(out))\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074513071_python.txt
|
Q:
How to execute python file inside another with specific parameters?
In terminal I would type something close to:
python main.py --something-something parameter1 --something- parameter2
Because that's how the program works. I need to run main.py in another python script but also need to have "--something-something parameter1 --something- parameter2" as part of it.
I have already looked What is the best way to call a script from another script? [closed] and some others but they did not answer to my problem.
Is this possible with importing os?
Lets say the parameter 2 is ID and its value is integer 1234 and parameter 1 dog is "dachshund".
I tried something close to:
dog = "dachshund"
ID = 1234
os.system("python main.py --something-something {dog} --something- {ID}")
But obviously it did not work and there must the right way to do this and there may even be better ways than using os.system(). Thanks in advance!
A:
Create the string you will use first
pythonCall = 'python main.py --something-something {} --something- {}'.format(dog, ID)
os.system(pythonCall)
|
How to execute python file inside another with specific parameters?
|
In terminal I would type something close to:
python main.py --something-something parameter1 --something- parameter2
Because that's how the program works. I need to run main.py in another python script but also need to have "--something-something parameter1 --something- parameter2" as part of it.
I have already looked What is the best way to call a script from another script? [closed] and some others but they did not answer to my problem.
Is this possible with importing os?
Lets say the parameter 2 is ID and its value is integer 1234 and parameter 1 dog is "dachshund".
I tried something close to:
dog = "dachshund"
ID = 1234
os.system("python main.py --something-something {dog} --something- {ID}")
But obviously it did not work and there must the right way to do this and there may even be better ways than using os.system(). Thanks in advance!
|
[
"Create the string you will use first\npythonCall = 'python main.py --something-something {} --something- {}'.format(dog, ID)\nos.system(pythonCall)\n\n"
] |
[
0
] |
[] |
[] |
[
"parameters",
"python",
"terminal"
] |
stackoverflow_0074513189_parameters_python_terminal.txt
|
Q:
Looking For Simple Python Scraping Help: Having Trouble Identifying Sections and Class with BeautifulSoup
I am trying to learn how to scrape data. I am very new to Python, so bare with me.
Upon searching YouTube, I found a tutorial and tried to scrape some data off of "https://www.pgatour.com/competition/2022/hero-world-challenge/leaderboard.html"
from bs4 import BeautifulSoup
import requests
SCRAPE = requests.get("https://www.pgatour.com/competition/2022/hero-world-challenge/leaderboard.html")
print(SCRAPE)
#Response [200] = Succesful...
#http response status codes
#Information Responses 100-199
#Successful 200-299
#Redirects 300-399
#Client Errors 400-499
#Server Errors 500-599
soup = BeautifulSoup(SCRAPE.content, 'html.parser')
#tells that the data is html and we need to parse it
table = soup.find_all('div', class_="leaderboard leaderboard-table large" )
#pick the large section that contains all the info you need
#then, pick each smaller section, find the type and class.
for list in table:
name = list.find('div', class_="player-name-col")
position = list.find('td', class_="position")
total = list.find('td', class_="total")
print(name, position, total)
Above is my code.. I also included pictures with the inspect open so I can show you what I was thinking when I tried to find the type and class within the leaderboard.
When I print, nothing happens. Any help is appreciated!
A:
Data is loaded dynamically by JavaScript and bs4 can't render JS that's why your code is printing nothing but you can pull the required data from API.
Example:
import pandas as pd
import requests
api_url= 'https://lbdata.pgatour.com/2022/r/478/leaderboard.json?userTrackingId=eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Njg5OTEzNTcsIm5iZiI6MTY2ODk5MTM1NywiZXhwIjoxNjY4OTkzMTU3fQ.eTvZpdJgVp5yzSQz4J8n8ovzaBnKPmLhZm6gfitKJeU'
headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
data=[]
res=requests.get(api_url,headers=headers)
#print(res)
for item in res.json()['rows']:
startRanks = item['total']
data.append({'total':startRanks})
df= pd.DataFrame(data)
print(df)
Output:
total
0 -18
1 -17
2 -15
3 -15
4 -14
5 -14
6 -13
7 -13
8 -11
9 -11
10 -11
11 -10
12 -10
13 -8
14 -8
15 -8
16 -7
17 -6
18 +1
19 +6
|
Looking For Simple Python Scraping Help: Having Trouble Identifying Sections and Class with BeautifulSoup
|
I am trying to learn how to scrape data. I am very new to Python, so bare with me.
Upon searching YouTube, I found a tutorial and tried to scrape some data off of "https://www.pgatour.com/competition/2022/hero-world-challenge/leaderboard.html"
from bs4 import BeautifulSoup
import requests
SCRAPE = requests.get("https://www.pgatour.com/competition/2022/hero-world-challenge/leaderboard.html")
print(SCRAPE)
#Response [200] = Succesful...
#http response status codes
#Information Responses 100-199
#Successful 200-299
#Redirects 300-399
#Client Errors 400-499
#Server Errors 500-599
soup = BeautifulSoup(SCRAPE.content, 'html.parser')
#tells that the data is html and we need to parse it
table = soup.find_all('div', class_="leaderboard leaderboard-table large" )
#pick the large section that contains all the info you need
#then, pick each smaller section, find the type and class.
for list in table:
name = list.find('div', class_="player-name-col")
position = list.find('td', class_="position")
total = list.find('td', class_="total")
print(name, position, total)
Above is my code.. I also included pictures with the inspect open so I can show you what I was thinking when I tried to find the type and class within the leaderboard.
When I print, nothing happens. Any help is appreciated!
|
[
"Data is loaded dynamically by JavaScript and bs4 can't render JS that's why your code is printing nothing but you can pull the required data from API.\nExample:\nimport pandas as pd\nimport requests\n\napi_url= 'https://lbdata.pgatour.com/2022/r/478/leaderboard.json?userTrackingId=eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Njg5OTEzNTcsIm5iZiI6MTY2ODk5MTM1NywiZXhwIjoxNjY4OTkzMTU3fQ.eTvZpdJgVp5yzSQz4J8n8ovzaBnKPmLhZm6gfitKJeU'\nheaders={\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'\n }\ndata=[]\n\nres=requests.get(api_url,headers=headers)\n#print(res)\nfor item in res.json()['rows']:\n startRanks = item['total']\n data.append({'total':startRanks})\n\ndf= pd.DataFrame(data)\nprint(df)\n\nOutput:\n total\n0 -18\n1 -17\n2 -15\n3 -15\n4 -14\n5 -14\n6 -13\n7 -13\n8 -11\n9 -11\n10 -11\n11 -10\n12 -10\n13 -8\n14 -8\n15 -8\n16 -7\n17 -6\n18 +1\n19 +6\n\n"
] |
[
1
] |
[] |
[] |
[
"beautifulsoup",
"pandas",
"python",
"web_scraping"
] |
stackoverflow_0074513130_beautifulsoup_pandas_python_web_scraping.txt
|
Q:
Why do I get None in output in second line while using eval function?
I am executing this line of code -
print(eval("print(2 +3)"))
but this instead of giving output as 5 gives output-
5
None
A:
When you try to get eval of something like
eval("2")
you are actually going to get type int.
But trying to evaluate print expression gives you None type. Print will be executed but type of
eval("print(2+3)")
will be None.
A:
This is because you are giving eval() within print().
eval("(2 +3)")
This will return 5 as the function eval returns the value 5 which gets printed using the print()
But,
print(eval("(2 +3)"))
Here inside the eval() you have used print(). So the inner print() prints the value 5 and the function eval() returns None as it has nothing to return. That None gets printed by the outer print()
A:
print() sometimes prints single None or None after value.
For don't print the None need to use define function.
May be your question was from Hackerrank.
I had a problem today.
And it is my answer.
def ev(expression):
return eval(expression)
ev(input())
|
Why do I get None in output in second line while using eval function?
|
I am executing this line of code -
print(eval("print(2 +3)"))
but this instead of giving output as 5 gives output-
5
None
|
[
"When you try to get eval of something like\neval(\"2\")\nyou are actually going to get type int.\nBut trying to evaluate print expression gives you None type. Print will be executed but type of\neval(\"print(2+3)\")\nwill be None.\n",
"This is because you are giving eval() within print().\neval(\"(2 +3)\")\n\nThis will return 5 as the function eval returns the value 5 which gets printed using the print()\nBut,\nprint(eval(\"(2 +3)\"))\n\nHere inside the eval() you have used print(). So the inner print() prints the value 5 and the function eval() returns None as it has nothing to return. That None gets printed by the outer print()\n",
"print() sometimes prints single None or None after value.\nFor don't print the None need to use define function.\nMay be your question was from Hackerrank.\nI had a problem today.\nAnd it is my answer.\ndef ev(expression):\n return eval(expression)\nev(input())\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"eval",
"function",
"python",
"python_3.x"
] |
stackoverflow_0066901984_eval_function_python_python_3.x.txt
|
Q:
How would I convert a format string with quotes into an f-string with nested quotes?
I've seen this question but I think I have more nested quotes and it's doing my head in.
How would I convert the following line into an f-string?
file.write('python -c "{code}"'.format(code="open('test.txt', 'w');"))
A:
There's barely anything to do here:
code="open('test.txt', 'w');"
file.write(f'python -c "{code}"')
You can of course also put the value of the variable in the f-string, but that would be silly:
file.write(f'python -c "{"open(\'test.txt\', \'w\');"}"')
Because replacing a string with a string is just, you know, inserting a string, no string formatting needed
file.write('python -c "open(\'test.txt\', \'w\');"')
|
How would I convert a format string with quotes into an f-string with nested quotes?
|
I've seen this question but I think I have more nested quotes and it's doing my head in.
How would I convert the following line into an f-string?
file.write('python -c "{code}"'.format(code="open('test.txt', 'w');"))
|
[
"There's barely anything to do here:\ncode=\"open('test.txt', 'w');\"\nfile.write(f'python -c \"{code}\"')\n\nYou can of course also put the value of the variable in the f-string, but that would be silly:\nfile.write(f'python -c \"{\"open(\\'test.txt\\', \\'w\\');\"}\"')\n\nBecause replacing a string with a string is just, you know, inserting a string, no string formatting needed\nfile.write('python -c \"open(\\'test.txt\\', \\'w\\');\"')\n\n"
] |
[
1
] |
[] |
[] |
[
"f_string",
"python"
] |
stackoverflow_0074513205_f_string_python.txt
|
Q:
Why is appending my list of tuples changing their content?
I am trying to make a list of tuples that contain a string and a dictionary. The string is a filename and the dictionary is a frequency list of n-grams.
('story.txt',
{'back': 12,
'been': 13,
'bees': 58,
'buzz': 13,
'cant': 30,
'come': 12,
'dont': 64,
'down': 16,
'from': 22,
...})
For what I'm doing, I want to make a list of these tuples that would look something like
[('story.txt',
{'back': 12,
'been': 13,
'bees': 58,
'buzz': 13,
'cant': 30,
'come': 12,
'dont': 64,
'down': 16,
'from': 22,
...}),
('great_expectations.txt',
{'_he_': 12,
'able': 32,
'aged': 54,
'aint': 56,
'also': 34,
'arms': 44,
'away': 158,
'baby': 23,
...})
]
I'm trying to do that with the following code:
documents = ['story.txt', 'great_expectations.txt']
outputs = []
for document in documents:
doc_map = map_maker.make_map(document, 4, 10)
list_tuple = (document, doc_map)
# pprint.pprint(list_tuple)
outputs.append(list_tuple)
# pprint.pprint(outputs)
For some reason, the code above is combining the data from the dictionaries before appending them, such that the 'story.txt' dictionary will have entries originally associated with 'great_expectations.txt' and vise-versa, like this:
[('story.txt',
{'_he_': 12,
'able': 32,
'aged': 54,
'aint': 56,
'also': 34,
'arms': 44,
'away': 158,
'baby': 23,
'back': 238,
...}),
('great_expectations.txt',
{'_he_': 12,
'able': 32,
'aged': 54,
'aint': 56,
'also': 34,
'arms': 44,
'away': 158,
'baby': 23,
'back': 238,
...})
]
Why is it doing this? I thought tuples were supposed to be immutable.
A:
There is no problem with code you presented, I speculate that you left hard coded file name somewhere in map_maker.make_map or you reusing result variable doc_map inside make_map (it's static or member of map_maker, beware of default arguments for mutable types in python)
|
Why is appending my list of tuples changing their content?
|
I am trying to make a list of tuples that contain a string and a dictionary. The string is a filename and the dictionary is a frequency list of n-grams.
('story.txt',
{'back': 12,
'been': 13,
'bees': 58,
'buzz': 13,
'cant': 30,
'come': 12,
'dont': 64,
'down': 16,
'from': 22,
...})
For what I'm doing, I want to make a list of these tuples that would look something like
[('story.txt',
{'back': 12,
'been': 13,
'bees': 58,
'buzz': 13,
'cant': 30,
'come': 12,
'dont': 64,
'down': 16,
'from': 22,
...}),
('great_expectations.txt',
{'_he_': 12,
'able': 32,
'aged': 54,
'aint': 56,
'also': 34,
'arms': 44,
'away': 158,
'baby': 23,
...})
]
I'm trying to do that with the following code:
documents = ['story.txt', 'great_expectations.txt']
outputs = []
for document in documents:
doc_map = map_maker.make_map(document, 4, 10)
list_tuple = (document, doc_map)
# pprint.pprint(list_tuple)
outputs.append(list_tuple)
# pprint.pprint(outputs)
For some reason, the code above is combining the data from the dictionaries before appending them, such that the 'story.txt' dictionary will have entries originally associated with 'great_expectations.txt' and vise-versa, like this:
[('story.txt',
{'_he_': 12,
'able': 32,
'aged': 54,
'aint': 56,
'also': 34,
'arms': 44,
'away': 158,
'baby': 23,
'back': 238,
...}),
('great_expectations.txt',
{'_he_': 12,
'able': 32,
'aged': 54,
'aint': 56,
'also': 34,
'arms': 44,
'away': 158,
'baby': 23,
'back': 238,
...})
]
Why is it doing this? I thought tuples were supposed to be immutable.
|
[
"There is no problem with code you presented, I speculate that you left hard coded file name somewhere in map_maker.make_map or you reusing result variable doc_map inside make_map (it's static or member of map_maker, beware of default arguments for mutable types in python)\n"
] |
[
0
] |
[] |
[] |
[
"dictionary",
"list",
"n_gram",
"python"
] |
stackoverflow_0074513202_dictionary_list_n_gram_python.txt
|
Q:
VsCode/Python in console: file not found
In my workingdirectory I have many folders with a python script modifying data in the same folder.
When running Python in VsCode I need to give a relative path from the working directory into the folder. For example using os.getcwd(), test.py is in D:\Workingdirectory\Folder1: VsCode says, D:\Workingdirectory. Running it in console: D:\Workingdirectory\Folder1.
Direct path is not an option.
How fo i fix it?
Thanks in advance!
A:
This is caused by vscode using workspace as root floder.
This will lead to a problem. When you use the os.getcwd() method in the deep directory of the workspace, you will still get the workspace directory.
You can open your settings and search Python > Terminal: Execute In File Dir then check it.
You can also use debug mode and add the following to your launch.json:
"cwd": "${fileDirname}"
|
VsCode/Python in console: file not found
|
In my workingdirectory I have many folders with a python script modifying data in the same folder.
When running Python in VsCode I need to give a relative path from the working directory into the folder. For example using os.getcwd(), test.py is in D:\Workingdirectory\Folder1: VsCode says, D:\Workingdirectory. Running it in console: D:\Workingdirectory\Folder1.
Direct path is not an option.
How fo i fix it?
Thanks in advance!
|
[
"This is caused by vscode using workspace as root floder.\nThis will lead to a problem. When you use the os.getcwd() method in the deep directory of the workspace, you will still get the workspace directory.\nYou can open your settings and search Python > Terminal: Execute In File Dir then check it.\n\nYou can also use debug mode and add the following to your launch.json:\n\"cwd\": \"${fileDirname}\"\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"visual_studio_code"
] |
stackoverflow_0074491233_python_visual_studio_code.txt
|
Q:
Running VBA code from Python: macros may be disabled
Trying to run an Excel macro via Python I get the following error:
Traceback (most recent call last):
File ".\test.py", line 17, in <module>
xlApp.Application.Run(MACRO)
File "<COMObject <unknown>>", line 14, in Run
File "C:\Users\twauchop\Desktop\Python\virtual_envs\gutenberg\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'test'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)
I tried many of the fixes suggested in other questions.
I tried 'xlApp.Application.Run(wb.name + "!" + MACRO)'.
Is this a naming convention issue? I enabled everything via Trust Center and changed the VBA sub to public.
As a side-note, I also cannot run macros from the programmatically opened workbook (i.e. if I try manually). If I open the workbook manually, however, everything is fine.
I am running Python 3.6.5 on a 64 bit system, Windows 10.
Python:
import win32com.client
import os
import traceback
DIRECTORY = r'C:\\Users\\twauchop\\Desktop\\Excel\\'
FILE = 'test.xlsb'
MACRO = 'test'
path = os.path.join(DIRECTORY, FILE)
if os.path.exists(path):
try:
xlApp = win32com.client.Dispatch('Excel.Application')
xlApp.DisplayAlerts = False
xlApp.Visible = True
wb = xlApp.Workbooks.Open(Filename=path, ReadOnly=1)
xlApp.Application.Run(MACRO)
wb.Close(SaveChanges=1)
xlApp.Application.Quit()
print('Code ran successfully.')
except:
print('An error was encountered; see traceback.')
print(traceback.format_exc())
xlApp.Quit()
VBA:
Public Sub test()
MsgBox "Hello World!"
End Sub
A:
xlApp.Application.AutomationSecurity=1 needs to go before ANY xlApp.Application.Run(excelMacroNameHere) code, as the AutomationSecurity is used to control (enable vs disable) macros and 1 means enable all macros.
|
Running VBA code from Python: macros may be disabled
|
Trying to run an Excel macro via Python I get the following error:
Traceback (most recent call last):
File ".\test.py", line 17, in <module>
xlApp.Application.Run(MACRO)
File "<COMObject <unknown>>", line 14, in Run
File "C:\Users\twauchop\Desktop\Python\virtual_envs\gutenberg\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'test'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)
I tried many of the fixes suggested in other questions.
I tried 'xlApp.Application.Run(wb.name + "!" + MACRO)'.
Is this a naming convention issue? I enabled everything via Trust Center and changed the VBA sub to public.
As a side-note, I also cannot run macros from the programmatically opened workbook (i.e. if I try manually). If I open the workbook manually, however, everything is fine.
I am running Python 3.6.5 on a 64 bit system, Windows 10.
Python:
import win32com.client
import os
import traceback
DIRECTORY = r'C:\\Users\\twauchop\\Desktop\\Excel\\'
FILE = 'test.xlsb'
MACRO = 'test'
path = os.path.join(DIRECTORY, FILE)
if os.path.exists(path):
try:
xlApp = win32com.client.Dispatch('Excel.Application')
xlApp.DisplayAlerts = False
xlApp.Visible = True
wb = xlApp.Workbooks.Open(Filename=path, ReadOnly=1)
xlApp.Application.Run(MACRO)
wb.Close(SaveChanges=1)
xlApp.Application.Quit()
print('Code ran successfully.')
except:
print('An error was encountered; see traceback.')
print(traceback.format_exc())
xlApp.Quit()
VBA:
Public Sub test()
MsgBox "Hello World!"
End Sub
|
[
"xlApp.Application.AutomationSecurity=1 needs to go before ANY xlApp.Application.Run(excelMacroNameHere) code, as the AutomationSecurity is used to control (enable vs disable) macros and 1 means enable all macros.\n"
] |
[
0
] |
[] |
[] |
[
"excel",
"python",
"vba",
"win32com"
] |
stackoverflow_0049972988_excel_python_vba_win32com.txt
|
Q:
Conda dependency range specifiction: ResolvePackageNotFound
I have an environment.yaml with this content (MWE)
name: the-env
dependencies:
- pandas>=1.5.0,<2.0.0
I run conda env create -f environment.yaml
I get
Collecting package metadata (repodata.json): done
Solving environment: failed
ResolvePackageNotFound:
- pandas[version='>=1.5.0,<2.0.0']
Why.
Docu is useless for my question... or I don't find the right section, and the answers to this questions also say this format is valid (I generate the actual environment.yaml with poetry2conda).
Was there a change? What is the correct range syntax?
btw I run conda 22.9.0.
A:
Currently, only Conda Forge provides any builds satisfying pandas>=1.5.0. So, the YAML should use:
name: the-env
channels:
- conda-forge
dependencies:
- pandas>=1.5.0,<2.0.0
"Should the latter not work if the former works...?"
pandas>=1.5.0,<2.0.0 is a subset of pandas<2.0.0, so the former being solvable entails that the latter will also be solvable (e.g., pandas=1.5.0 satisfies both), but the latter being solvable does not entail the former can be solved (e.g., pandas=1.4.0 only satifies <2.0.0).
|
Conda dependency range specifiction: ResolvePackageNotFound
|
I have an environment.yaml with this content (MWE)
name: the-env
dependencies:
- pandas>=1.5.0,<2.0.0
I run conda env create -f environment.yaml
I get
Collecting package metadata (repodata.json): done
Solving environment: failed
ResolvePackageNotFound:
- pandas[version='>=1.5.0,<2.0.0']
Why.
Docu is useless for my question... or I don't find the right section, and the answers to this questions also say this format is valid (I generate the actual environment.yaml with poetry2conda).
Was there a change? What is the correct range syntax?
btw I run conda 22.9.0.
|
[
"Currently, only Conda Forge provides any builds satisfying pandas>=1.5.0. So, the YAML should use:\nname: the-env\nchannels:\n - conda-forge\ndependencies:\n - pandas>=1.5.0,<2.0.0\n\n\n\"Should the latter not work if the former works...?\"\n\npandas>=1.5.0,<2.0.0 is a subset of pandas<2.0.0, so the former being solvable entails that the latter will also be solvable (e.g., pandas=1.5.0 satisfies both), but the latter being solvable does not entail the former can be solved (e.g., pandas=1.4.0 only satifies <2.0.0).\n"
] |
[
0
] |
[] |
[] |
[
"anaconda",
"conda",
"dependencies",
"environment",
"python"
] |
stackoverflow_0074406399_anaconda_conda_dependencies_environment_python.txt
|
Q:
Google Sheets API Wont Let Me Write Data into My Google Sheet
Code is below. this isnt the full code but the basis of it. Im trying to take data from Twitter's API and Write it to my Google Sheets API. Below is the Code.
from googleapiclient import discovery
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
SERVICE_ACCOUNT_FILE = 'twitter.json' #json File should be in the same folder as this Python Script.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1f4iqVHljytmRSC2EZcApEiA2lE1cHa1o6Fr4s3t0AKg'
#SAMPLE_RANGE_NAME = 'Class Data!A2:A60'
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
# Call the Sheets API
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range='twitterData!A1:A180').execute()
#ERROR HERE BELOW
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": 8}).execute()
the one Line im getting an Error for has the comment above it Error Below. and this is the Error Message:
Traceback (most recent call last):
File "C:\Users\John Doe\Desktop\Code\Python\Twitter\test.py", line 27, in <module>
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
File "C:\Users\John Doe\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\John Doe\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleapiclient\http.py", line 938, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1f4iqVHljytmRSC2EZcApEiA2lE1cHa1o6Fr4s3t0AKg/values/twitterData%21B2%3AB180?valueInputOption=USER_ENTERED&alt=json returned "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'data.values', 'description': "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8"}]}]">
Ive used Google Sheets API before. Im not sure why this code isnt working. Its just that one line.
A:
I think that the reason for your current issue of "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8" is due to body={"values": 8}. In this case, it is required to use a 2-dimensional array. So, please modify it as follows.
From:
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": 8}).execute()
To:
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID, range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": [[8]]}).execute()
In this modification, body={"values": 8} is modified to body={"values": [[8]]}.
By this modification, 8 is put to the cell "B2" of "twitterData" sheet.
Reference:
Method: spreadsheets.values.update
|
Google Sheets API Wont Let Me Write Data into My Google Sheet
|
Code is below. this isnt the full code but the basis of it. Im trying to take data from Twitter's API and Write it to my Google Sheets API. Below is the Code.
from googleapiclient import discovery
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
SERVICE_ACCOUNT_FILE = 'twitter.json' #json File should be in the same folder as this Python Script.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1f4iqVHljytmRSC2EZcApEiA2lE1cHa1o6Fr4s3t0AKg'
#SAMPLE_RANGE_NAME = 'Class Data!A2:A60'
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
# Call the Sheets API
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range='twitterData!A1:A180').execute()
#ERROR HERE BELOW
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": 8}).execute()
the one Line im getting an Error for has the comment above it Error Below. and this is the Error Message:
Traceback (most recent call last):
File "C:\Users\John Doe\Desktop\Code\Python\Twitter\test.py", line 27, in <module>
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
File "C:\Users\John Doe\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\John Doe\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleapiclient\http.py", line 938, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1f4iqVHljytmRSC2EZcApEiA2lE1cHa1o6Fr4s3t0AKg/values/twitterData%21B2%3AB180?valueInputOption=USER_ENTERED&alt=json returned "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'data.values', 'description': "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8"}]}]">
Ive used Google Sheets API before. Im not sure why this code isnt working. Its just that one line.
|
[
"I think that the reason for your current issue of \"Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8\" is due to body={\"values\": 8}. In this case, it is required to use a 2-dimensional array. So, please modify it as follows.\nFrom:\nrequest = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,\n range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={\"values\": 8}).execute()\n\nTo:\nrequest = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID, range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={\"values\": [[8]]}).execute()\n\n\nIn this modification, body={\"values\": 8} is modified to body={\"values\": [[8]]}.\nBy this modification, 8 is put to the cell \"B2\" of \"twitterData\" sheet.\n\nReference:\n\nMethod: spreadsheets.values.update\n\n"
] |
[
0
] |
[] |
[] |
[
"google_cloud_platform",
"google_sheets",
"google_sheets_api",
"python"
] |
stackoverflow_0074511522_google_cloud_platform_google_sheets_google_sheets_api_python.txt
|
Q:
Beautiful Soup data extract
Have an local .html from which I am extracting point data, parsed with BeautifulSoup but I don't know how to extract the date that is inside a div, the parse array is the following:
<div class="_a6-p"><div><div><a href="https://www.instagram.com/chuckbasspics" target="_blank">chuckbasspics</a></div><div>Jan 7, 2013, 5:41 AM</div></div></div><div class="_3-94 _a6-o"></div></div><div class="pam _3-95 _2ph- _a6-g uiBoxWhite noborder"><div class="_a6-p"><div><div>
Any idea how to do it?
I already extracted the users and urls (href) with the following code:
fl_html = open('followers.html', "r")
index = fl_html.read()
soup = BeautifulSoup(index, 'lxml')
usernames = soup.find_all('a', href=True)
for i in usernames:
users.append(i.get_text(strip=True))
url_follower.append(i['href'])
A:
You can use bs4 API or CSS selector:
from bs4 import BeautifulSoup
html_doc = """<div class="_a6-p"><div><div><a href="https://www.instagram.com/chuckbasspics" target="_blank">chuckbasspics</a></div><div>Jan 7, 2013, 5:41 AM</div></div></div><div class="_3-94 _a6-o"></div></div><div class="pam _3-95 _2ph- _a6-g uiBoxWhite noborder"><div class="_a6-p"><div><div>"""
soup = BeautifulSoup(html_doc, "html.parser")
Extracting the date using .get_text() with separator=
You can get all text from the HTML snippet with custom separator, then .split:
t = soup.get_text(strip=True, separator="|").split("|")
print(t[1])
Prints:
Jan 7, 2013, 5:41 AM
CSS selector
Find next sibling to <div> which contains <a>:
t = soup.select_one("div:has(a) + div")
print(t.text)
Print:
Jan 7, 2013, 5:41 AM
Using bs4 API
Time must contain PM or AM, so select <div> which contains this string:
t = soup.find("div", text=lambda t: t and (" AM" in t or " PM" in t))
print(t.text)
Prints:
Jan 7, 2013, 5:41 AM
|
Beautiful Soup data extract
|
Have an local .html from which I am extracting point data, parsed with BeautifulSoup but I don't know how to extract the date that is inside a div, the parse array is the following:
<div class="_a6-p"><div><div><a href="https://www.instagram.com/chuckbasspics" target="_blank">chuckbasspics</a></div><div>Jan 7, 2013, 5:41 AM</div></div></div><div class="_3-94 _a6-o"></div></div><div class="pam _3-95 _2ph- _a6-g uiBoxWhite noborder"><div class="_a6-p"><div><div>
Any idea how to do it?
I already extracted the users and urls (href) with the following code:
fl_html = open('followers.html', "r")
index = fl_html.read()
soup = BeautifulSoup(index, 'lxml')
usernames = soup.find_all('a', href=True)
for i in usernames:
users.append(i.get_text(strip=True))
url_follower.append(i['href'])
|
[
"You can use bs4 API or CSS selector:\nfrom bs4 import BeautifulSoup\n\nhtml_doc = \"\"\"<div class=\"_a6-p\"><div><div><a href=\"https://www.instagram.com/chuckbasspics\" target=\"_blank\">chuckbasspics</a></div><div>Jan 7, 2013, 5:41 AM</div></div></div><div class=\"_3-94 _a6-o\"></div></div><div class=\"pam _3-95 _2ph- _a6-g uiBoxWhite noborder\"><div class=\"_a6-p\"><div><div>\"\"\"\n\nsoup = BeautifulSoup(html_doc, \"html.parser\")\n\nExtracting the date using .get_text() with separator=\nYou can get all text from the HTML snippet with custom separator, then .split:\nt = soup.get_text(strip=True, separator=\"|\").split(\"|\")\nprint(t[1])\n\nPrints:\nJan 7, 2013, 5:41 AM\n\nCSS selector\nFind next sibling to <div> which contains <a>:\nt = soup.select_one(\"div:has(a) + div\")\nprint(t.text)\n\nPrint:\nJan 7, 2013, 5:41 AM\n\nUsing bs4 API\nTime must contain PM or AM, so select <div> which contains this string:\nt = soup.find(\"div\", text=lambda t: t and (\" AM\" in t or \" PM\" in t))\nprint(t.text)\n\nPrints:\nJan 7, 2013, 5:41 AM\n\n"
] |
[
0
] |
[] |
[] |
[
"beautifulsoup",
"html",
"python"
] |
stackoverflow_0074513306_beautifulsoup_html_python.txt
|
Q:
Udacity Self Driving Car Simulator
I am working on Udacity's self-driving car simulator. I am facing a problem in this when I run the drive.py file with my model as argument model.h5 nothing happens in the simulator.
The model has been trained completely without any errors but still, there is no response from the simulator.
Here is the drive.py python code and a link to the video to show what is actually happening
drive.py
import argparse
import base64
from datetime import datetime
import os
import shutil
import numpy as np
import socketio
import eventlet
import eventlet.wsgi
from PIL import Image
from flask import Flask
from io import BytesIO
from keras.models import load_model
import h5py
from keras import __version__ as keras_version
sio = socketio.Server()
app = Flask(__name__)
model = None
prev_image_array = None
class SimplePIController:
def __init__(self, Kp, Ki):
self.Kp = Kp
self.Ki = Ki
self.set_point = 0.
self.error = 0.
self.integral = 0.
def set_desired(self, desired):
self.set_point = desired
def update(self, measurement):
# proportional error
self.error = self.set_point - measurement
# integral error
self.integral += self.error
return self.Kp * self.error + self.Ki * self.integral
controller = SimplePIController(0.1, 0.002)
set_speed = 30
controller.set_desired(set_speed)
def crop_image(img, img_height=75, img_width=200):
height = img.shape[0]
width = img.shape[1]
y_start = 60
#x_start = int(width/2)-int(img_width/2)
return img[y_start:y_start+img_height, 0:width ]#x_start:x_start+img_width]
@sio.on('telemetry')
def telemetry(sid, data):
if data:
# The current steering angle of the car
steering_angle = data["steering_angle"]
# The current throttle of the car
throttle = data["throttle"]
# The current speed of the car
speed = data["speed"]
# The current image from the center camera of the car
imgString = data["image"]
image = Image.open(BytesIO(base64.b64decode(imgString)))
image_array = np.asarray(image)
image_array = crop_image(image_array)
steering_angle = float(model.predict(image_array[None, :, :, :], batch_size=1))
throttle = controller.update(float(speed))
print(steering_angle, throttle)
send_control(steering_angle, throttle)
# save frame
if args.image_folder != '':
timestamp = datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3]
image_filename = os.path.join(args.image_folder, timestamp)
image.save('{}.jpg'.format(image_filename))
else:
# NOTE: DON'T EDIT THIS.
sio.emit('manual', data={}, skip_sid=True)
@sio.on('connect')
def connect(sid, environ):
print("connect ", sid)
send_control(0, 0)
def send_control(steering_angle, throttle):
sio.emit(
"steer",
data={
'steering_angle': steering_angle.__str__(),
'throttle': throttle.__str__()
},
skip_sid=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Remote Driving')
parser.add_argument(
'model',
type=str,
help='Path to model h5 file. Model should be on the same path.'
)
parser.add_argument(
'image_folder',
type=str,
nargs='?',
default='',
help='Path to image folder. This is where the images from the run will be saved.'
)
args = parser.parse_args()
# check that model Keras version is same as local Keras version
f = h5py.File(args.model, mode='r')
model_version = f.attrs.get('keras_version')
keras_version = str(keras_version).encode('utf8')
if model_version != keras_version:
print('You are using Keras version ', keras_version,
', but the model was built using ', model_version)
model = load_model(args.model)
if args.image_folder != '':
print("Creating image folder at {}".format(args.image_folder))
if not os.path.exists(args.image_folder):
os.makedirs(args.image_folder)
else:
shutil.rmtree(args.image_folder)
os.makedirs(args.image_folder)
print("RECORDING THIS RUN ...")
else:
print("NOT RECORDING THIS RUN ...")
# wrap Flask application with engineio's middleware
app = socketio.Middleware(sio, app)
# deploy as an eventlet WSGI server
eventlet.wsgi.server(eventlet.listen(('', 4567)), app)
problem video link
https://youtu.be/nP8WH8pM29Q
A:
This is due to the socketio version. Use 4.2.1, that should fix your problem
|
Udacity Self Driving Car Simulator
|
I am working on Udacity's self-driving car simulator. I am facing a problem in this when I run the drive.py file with my model as argument model.h5 nothing happens in the simulator.
The model has been trained completely without any errors but still, there is no response from the simulator.
Here is the drive.py python code and a link to the video to show what is actually happening
drive.py
import argparse
import base64
from datetime import datetime
import os
import shutil
import numpy as np
import socketio
import eventlet
import eventlet.wsgi
from PIL import Image
from flask import Flask
from io import BytesIO
from keras.models import load_model
import h5py
from keras import __version__ as keras_version
sio = socketio.Server()
app = Flask(__name__)
model = None
prev_image_array = None
class SimplePIController:
def __init__(self, Kp, Ki):
self.Kp = Kp
self.Ki = Ki
self.set_point = 0.
self.error = 0.
self.integral = 0.
def set_desired(self, desired):
self.set_point = desired
def update(self, measurement):
# proportional error
self.error = self.set_point - measurement
# integral error
self.integral += self.error
return self.Kp * self.error + self.Ki * self.integral
controller = SimplePIController(0.1, 0.002)
set_speed = 30
controller.set_desired(set_speed)
def crop_image(img, img_height=75, img_width=200):
height = img.shape[0]
width = img.shape[1]
y_start = 60
#x_start = int(width/2)-int(img_width/2)
return img[y_start:y_start+img_height, 0:width ]#x_start:x_start+img_width]
@sio.on('telemetry')
def telemetry(sid, data):
if data:
# The current steering angle of the car
steering_angle = data["steering_angle"]
# The current throttle of the car
throttle = data["throttle"]
# The current speed of the car
speed = data["speed"]
# The current image from the center camera of the car
imgString = data["image"]
image = Image.open(BytesIO(base64.b64decode(imgString)))
image_array = np.asarray(image)
image_array = crop_image(image_array)
steering_angle = float(model.predict(image_array[None, :, :, :], batch_size=1))
throttle = controller.update(float(speed))
print(steering_angle, throttle)
send_control(steering_angle, throttle)
# save frame
if args.image_folder != '':
timestamp = datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3]
image_filename = os.path.join(args.image_folder, timestamp)
image.save('{}.jpg'.format(image_filename))
else:
# NOTE: DON'T EDIT THIS.
sio.emit('manual', data={}, skip_sid=True)
@sio.on('connect')
def connect(sid, environ):
print("connect ", sid)
send_control(0, 0)
def send_control(steering_angle, throttle):
sio.emit(
"steer",
data={
'steering_angle': steering_angle.__str__(),
'throttle': throttle.__str__()
},
skip_sid=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Remote Driving')
parser.add_argument(
'model',
type=str,
help='Path to model h5 file. Model should be on the same path.'
)
parser.add_argument(
'image_folder',
type=str,
nargs='?',
default='',
help='Path to image folder. This is where the images from the run will be saved.'
)
args = parser.parse_args()
# check that model Keras version is same as local Keras version
f = h5py.File(args.model, mode='r')
model_version = f.attrs.get('keras_version')
keras_version = str(keras_version).encode('utf8')
if model_version != keras_version:
print('You are using Keras version ', keras_version,
', but the model was built using ', model_version)
model = load_model(args.model)
if args.image_folder != '':
print("Creating image folder at {}".format(args.image_folder))
if not os.path.exists(args.image_folder):
os.makedirs(args.image_folder)
else:
shutil.rmtree(args.image_folder)
os.makedirs(args.image_folder)
print("RECORDING THIS RUN ...")
else:
print("NOT RECORDING THIS RUN ...")
# wrap Flask application with engineio's middleware
app = socketio.Middleware(sio, app)
# deploy as an eventlet WSGI server
eventlet.wsgi.server(eventlet.listen(('', 4567)), app)
problem video link
https://youtu.be/nP8WH8pM29Q
|
[
"This is due to the socketio version. Use 4.2.1, that should fix your problem\n"
] |
[
0
] |
[] |
[] |
[
"python",
"simulator"
] |
stackoverflow_0073705466_python_simulator.txt
|
Q:
Trying to dockerize Django app, Docker cannot find ft2build.h
I'm new to Docker and I'm trying to dockerize a Django app but when I run docker build -t sometag . I receive the following error:
#9 23.05 Preparing metadata (setup.py): started
#9 23.32 Preparing metadata (setup.py): finished with status 'error'
#9 23.33 error: subprocess-exited-with-error
#9 23.33
#9 23.33 × python setup.py egg_info did not run successfully.
#9 23.33 │ exit code: 1
#9 23.33 ╰─> [10 lines of output]
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: ================================================
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: Attempting build of _rl_accel
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: extensions from 'src/rl_addons/rl_accel'
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: ================================================
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: ===================================================
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: Attempting build of _renderPM
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: extensions from 'src/rl_addons/renderPM'
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: ===================================================
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: will use package libart 2.3.21
#9 23.33 !!!!! cannot find ft2build.h
#9 23.33 [end of output]
#9 23.33
#9 23.33 note: This error originates from a subprocess, and is likely not a problem with pip.
#9 23.33 error: metadata-generation-failed
#9 23.33
#9 23.33 × Encountered error while generating package metadata.
#9 23.33 ╰─> See above for output.
#9 23.33
#9 23.33 note: This is an issue with the package mentioned above, not pip.
#9 23.33 hint: See above for details.
------
executor failed running [/bin/sh -c pip install -r requirements.txt]: exit code: 1
I'm not sure if it is related to ft2build.h.I'm I missing something on my dockerfile?
This is my requirements.txt:
arabic-reshaper==2.1.3
asn1crypto==1.5.1
attrs==20.3.0
azure-core==1.23.1
azure-storage-blob==12.11.0
certifi==2021.10.8
cffi==1.15.0
charset-normalizer==2.0.12
click==8.1.2
colorama==0.4.4
cryptography==36.0.2
cssselect2==0.5.0
distlib==0.3.5
Django==4.0.3
django-crispy-forms==1.14.0
django-storages==1.12.3
djangorestframework==3.14.0
filelock==3.8.0
future==0.18.2
html5lib==1.1
idna==3.3
isodate==0.6.1
jellyfish==0.9.0
lib50==3.0.4
lxml==4.8.0
markdown2==2.4.2
msrest==0.6.21
oauthlib==3.2.0
oscrypto==1.3.0
pexpect==4.8.0
Pillow==9.1.0
platformdirs==2.5.2
psycopg2-binary==2.9.3
ptyprocess==0.7.0
pycparser==2.21
pyHanko==0.12.1
pyhanko-certvalidator==0.19.5
PyPDF2==1.27.3
PyPDF3==1.0.6
python-bidi==0.4.2
pytz==2022.1
PyYAML==5.4.1
qrcode==7.3.1
reportlab==3.6.9
requests==2.27.1
requests-oauthlib==1.3.1
six==1.16.0
submit50==3.1.1
svglib==1.2.1
termcolor==1.1.0
tinycss2==1.1.1
tk==0.1.0
tqdm==4.64.0
typing_extensions==4.1.1
tzdata==2022.1
tzlocal==4.2
uritools==4.0.0
urllib3==1.26.9
virtualenv==20.16.3
webencodings==0.5.1
whitenoise==6.0.0
xhtml2pdf==0.2.7
Note: I had to remove the dockerfile as Stackoverflow wouldn't allow me to publish so much code but I'm running this RUN apk update \&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev \&& pip install --upgrade pip
A:
I'm not sure if it is related to ft2build.h.I'm I missing something on my dockerfile?
To solve the problem with the error ft2build.h. in the compile process, you need the freetype library installed
I assume you are using the last version of Alpine, and I can see you can install pip packages without problems.
As a result, the missing part should be the freetype-dev package to install.
RUN apk update \
&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev freetype-dev\
|
Trying to dockerize Django app, Docker cannot find ft2build.h
|
I'm new to Docker and I'm trying to dockerize a Django app but when I run docker build -t sometag . I receive the following error:
#9 23.05 Preparing metadata (setup.py): started
#9 23.32 Preparing metadata (setup.py): finished with status 'error'
#9 23.33 error: subprocess-exited-with-error
#9 23.33
#9 23.33 × python setup.py egg_info did not run successfully.
#9 23.33 │ exit code: 1
#9 23.33 ╰─> [10 lines of output]
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: ================================================
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: Attempting build of _rl_accel
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: extensions from 'src/rl_addons/rl_accel'
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: ================================================
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: ===================================================
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: Attempting build of _renderPM
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: extensions from 'src/rl_addons/renderPM'
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: ===================================================
#9 23.33 ##### setup-python-3.10.8-linux-x86_64: will use package libart 2.3.21
#9 23.33 !!!!! cannot find ft2build.h
#9 23.33 [end of output]
#9 23.33
#9 23.33 note: This error originates from a subprocess, and is likely not a problem with pip.
#9 23.33 error: metadata-generation-failed
#9 23.33
#9 23.33 × Encountered error while generating package metadata.
#9 23.33 ╰─> See above for output.
#9 23.33
#9 23.33 note: This is an issue with the package mentioned above, not pip.
#9 23.33 hint: See above for details.
------
executor failed running [/bin/sh -c pip install -r requirements.txt]: exit code: 1
I'm not sure if it is related to ft2build.h.I'm I missing something on my dockerfile?
This is my requirements.txt:
arabic-reshaper==2.1.3
asn1crypto==1.5.1
attrs==20.3.0
azure-core==1.23.1
azure-storage-blob==12.11.0
certifi==2021.10.8
cffi==1.15.0
charset-normalizer==2.0.12
click==8.1.2
colorama==0.4.4
cryptography==36.0.2
cssselect2==0.5.0
distlib==0.3.5
Django==4.0.3
django-crispy-forms==1.14.0
django-storages==1.12.3
djangorestframework==3.14.0
filelock==3.8.0
future==0.18.2
html5lib==1.1
idna==3.3
isodate==0.6.1
jellyfish==0.9.0
lib50==3.0.4
lxml==4.8.0
markdown2==2.4.2
msrest==0.6.21
oauthlib==3.2.0
oscrypto==1.3.0
pexpect==4.8.0
Pillow==9.1.0
platformdirs==2.5.2
psycopg2-binary==2.9.3
ptyprocess==0.7.0
pycparser==2.21
pyHanko==0.12.1
pyhanko-certvalidator==0.19.5
PyPDF2==1.27.3
PyPDF3==1.0.6
python-bidi==0.4.2
pytz==2022.1
PyYAML==5.4.1
qrcode==7.3.1
reportlab==3.6.9
requests==2.27.1
requests-oauthlib==1.3.1
six==1.16.0
submit50==3.1.1
svglib==1.2.1
termcolor==1.1.0
tinycss2==1.1.1
tk==0.1.0
tqdm==4.64.0
typing_extensions==4.1.1
tzdata==2022.1
tzlocal==4.2
uritools==4.0.0
urllib3==1.26.9
virtualenv==20.16.3
webencodings==0.5.1
whitenoise==6.0.0
xhtml2pdf==0.2.7
Note: I had to remove the dockerfile as Stackoverflow wouldn't allow me to publish so much code but I'm running this RUN apk update \&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev \&& pip install --upgrade pip
|
[
"\nI'm not sure if it is related to ft2build.h.I'm I missing something on my dockerfile?\n\nTo solve the problem with the error ft2build.h. in the compile process, you need the freetype library installed\nI assume you are using the last version of Alpine, and I can see you can install pip packages without problems.\nAs a result, the missing part should be the freetype-dev package to install.\nRUN apk update \\ \n && apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev freetype-dev\\\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"docker",
"python"
] |
stackoverflow_0074512564_django_docker_python.txt
|
Q:
How to add new rows to a dataframe based on ranges of two columns in the same dataframe?
I have a dataframe that summarizes the segments of track within a bigger network. These segments have specific segement_ids and it looks like this:
import pandas as pd
import numpy as np
my_dict = {
'segment_id':['a', 'b', 'c', 'd', 'e'],
'km_start':[2,4,9,15,20],
'km_end':[3,7,11,16,22],
'min_km_start':[0,0,0,0,0],
'max_km_end':[25,25,25,25,25]
}
df = pd.DataFrame(my_dict)
segment_id km_start km_end min_km_start max_km_end
0 a 2 3 0 25
1 b 4 7 0 25
2 c 9 11 0 25
3 d 15 16 0 25
4 e 20 22 0 25
Graphically, I want to do the following:
Inessence, I need to find the gaps between the two pairs of columns (['km_start','km_end'] and ['min_km_start','max_km_end']) and fill in the segement_id in a descending order starting from -1.
Here is the desired output:
segment_id km_start km_end min_km_start max_km_end
0 -1 0 2 0 25
1 a 2 3 0 25
2 -2 3 4 0 25
3 b 4 7 0 25
4 -3 7 9 0 25
5 c 9 11 0 25
6 -4 11 15 0 25
7 d 15 16 0 25
8 -5 16 20 0 25
9 e 20 22 0 25
10 -6 22 25 0 25
A:
Try this
starts = pd.concat([pd.Series(df['min_km_start'].iloc[0]), df['km_end']]).reset_index(drop=True)
ends = pd.concat([df['km_start'], pd.Series(df['max_km_end'].iloc[0])]).reset_index(drop=True)
mask = ~starts.isin(df['km_start'])
pd.concat([df, pd.DataFrame({'km_start': starts[mask], 'km_end': ends[mask], 'segment_id': np.arange(-1,-mask.sum()-1,-1)})]).fillna(method='ffill').sort_values(by='km_start').reset_index(drop=True)
Output
segment_id km_start km_end min_km_start max_km_end
0 -1 0 2 0.0 25.0
1 a 2 3 0.0 25.0
2 -2 3 4 0.0 25.0
3 b 4 7 0.0 25.0
4 -3 7 9 0.0 25.0
5 c 9 11 0.0 25.0
6 -4 11 15 0.0 25.0
7 d 15 16 0.0 25.0
8 -5 16 20 0.0 25.0
9 e 20 22 0.0 25.0
10 -6 22 25 0.0 25.0
|
How to add new rows to a dataframe based on ranges of two columns in the same dataframe?
|
I have a dataframe that summarizes the segments of track within a bigger network. These segments have specific segement_ids and it looks like this:
import pandas as pd
import numpy as np
my_dict = {
'segment_id':['a', 'b', 'c', 'd', 'e'],
'km_start':[2,4,9,15,20],
'km_end':[3,7,11,16,22],
'min_km_start':[0,0,0,0,0],
'max_km_end':[25,25,25,25,25]
}
df = pd.DataFrame(my_dict)
segment_id km_start km_end min_km_start max_km_end
0 a 2 3 0 25
1 b 4 7 0 25
2 c 9 11 0 25
3 d 15 16 0 25
4 e 20 22 0 25
Graphically, I want to do the following:
Inessence, I need to find the gaps between the two pairs of columns (['km_start','km_end'] and ['min_km_start','max_km_end']) and fill in the segement_id in a descending order starting from -1.
Here is the desired output:
segment_id km_start km_end min_km_start max_km_end
0 -1 0 2 0 25
1 a 2 3 0 25
2 -2 3 4 0 25
3 b 4 7 0 25
4 -3 7 9 0 25
5 c 9 11 0 25
6 -4 11 15 0 25
7 d 15 16 0 25
8 -5 16 20 0 25
9 e 20 22 0 25
10 -6 22 25 0 25
|
[
"Try this\nstarts = pd.concat([pd.Series(df['min_km_start'].iloc[0]), df['km_end']]).reset_index(drop=True)\nends = pd.concat([df['km_start'], pd.Series(df['max_km_end'].iloc[0])]).reset_index(drop=True)\nmask = ~starts.isin(df['km_start'])\npd.concat([df, pd.DataFrame({'km_start': starts[mask], 'km_end': ends[mask], 'segment_id': np.arange(-1,-mask.sum()-1,-1)})]).fillna(method='ffill').sort_values(by='km_start').reset_index(drop=True)\n\nOutput\n segment_id km_start km_end min_km_start max_km_end\n0 -1 0 2 0.0 25.0\n1 a 2 3 0.0 25.0\n2 -2 3 4 0.0 25.0\n3 b 4 7 0.0 25.0\n4 -3 7 9 0.0 25.0\n5 c 9 11 0.0 25.0\n6 -4 11 15 0.0 25.0\n7 d 15 16 0.0 25.0\n8 -5 16 20 0.0 25.0\n9 e 20 22 0.0 25.0\n10 -6 22 25 0.0 25.0\n\n"
] |
[
2
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074513220_pandas_python.txt
|
Q:
Why does VSCode Python always put two tabs instead of one?
In my VSCode settings, I have Tab Size set to 2 and in Prettier I have it set to 2 spaces as well. It works fine, whenever I go to the next line, it indents by 1 tab (2 spaces) and whenever I press tab it places a tab where my cursor was. But when I save my file, all of the single tabs for indenting turn into 2 tabs. Here is an image from after saving: image. And yes, I am making a Discord Bot.
I saved my file and I expected it to look like this
A:
I want to indent using tabs but when I save it indents with 2 tabs and that's annoying
Click the Select Indentation option in the lower right corner.
Choose Indent Using Tabs
Choose 2.
You can also change the settings by searching tab size:
|
Why does VSCode Python always put two tabs instead of one?
|
In my VSCode settings, I have Tab Size set to 2 and in Prettier I have it set to 2 spaces as well. It works fine, whenever I go to the next line, it indents by 1 tab (2 spaces) and whenever I press tab it places a tab where my cursor was. But when I save my file, all of the single tabs for indenting turn into 2 tabs. Here is an image from after saving: image. And yes, I am making a Discord Bot.
I saved my file and I expected it to look like this
|
[
"\nI want to indent using tabs but when I save it indents with 2 tabs and that's annoying\n\n\n\nClick the Select Indentation option in the lower right corner.\n\n\n\nChoose Indent Using Tabs\n\n\n\nChoose 2.\n\nYou can also change the settings by searching tab size:\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x",
"save",
"visual_studio_code"
] |
stackoverflow_0074502151_python_python_3.x_save_visual_studio_code.txt
|
Q:
Weighted Mean Squared Error in TensorFlow
I created a neural network for Quickest Detection.
The input is a list of 10 observation and the output is the change time predicted.
I want to modify the Probability of false alarms using a Weighted MSE.
I created this neural network:
model = k.Sequential(\[
k.layers.Dense(window_size, activation = k.activations.relu, input_shape=\[window_size\]),
k.layers.Dense(window_size, activation = k.activations.relu),
k.layers.Dense(window_size, activation = k.activations.relu),
k.layers.Dense(window_size, activation = k.activations.relu),
k.layers.Dense(1, activation = k.activations.relu),
\])
model.compile(optimizer = 'Adam', loss = 'mse')
\#training
history = model.fit(x = X, y=y, epochs = 50)
I have to modify this model introducing a weighted MSE that prevent False Alarms
(a false alarms occurs when value predicted - true label < 0).
How can I implement it?
A:
You can achieve this by creating a custom loss function:
def custom_loss(y_true, y_pred):
loss = k.mean(k.square(y_true - y_pred), axis=-1) # MSE
loss = k.where((y_pred - y_true) < 0.0, loss, loss * 0.5) # higher loss for false alarms
return loss
model.compile(optimizer = 'Adam', loss = custom_loss)
However, I would recommend using a different loss function. For example, you could use the MSLE (Mean Squared Logarithmic Error) loss function. This loss function is penalized more for underestimating, which is what you want to achieve, because its exactly the case when predicted smaller than true value. You can use it like this:
model.compile(optimizer = 'Adam', loss = 'msle')
|
Weighted Mean Squared Error in TensorFlow
|
I created a neural network for Quickest Detection.
The input is a list of 10 observation and the output is the change time predicted.
I want to modify the Probability of false alarms using a Weighted MSE.
I created this neural network:
model = k.Sequential(\[
k.layers.Dense(window_size, activation = k.activations.relu, input_shape=\[window_size\]),
k.layers.Dense(window_size, activation = k.activations.relu),
k.layers.Dense(window_size, activation = k.activations.relu),
k.layers.Dense(window_size, activation = k.activations.relu),
k.layers.Dense(1, activation = k.activations.relu),
\])
model.compile(optimizer = 'Adam', loss = 'mse')
\#training
history = model.fit(x = X, y=y, epochs = 50)
I have to modify this model introducing a weighted MSE that prevent False Alarms
(a false alarms occurs when value predicted - true label < 0).
How can I implement it?
|
[
"You can achieve this by creating a custom loss function:\n def custom_loss(y_true, y_pred):\n loss = k.mean(k.square(y_true - y_pred), axis=-1) # MSE\n loss = k.where((y_pred - y_true) < 0.0, loss, loss * 0.5) # higher loss for false alarms\n return loss\n model.compile(optimizer = 'Adam', loss = custom_loss)\n\nHowever, I would recommend using a different loss function. For example, you could use the MSLE (Mean Squared Logarithmic Error) loss function. This loss function is penalized more for underestimating, which is what you want to achieve, because its exactly the case when predicted smaller than true value. You can use it like this:\n model.compile(optimizer = 'Adam', loss = 'msle')\n\n"
] |
[
0
] |
[] |
[] |
[
"artificial_intelligence",
"deep_learning",
"neural_network",
"python",
"tensorflow"
] |
stackoverflow_0074511992_artificial_intelligence_deep_learning_neural_network_python_tensorflow.txt
|
Q:
Python recursive generator breaks when using list() and append() keywords
I have only recently learned about coroutines using generators and tried to implement the concept in the following recursive function:
def _recursive_nWay_generator(input: list, output={}):
'''
Helper function; used to generate parameter-value pairs
to submit to the model for the simulation.
Parameters
----------
input : list of tuple
every tuple of the list must be of the form:
``('name_of_parameter', iterable_of_values)``
output : list, optional
parameter used for recursion; allows for list building
across subgenerators
Returns
-------
Generator :
Specifications used for simulation setup of the form:
``{'par1': val1, ...}``
'''
# exit condition
if len(input) == 0:
yield output
# recursive loop
else:
curr = input[0]
par_name = curr[0]
for par_value in curr[1]:
output[par_name] = par_value
# coroutines for the win!
yield from _recursive_nWay_generator(input[1:], output=output)
Function somewhat works as intended:
testlist = [('a', (1, 2, 3)), ('b', (4, 5, 6)), ('c', (7, 8))]
for a in _recursive_nWay_generator(testlist):
print(a)
Output:
{'a': 1, 'b': 4, 'c': 7}
{'a': 1, 'b': 4, 'c': 8}
{'a': 1, 'b': 5, 'c': 7}
{'a': 1, 'b': 5, 'c': 8}
{'a': 1, 'b': 6, 'c': 7}
{'a': 1, 'b': 6, 'c': 8}
{'a': 2, 'b': 4, 'c': 7}
{'a': 2, 'b': 4, 'c': 8}
{'a': 2, 'b': 5, 'c': 7}
{'a': 2, 'b': 5, 'c': 8}
{'a': 2, 'b': 6, 'c': 7}
{'a': 2, 'b': 6, 'c': 8}
{'a': 3, 'b': 4, 'c': 7}
{'a': 3, 'b': 4, 'c': 8}
{'a': 3, 'b': 5, 'c': 7}
{'a': 3, 'b': 5, 'c': 8}
{'a': 3, 'b': 6, 'c': 7}
{'a': 3, 'b': 6, 'c': 8}
However, it breaks when I try to append to an existing list or construct a new one:
gen = _recursive_nWay_generator(testlist)
print(list(gen))
Output:
[{'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}]
This question was attempting to do something close to what I have, but I'm not seeing answers that could help.
I am honestly clueless as to how to solve this, the online searches I tried gave nothing no matter how I phrase the question. If this was answered before I'll be happy to just follow the link.
A:
The problem with your code is reusing the same mutable output dict during the iteration and recursive calls. That is, you yield output and then later on you modify it with output[par_name] = par_value but it's the same dict in each case - so you're modifying the instance which was already returned! If you append each result into a list and then print them all at the end, you'll see that they're identical - it's the same result yielded each time.
The simplest way to "fix" your existing code is to yield copies, i.e. change the line:
yield output
into this:
yield dict(output.items())
However, this algorithm is not great, and I recommend you look for something better. Using recursion is poor choice here. I'll offer you a simple/direct way to generate the sequence more efficiently:
import itertools as it
testlist = [('a', (1, 2, 3)), ('b', (4, 5, 6)), ('c', (7, 8))]
keys, vals = zip(*testlist)
for p in it.product(*vals):
print(dict(zip(keys, p)))
|
Python recursive generator breaks when using list() and append() keywords
|
I have only recently learned about coroutines using generators and tried to implement the concept in the following recursive function:
def _recursive_nWay_generator(input: list, output={}):
'''
Helper function; used to generate parameter-value pairs
to submit to the model for the simulation.
Parameters
----------
input : list of tuple
every tuple of the list must be of the form:
``('name_of_parameter', iterable_of_values)``
output : list, optional
parameter used for recursion; allows for list building
across subgenerators
Returns
-------
Generator :
Specifications used for simulation setup of the form:
``{'par1': val1, ...}``
'''
# exit condition
if len(input) == 0:
yield output
# recursive loop
else:
curr = input[0]
par_name = curr[0]
for par_value in curr[1]:
output[par_name] = par_value
# coroutines for the win!
yield from _recursive_nWay_generator(input[1:], output=output)
Function somewhat works as intended:
testlist = [('a', (1, 2, 3)), ('b', (4, 5, 6)), ('c', (7, 8))]
for a in _recursive_nWay_generator(testlist):
print(a)
Output:
{'a': 1, 'b': 4, 'c': 7}
{'a': 1, 'b': 4, 'c': 8}
{'a': 1, 'b': 5, 'c': 7}
{'a': 1, 'b': 5, 'c': 8}
{'a': 1, 'b': 6, 'c': 7}
{'a': 1, 'b': 6, 'c': 8}
{'a': 2, 'b': 4, 'c': 7}
{'a': 2, 'b': 4, 'c': 8}
{'a': 2, 'b': 5, 'c': 7}
{'a': 2, 'b': 5, 'c': 8}
{'a': 2, 'b': 6, 'c': 7}
{'a': 2, 'b': 6, 'c': 8}
{'a': 3, 'b': 4, 'c': 7}
{'a': 3, 'b': 4, 'c': 8}
{'a': 3, 'b': 5, 'c': 7}
{'a': 3, 'b': 5, 'c': 8}
{'a': 3, 'b': 6, 'c': 7}
{'a': 3, 'b': 6, 'c': 8}
However, it breaks when I try to append to an existing list or construct a new one:
gen = _recursive_nWay_generator(testlist)
print(list(gen))
Output:
[{'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}, {'a': 3, 'b': 6, 'c': 8}]
This question was attempting to do something close to what I have, but I'm not seeing answers that could help.
I am honestly clueless as to how to solve this, the online searches I tried gave nothing no matter how I phrase the question. If this was answered before I'll be happy to just follow the link.
|
[
"The problem with your code is reusing the same mutable output dict during the iteration and recursive calls. That is, you yield output and then later on you modify it with output[par_name] = par_value but it's the same dict in each case - so you're modifying the instance which was already returned! If you append each result into a list and then print them all at the end, you'll see that they're identical - it's the same result yielded each time.\nThe simplest way to \"fix\" your existing code is to yield copies, i.e. change the line:\nyield output\n\ninto this:\nyield dict(output.items())\n\nHowever, this algorithm is not great, and I recommend you look for something better. Using recursion is poor choice here. I'll offer you a simple/direct way to generate the sequence more efficiently:\nimport itertools as it \n\ntestlist = [('a', (1, 2, 3)), ('b', (4, 5, 6)), ('c', (7, 8))]\nkeys, vals = zip(*testlist)\nfor p in it.product(*vals):\n print(dict(zip(keys, p)))\n\n"
] |
[
0
] |
[] |
[] |
[
"coroutine",
"generator",
"list",
"python",
"recursion"
] |
stackoverflow_0074513316_coroutine_generator_list_python_recursion.txt
|
Q:
How do I extract a value from quarterly cashflow using python and yfinance
import yfinance as yf
ticker = yf.Ticker("AAPL)
q_cashflow = ticker_quarterly_cashflow
print(q_cashflow)
Some output below. How do I extract for instance the value of 'Change To Liabilities' on '2021-06-26' which is 3.070000e+08? Sorry I am beginning to learn programming. Thanks in advance.
2022-03-26 ... 2021-06-26
Investments -6.390000e+09 ... 5.747000e+09
Change To Liabilities -2.139800e+10 ... 3.070000e+08
Total Cashflows From Investing Activities -9.265000e+09 ... 3.572000e+09
Net Borrowings -1.751000e+09 ... 3.220000e+09
Total Cash From Financing Activities -2.835100e+10 ... -2.939600e+10
Net Income 2.501000e+10 ... 2.174400e+10
Change In Cash -9.450000e+09 ... -4.730000e+09
A:
It is just a Pandas dataframe. You can use the usual way that you use to extract a value from a Pandas dataframe. For example, q_cashflow.loc[row_index_name, column_name]
|
How do I extract a value from quarterly cashflow using python and yfinance
|
import yfinance as yf
ticker = yf.Ticker("AAPL)
q_cashflow = ticker_quarterly_cashflow
print(q_cashflow)
Some output below. How do I extract for instance the value of 'Change To Liabilities' on '2021-06-26' which is 3.070000e+08? Sorry I am beginning to learn programming. Thanks in advance.
2022-03-26 ... 2021-06-26
Investments -6.390000e+09 ... 5.747000e+09
Change To Liabilities -2.139800e+10 ... 3.070000e+08
Total Cashflows From Investing Activities -9.265000e+09 ... 3.572000e+09
Net Borrowings -1.751000e+09 ... 3.220000e+09
Total Cash From Financing Activities -2.835100e+10 ... -2.939600e+10
Net Income 2.501000e+10 ... 2.174400e+10
Change In Cash -9.450000e+09 ... -4.730000e+09
|
[
"It is just a Pandas dataframe. You can use the usual way that you use to extract a value from a Pandas dataframe. For example, q_cashflow.loc[row_index_name, column_name]\n"
] |
[
0
] |
[] |
[] |
[
"python",
"yfinance"
] |
stackoverflow_0072818954_python_yfinance.txt
|
Q:
Get softmax output and raw output of the last layer of a model
When creating a neural network for image classification, I want to get the classification on one hand and the raw output on the other hand to determine if the image really contains one of the images I want to classify or not. If not then the raw output should contain very low values for all classes. But if the image really contains one of the objects that I want to classify, then the raw output should have a high value for one of the neurons.
Assuming I have the following code:
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(80, 80, 3)))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(16, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(16, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(4, activation='softmax'))
How would I get the raw output of the last dense layer?
A:
You can use functional API and implement your model in a next way:
inputs = tf.keras.Input(shape=(80, 80, 3))
x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu')(inputs)
x = tf.keras.layers.MaxPooling2D((2, 2))(x)
x = tf.keras.layers.Dropout(0.3)(x)
x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu')(x)
x = tf.keras.layers.MaxPooling2D((2, 2))(x)
x = tf.keras.layers.Dropout(0.3)(x)
x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu')(x)
x = tf.keras.layers.MaxPooling2D((2, 2))(x)
x = tf.keras.layers.Flatten()(x)
# here you can get raw output
logits = tf.keras.layers.Dense(4)(x)
model = tf.keras.Model(
inputs=inputs,
outputs={
'logits': logits,
'predictions': tf.nn.softmax(logits)
}
)
model.summary()
After that, your model will have two outputs in dictionary format. Beware that you can't use a simple loss function like categorical_crossentropy because it will try to minimize loss for both outputs. You need to use losses argument in compile method to specify the loss for each output. For example:
model.compile(
optimizer='adam',
loss={
# ignore logits loss
'logits': lambda y_true, y_pred: 0.0,
'predictions': tf.keras.losses.CategoricalCrossentropy()
})
And your fit would look like this:
model.fit(
x_train,
{
'logits': y_train,
'predictions': y_train
},
epochs=10
)
|
Get softmax output and raw output of the last layer of a model
|
When creating a neural network for image classification, I want to get the classification on one hand and the raw output on the other hand to determine if the image really contains one of the images I want to classify or not. If not then the raw output should contain very low values for all classes. But if the image really contains one of the objects that I want to classify, then the raw output should have a high value for one of the neurons.
Assuming I have the following code:
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(80, 80, 3)))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(16, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(16, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(4, activation='softmax'))
How would I get the raw output of the last dense layer?
|
[
"You can use functional API and implement your model in a next way:\n inputs = tf.keras.Input(shape=(80, 80, 3))\n x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu')(inputs)\n x = tf.keras.layers.MaxPooling2D((2, 2))(x)\n x = tf.keras.layers.Dropout(0.3)(x)\n x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu')(x)\n x = tf.keras.layers.MaxPooling2D((2, 2))(x)\n x = tf.keras.layers.Dropout(0.3)(x)\n x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu')(x)\n x = tf.keras.layers.MaxPooling2D((2, 2))(x)\n x = tf.keras.layers.Flatten()(x)\n # here you can get raw output\n logits = tf.keras.layers.Dense(4)(x)\n model = tf.keras.Model(\n inputs=inputs, \n outputs={\n 'logits': logits,\n 'predictions': tf.nn.softmax(logits)\n }\n )\n model.summary()\n\nAfter that, your model will have two outputs in dictionary format. Beware that you can't use a simple loss function like categorical_crossentropy because it will try to minimize loss for both outputs. You need to use losses argument in compile method to specify the loss for each output. For example:\n model.compile(\n optimizer='adam',\n loss={\n # ignore logits loss\n 'logits': lambda y_true, y_pred: 0.0,\n 'predictions': tf.keras.losses.CategoricalCrossentropy()\n })\n\nAnd your fit would look like this:\n model.fit(\n x_train,\n {\n 'logits': y_train,\n 'predictions': y_train\n },\n epochs=10\n )\n\n"
] |
[
1
] |
[] |
[] |
[
"classification",
"deep_learning",
"neural_network",
"python",
"tensorflow"
] |
stackoverflow_0074508999_classification_deep_learning_neural_network_python_tensorflow.txt
|
Q:
i cant figure out my python game keep crashing
please help when i press space, e, or f my game crashes but i cant find out why also can you help me make this dam block move upwards. please help me i will go insane if i cant figure this out.
`
# import the pygame module
import pygame
import keyboard
import time
xb = 30
yb = 670
x = 30
y = 670
o = 0
# Define the background colour
# using RGB color coding.
background_colour = (10,10,10)
# Define the dimensions of
# screen object(width,height)
screen = pygame.display.set_mode((800, 750),pygame.RESIZABLE)
# Set the caption of the screen
pygame.display.set_caption('shoter')
# Fill the background colour to the screen
screen.fill(background_colour)
def player():
color = (40,40,45)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.draw.polygon(screen, color, ((x+60,y), (x+30,y-80), (x,y)))
pygame.draw.polygon(screen, color, ((x-20,y+52.5), (x+30,y+70), (x+80,y+52.5)))
color = (60,60,65)
pygame.draw.rect(screen, color, pygame.Rect((x-70), (y+20), 200, 30))
color = (40,40,45)
pygame.draw.rect(screen, color, pygame.Rect(x-70, y-20, 20, 40))
pygame.draw.rect(screen, color, pygame.Rect(x+110, y-20, 20, 40))
# Update the display using flip
pygame.display.flip()
# Variable to keep our game loop running
running = True
while running:
for event in pygame.event.get():
# Check for QUIT event
if event.type == pygame.QUIT:
running = False
if keyboard.is_pressed("a") or keyboard.is_pressed("w") or keyboard.is_pressed("left arrow"):
print("left")
screen.fill(background_colour)
x = (x + -3.75)
player()
time.sleep(0.005)
pygame.display.flip()
if keyboard.is_pressed("d") or keyboard.is_pressed("s") or keyboard.is_pressed("right arrow"):
print("right")
screen.fill(background_colour)
x = (x + 3.75)
player()
time.sleep(0.005)
pygame.display.flip()
if keyboard.is_pressed("space") or keyboard.is_pressed("f") or keyboard.is_pressed("e"):
color = (255,0,0)
pygame.draw.rect(screen, color, pygame.Rect(xb, yb, 60, 60))
while (yb > -40):
yb = yb + 5
time.sleep(0.5)
print("shot")
pygame.display.flip()
time.sleep(0.01)
`
please help me ive tried to almost everything to make it work but everytime i press space it crashes
i think this is because of the while loop?
A:
In PyGame, the 0,0 co-ordinate is in the upper-left corner of the window. In your game the player is positioned at the bottom, so the projectile moves up the display, going from a large y-coordinate to a smaller one, and eventually negative once off-screen.
As @Chris Doyle points out in a comment, your code has a tight loop where yb is increased, but then is tested for being < -40. Since yb is already positive, this can never happen. So your program is locking up at this point, as the loop exiting condition can never be satisfied.
Looking at your code, there's a few tweaks necessary for the projectile logic.
First it's best to try to paint everything on the screen from one place, then you're not re-painting (or accidentally erasing) items on every loop.
I also moved the logic of the bullet movement out into the main loop. So pressing space only starts the bullet. The movement happens when the main loop "sees" a bullet on the screen (when firing is True).
Other tweaks: I don't have the keyboard module, so I ported this to standard PyGame keys. And I took the liberty of renaming the x,y and xb,yb to player_x, player_y and projectile_x, projectile_y. I hope that's OK.
# import the pygame module
import pygame
#import keyboard
import time
projectile_x = 30
projectile_y = 670
player_x = 30
player_y = 670
o = 0
# Define the background colour
# using RGB color coding.
background_colour = (10,10,10)
# Define the dimensions of
# screen object(width,height)
screen = pygame.display.set_mode((800, 750),pygame.RESIZABLE)
# Set the caption of the screen
pygame.display.set_caption('shoter')
# Fill the background colour to the screen
screen.fill(background_colour)
def player():
color = (40,40,45)
pygame.draw.rect(screen, color, pygame.Rect(player_x, player_y, 60, 60))
pygame.draw.polygon(screen, color, ((player_x+60,player_y), (player_x+30,player_y-80), (player_x,player_y)))
pygame.draw.polygon(screen, color, ((player_x-20,player_y+52.5), (player_x+30,player_y+70), (player_x+80,player_y+52.5)))
color = (60,60,65)
pygame.draw.rect(screen, color, pygame.Rect((player_x-70), (player_y+20), 200, 30))
color = (40,40,45)
pygame.draw.rect(screen, color, pygame.Rect(player_x-70, player_y-20, 20, 40))
pygame.draw.rect(screen, color, pygame.Rect(player_x+110, player_y-20, 20, 40))
# Update the display using flip
pygame.display.flip()
# Is a projectile on screen?
firing = False
# Variable to keep our game loop running
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
# Check for QUIT event
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
a_w_left = keys[pygame.K_LEFT] or keys[pygame.K_a] or keys[pygame.K_w]
d_s_right = keys[pygame.K_RIGHT] or keys[pygame.K_d] or keys[pygame.K_s]
e_f_space = keys[pygame.K_SPACE] or keys[pygame.K_e] or keys[pygame.K_f]
if a_w_left:
print("left")
player_x = (player_x + -3.75)
if d_s_right:
print("right")
player_x = (player_x + 3.75)
if e_f_space:
if ( not firing ):
firing = True
projectile_x = player_x
projectile_y = player_y - 10
print("shot")
# repaint the screen
screen.fill(background_colour)
player()
if ( firing ):
color = (255,0,0)
pygame.draw.rect(screen, color, pygame.Rect(projectile_x, projectile_y, 60, 60))
projectile_y = projectile_y - 5
if ( projectile_y < -60 ):
firing = False # bullet off screen
pygame.display.flip()
clock.tick( 60 ) # limit FPS
Also, it's not good practice to use time.sleep() to control movement (etc.) in a PyGame program, because it blocks everything up. It's better to use the real-time millisecond clock provided by pygame.time.get_ticks().
|
i cant figure out my python game keep crashing
|
please help when i press space, e, or f my game crashes but i cant find out why also can you help me make this dam block move upwards. please help me i will go insane if i cant figure this out.
`
# import the pygame module
import pygame
import keyboard
import time
xb = 30
yb = 670
x = 30
y = 670
o = 0
# Define the background colour
# using RGB color coding.
background_colour = (10,10,10)
# Define the dimensions of
# screen object(width,height)
screen = pygame.display.set_mode((800, 750),pygame.RESIZABLE)
# Set the caption of the screen
pygame.display.set_caption('shoter')
# Fill the background colour to the screen
screen.fill(background_colour)
def player():
color = (40,40,45)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.draw.polygon(screen, color, ((x+60,y), (x+30,y-80), (x,y)))
pygame.draw.polygon(screen, color, ((x-20,y+52.5), (x+30,y+70), (x+80,y+52.5)))
color = (60,60,65)
pygame.draw.rect(screen, color, pygame.Rect((x-70), (y+20), 200, 30))
color = (40,40,45)
pygame.draw.rect(screen, color, pygame.Rect(x-70, y-20, 20, 40))
pygame.draw.rect(screen, color, pygame.Rect(x+110, y-20, 20, 40))
# Update the display using flip
pygame.display.flip()
# Variable to keep our game loop running
running = True
while running:
for event in pygame.event.get():
# Check for QUIT event
if event.type == pygame.QUIT:
running = False
if keyboard.is_pressed("a") or keyboard.is_pressed("w") or keyboard.is_pressed("left arrow"):
print("left")
screen.fill(background_colour)
x = (x + -3.75)
player()
time.sleep(0.005)
pygame.display.flip()
if keyboard.is_pressed("d") or keyboard.is_pressed("s") or keyboard.is_pressed("right arrow"):
print("right")
screen.fill(background_colour)
x = (x + 3.75)
player()
time.sleep(0.005)
pygame.display.flip()
if keyboard.is_pressed("space") or keyboard.is_pressed("f") or keyboard.is_pressed("e"):
color = (255,0,0)
pygame.draw.rect(screen, color, pygame.Rect(xb, yb, 60, 60))
while (yb > -40):
yb = yb + 5
time.sleep(0.5)
print("shot")
pygame.display.flip()
time.sleep(0.01)
`
please help me ive tried to almost everything to make it work but everytime i press space it crashes
i think this is because of the while loop?
|
[
"In PyGame, the 0,0 co-ordinate is in the upper-left corner of the window. In your game the player is positioned at the bottom, so the projectile moves up the display, going from a large y-coordinate to a smaller one, and eventually negative once off-screen.\nAs @Chris Doyle points out in a comment, your code has a tight loop where yb is increased, but then is tested for being < -40. Since yb is already positive, this can never happen. So your program is locking up at this point, as the loop exiting condition can never be satisfied.\nLooking at your code, there's a few tweaks necessary for the projectile logic.\nFirst it's best to try to paint everything on the screen from one place, then you're not re-painting (or accidentally erasing) items on every loop.\nI also moved the logic of the bullet movement out into the main loop. So pressing space only starts the bullet. The movement happens when the main loop \"sees\" a bullet on the screen (when firing is True).\nOther tweaks: I don't have the keyboard module, so I ported this to standard PyGame keys. And I took the liberty of renaming the x,y and xb,yb to player_x, player_y and projectile_x, projectile_y. I hope that's OK.\n# import the pygame module\nimport pygame\n#import keyboard\nimport time\n\nprojectile_x = 30\nprojectile_y = 670\nplayer_x = 30\nplayer_y = 670\no = 0\n\n# Define the background colour\n# using RGB color coding.\nbackground_colour = (10,10,10)\n \n# Define the dimensions of\n# screen object(width,height)\n\nscreen = pygame.display.set_mode((800, 750),pygame.RESIZABLE)\n \n# Set the caption of the screen\npygame.display.set_caption('shoter')\n \n# Fill the background colour to the screen\nscreen.fill(background_colour)\n\n\n\ndef player():\n color = (40,40,45)\n pygame.draw.rect(screen, color, pygame.Rect(player_x, player_y, 60, 60))\n pygame.draw.polygon(screen, color, ((player_x+60,player_y), (player_x+30,player_y-80), (player_x,player_y)))\n\n pygame.draw.polygon(screen, color, ((player_x-20,player_y+52.5), (player_x+30,player_y+70), (player_x+80,player_y+52.5)))\n color = (60,60,65)\n pygame.draw.rect(screen, color, pygame.Rect((player_x-70), (player_y+20), 200, 30))\n color = (40,40,45)\n pygame.draw.rect(screen, color, pygame.Rect(player_x-70, player_y-20, 20, 40))\n pygame.draw.rect(screen, color, pygame.Rect(player_x+110, player_y-20, 20, 40))\n\n \n# Update the display using flip\npygame.display.flip()\n\n# Is a projectile on screen?\nfiring = False\n\n# Variable to keep our game loop running\nrunning = True\n\n \nclock = pygame.time.Clock()\nwhile running:\n\n for event in pygame.event.get():\n # Check for QUIT event \n if event.type == pygame.QUIT:\n running = False\n\n keys = pygame.key.get_pressed()\n\n a_w_left = keys[pygame.K_LEFT] or keys[pygame.K_a] or keys[pygame.K_w]\n d_s_right = keys[pygame.K_RIGHT] or keys[pygame.K_d] or keys[pygame.K_s]\n e_f_space = keys[pygame.K_SPACE] or keys[pygame.K_e] or keys[pygame.K_f]\n\n if a_w_left:\n print(\"left\")\n player_x = (player_x + -3.75)\n\n if d_s_right:\n print(\"right\")\n player_x = (player_x + 3.75)\n\n if e_f_space:\n if ( not firing ):\n firing = True\n projectile_x = player_x\n projectile_y = player_y - 10\n print(\"shot\")\n\n # repaint the screen\n screen.fill(background_colour)\n player()\n if ( firing ):\n color = (255,0,0)\n pygame.draw.rect(screen, color, pygame.Rect(projectile_x, projectile_y, 60, 60))\n projectile_y = projectile_y - 5\n if ( projectile_y < -60 ):\n firing = False # bullet off screen\n\n pygame.display.flip()\n clock.tick( 60 ) # limit FPS\n\nAlso, it's not good practice to use time.sleep() to control movement (etc.) in a PyGame program, because it blocks everything up. It's better to use the real-time millisecond clock provided by pygame.time.get_ticks().\n"
] |
[
1
] |
[] |
[] |
[
"keyboard",
"pygame",
"python"
] |
stackoverflow_0074513113_keyboard_pygame_python.txt
|
Q:
SLY python can't parse simple tokens
I'm working on making a simple interpreted programming language using SLY to generate a AST which I will interpret without using SLY.
Currently I have been able to generate all my tokens and giving them to the parser, but it can't recognize any rule, only empty ones.
Lexer:
from .sly.lex import Lexer
class ALexer(Lexer):
tokens = { ID, NUMBER, STRING, BOOL, PLUS, TIMES, MINUS, DIVIDE, ASSIGN, LPAREN, RPAREN, COMMA, NL }
ignore = ' \t'
# Tokens
@_(r'\d+[[.]?\d*[f]?]?')
def NUMBER(self, t):
endswithF = t.value.endswith('f')
isfloat = endswithF or t.value.find('.') != -1
t.value = float(t.value[:-1] if endswithF else t.value) if isfloat else int(t.value) # Convert to a numeric value
return t
ID = r'[a-zA-Z_][a-zA-Z0-9_]*'
ID['true'] = BOOL
ID['false'] = BOOL
@_(r'".*"')
def STRING(self, t):
t.value = t.value[1:-1]
return t
# Special symbols
PLUS = r'\+'
MINUS = r'-'
TIMES = r'\*'
DIVIDE = r'/'
ASSIGN = r'='
LPAREN = r'\('
RPAREN = r'\)'
COMMA = r','
@_(r'true', r'false')
def BOOL(self, t):
t.value = t.value == 'true'
return t
@_(r'\n')
def NL(self, t):
self.lineno += 1
def error(self, t):
print("Illegal character '%s'" % t.value[0])
self.index += 1
Util classes:
from enum import Enum
class SupportedOp(str, Enum):
CONSTANT = "CONSTANT",
VARIABLE = "VARIABLE",
ARGS_LIST = "ARGS_LIST",
FUNC_CALL = "FUNC_CALL",
STATEMENT = "STATEMENT",
STATEMENT_LIST = "STATEMENT_LIST",
PROGRAM = "PROGRAM",
SUM = '+',
SUB = '-',
DIV = '/',
MUL = '*',
ASSIGNMENT = '='
class ParsedOp(dict):
def __init__(self, op: SupportedOp, *values):
dict.__init__(self, op=op, values=values)
Parser:
class AParser(Parser):
debugfile = 'parser.out'
tokens = ALexer.tokens
precedence = (
#('nonassoc', LESSTHAN, GREATERTHAN), # Nonassociative operators
('left', PLUS, MINUS),
('left', TIMES, DIVIDE)
#('right', UMINUS), # Unary minus operator
)
@_('statement_list')
def program(self, p):
print('program', p[0])
return ParsedOp(SupportedOp.PROGRAM, p[0])
@_('statement BACK_IN_LINES statement_list')
def statement_list(self, p):
print('statement_list', p[0], p[1], p[2])
lst: list = p[1].values[0]
lst.append(p[0])
return ParsedOp(SupportedOp.STATEMENT_LIST, lst)
@_('statement')
def statement_list(self, p):
print('statement_list', p[0])
return ParsedOp(SupportedOp.STATEMENT_LIST, [p[0]])
@_('empty')
def statement_list(self, p):
print('empty statement_list')
return ParsedOp(SupportedOp.STATEMENT_LIST, [])
@_('NL BACK_IN_LINES', 'NL')
def BACK_IN_LINES(self, p):
print('BACK_IN_LINES', p[0])
#unused
return 'NL'
@_('assignment', 'expr')
def statement(self, p):
print('statement', p[0])
return ParsedOp(SupportedOp.STATEMENT, p[0])
@_('ID ASSIGN expr')
def assignment(self, p):
print('assignment', p[0], p[1], p[2])
return ParsedOp(SupportedOp.ASSIGNMENT, p[0], p[2])
@_('expr COMMA expr_list')
def expr_list(self, p):
print('expr_list', p[0], p[1], p[2])
lst: list = p[1].values[0]
lst.append(p[0])
return ParsedOp(SupportedOp.ARGS_LIST, lst)
@_('expr')
def expr_list(self, p):
print('expr_list', p[0])
return ParsedOp(SupportedOp.ARGS_LIST, [p[0]])
@_('empty')
def expr_list(self, p):
print('empty expr_list')
return ParsedOp(SupportedOp.ARGS_LIST, [])
@_('constant')
def expr(self, p):
print('expr', p[0])
return p[0]
@_('ID')
def expr(self, p):
print('expr', p[0])
return ParsedOp(SupportedOp.VARIABLE, p[0])
@_('LPAREN expr RPAREN')
def expr(self, p):
print('expr', p[0], p[1], p[2])
return p[1]
@_('ID LPAREN expr_list RPAREN')
def expr(self, p):
print('expr', p[0], p[1], p[2], p[3])
#if exists p.ID in functions
return ParsedOp(SupportedOp.FUNC_CALL, p.ID, p.expr_list)
@_( 'expr PLUS expr',
'expr MINUS expr',
'expr TIMES expr',
'expr DIVIDE expr')
def expr(self, p):
print('expr', p[0], p[1], p[2])
return ParsedOp(SupportedOp(p[1]), p[0], p[2])
@_('NUMBER', 'STRING', 'BOOL')
def constant(self, p):
print('constant', p[0])
return ParsedOp(SupportedOp.CONSTANT, p[0])
@_('')
def empty(self, p):
print('empty')
pass
def error(self, p):
if p:
print("Syntax error at token", p.type)
# Just discard the token and tell the parser it's okay.
self.errok()
else:
print("Syntax error at EOF")
I don't know if all my rules are ok but I commented every rule leaving uncommented only the "constant" rule which is straightforward, still can't recognize it.
Main:
tokens_out = lexer.ALexer().tokenize(event.get("code"))
tree = AParser().parse(tokens_out)
All my tokens are well recognized so the Lexer is ok. The parser can't recognize any rule. Any idea?
A:
As far as I can see, your code works fine up to the point at which you attempt to parse the second statement. I tried it with the input x=2 as suggested in your comment, and it produced the following result (pretty-printed with the pprint module):
{ 'op': <SupportedOp.PROGRAM: 'PROGRAM'>,
'values': ( { 'op': <SupportedOp.STATEMENT_LIST: 'STATEMENT_LIST'>,
'values': ( [ { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,
'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,
'values': ( 'x',
{ 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,
'values': ( 2,)})},)}],)},)}
But once you try to parse two statements --say x=2 and y=2 on separate lines-- things start to fall apart.
There are several issues, which I'll try to deal with one at a time.
The first problem is that your NL lexer rule does not return anything, which means that no token is emitted. That means that the BACK_IN_LINES rule cannot match, because it is expecting to see one or more NL tokens. This generates a cascade of parser errors, which you should have seen on your console.
It's easy to get confused about the parser's progress. Since the parser doesn't see the NL token, what it sees is x = 2 y .... At the moment at which it sees the y, it hasn't yet reduced expr; after all, the next token might have been a + or other operator. But an ID is not one of the possible tokens which can follow 2, so a syntax error is thrown immediately, with the result that expr, statement and statement_list are not reduced, and so their reduction actions never execute, and thus you never see any of the debugging output you've put in the reduction actions. That doesn't really mean that the rule was not recognised; it would be more accurate to say that the rule was recognised but a longer match was still possible.
If you fix the lexer by adding return t at the end of the NL rule, then you run into the second problem, which is the reduction action for statement_list: statement BACK_IN_LINES statement_list. This bug causes the parse to fail even for an input consisting only of x=2, if that input is terminated with a newline character. The action is triggered because BACK_IN_LINES is now recognised, so the grammar requires that the statement_list has two subcomponents, a statement (x=2) and a statement_listconsisting of the rest of the input. The rest of the input is empty, which is OK because you allow astatement_list` to match an empty input. But, as I said, that causes the reduction action to execute, and that reduction action includes:
lst: list = p[1].values[0]
That line has several problems. First, p[1] is the BACK_IN_LINES grammar symbol; you obviously intended to use p[2], which is the statement_list. So p[1] is the string NL, which doesn't have a values attribute. (That should be evident from the Python traceback, assuming that you can see the exception tracebacks. If you can't, you should seriously consider debugging in a Python console instead of whatever you are using.)
But when we fix it to use p[2] instead, we still get a Python TypeError exception. Instead of complaining that a str has no values attribute, it now complains that a builtin_function_or_method is not subscriptable. The builtin_function_or_method is the values method of a dict object, becasue p[2] is a SupportedOp, which is subclassed from dict. If you had intended to use the values method, you would have had to have called it, but I don't think that was what you intended (and therefore the values key is perhaps badly named). What you actually meant was the value associated with the values key, which means that the line should read:
lst: list = p[2]["values"][0]
But that's still a bit problematic. Let's take a look at the parsed result of the input consisting of three lines:
first = 1
second = 2
third = 3
That produces (again, pretty printed with pprint):
{ 'op': <SupportedOp.PROGRAM: 'PROGRAM'>,
'values': ( { 'op': <SupportedOp.STATEMENT_LIST: 'STATEMENT_LIST'>,
'values': ( [ { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,
'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,
'values': ( 'third',
{ 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,
'values': ( 3,)})},)},
{ 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,
'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,
'values': ( 'second',
{ 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,
'values': ( 2,)})},)},
{ 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,
'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,
'values': ( 'first',
{ 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,
'values': ( 1,)})},)}],)},)}
If you look carefully at that output, you'll see that the three statements are indeed there, but in the wrong order.
That's the result of your choosing to use a right-recursive rule for statement_list:
statement_list: statement BACK_IN_LINES statement_list
Right-recursive rules are practically never correct for bottom-up parsers (such as the LALR(1) parser generated by Sly), although there are times when they are needed. If you can choose between a left-recursive rule and a right-recursive rule, your best option is the left-recursive rule:
statement_list: statement_list BACK_IN_LINES statement
This has two advantages. First, it doesn't require use of the parser stack to hold all the intermediate and incomplete subparses of statement_list until the end of the list is reached. More importantly, it executes the reduction actions for the recursive non-terminal in the order you probably expect them to be executed, which is left-to-right.
The right-recursive rule executes the reduction actions right-to-left, because the first recursive reduction is the last nested statement_list. And the consequence is that which we have already seen: the statements are appended to the statement_list in reverse order, starting with the last one.
It's easy to rewrite the rule as left-recursive. But if we do a naive change, we'll end up with a different problem. It's (probably) desirable that the input is allowed to but not required to end with a newline. That worked with the right-recursive production because statement_list was allowed to be empty. But that won't help with the left-recursive rule; a left-recursive rule with an empty option puts the empty option at the beginning of the list (precisely because it produces the list left-to-right). With the left-recursive rule, it's more convenient to allow statement to be empty. But instead of adding an "empty statement", which will clutter up the AST, we can just add a rule to statement_list which accepts an empty sequence instead of a statement. Once we do that, we eliminate the need for BACK_IN_LINES, because the grammatical logic is kept in statement_list.
So we can remove BACK_IN_LINES and replace the rules for statement_list with the following:
@_('statement')
def statement_list(self, p):
print('statement_list', p[0])
return ParsedOp(SupportedOp.STATEMENT_LIST, [p[0]])
@_('empty')
def statement_list(self, p):
print('empty statement_list')
return ParsedOp(SupportedOp.STATEMENT_LIST, [])
@_('statement_list NL')
def statement_list(self, p):
print('statement_list', p[0])
return p[0]
@_('statement_list NL statement')
def statement_list(self, p):
print('statement_list', p[0], p[1], p[2])
lst: list = p[0]["values"][0]
lst.append(p[2])
return ParsedOp(SupportedOp.STATEMENT_LIST, lst)
Now, finally, we get the expected parse:
{ 'op': <SupportedOp.PROGRAM: 'PROGRAM'>,
'values': ( { 'op': <SupportedOp.STATEMENT_LIST: 'STATEMENT_LIST'>,
'values': ( [ { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,
'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,
'values': ( 'first',
{ 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,
'values': ( 1,)})},)},
{ 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,
'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,
'values': ( 'second',
{ 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,
'values': ( 2,)})},)},
{ 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,
'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,
'values': ( 'third',
{ 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,
'values': ( 3,)})},)}],)},)}
|
SLY python can't parse simple tokens
|
I'm working on making a simple interpreted programming language using SLY to generate a AST which I will interpret without using SLY.
Currently I have been able to generate all my tokens and giving them to the parser, but it can't recognize any rule, only empty ones.
Lexer:
from .sly.lex import Lexer
class ALexer(Lexer):
tokens = { ID, NUMBER, STRING, BOOL, PLUS, TIMES, MINUS, DIVIDE, ASSIGN, LPAREN, RPAREN, COMMA, NL }
ignore = ' \t'
# Tokens
@_(r'\d+[[.]?\d*[f]?]?')
def NUMBER(self, t):
endswithF = t.value.endswith('f')
isfloat = endswithF or t.value.find('.') != -1
t.value = float(t.value[:-1] if endswithF else t.value) if isfloat else int(t.value) # Convert to a numeric value
return t
ID = r'[a-zA-Z_][a-zA-Z0-9_]*'
ID['true'] = BOOL
ID['false'] = BOOL
@_(r'".*"')
def STRING(self, t):
t.value = t.value[1:-1]
return t
# Special symbols
PLUS = r'\+'
MINUS = r'-'
TIMES = r'\*'
DIVIDE = r'/'
ASSIGN = r'='
LPAREN = r'\('
RPAREN = r'\)'
COMMA = r','
@_(r'true', r'false')
def BOOL(self, t):
t.value = t.value == 'true'
return t
@_(r'\n')
def NL(self, t):
self.lineno += 1
def error(self, t):
print("Illegal character '%s'" % t.value[0])
self.index += 1
Util classes:
from enum import Enum
class SupportedOp(str, Enum):
CONSTANT = "CONSTANT",
VARIABLE = "VARIABLE",
ARGS_LIST = "ARGS_LIST",
FUNC_CALL = "FUNC_CALL",
STATEMENT = "STATEMENT",
STATEMENT_LIST = "STATEMENT_LIST",
PROGRAM = "PROGRAM",
SUM = '+',
SUB = '-',
DIV = '/',
MUL = '*',
ASSIGNMENT = '='
class ParsedOp(dict):
def __init__(self, op: SupportedOp, *values):
dict.__init__(self, op=op, values=values)
Parser:
class AParser(Parser):
debugfile = 'parser.out'
tokens = ALexer.tokens
precedence = (
#('nonassoc', LESSTHAN, GREATERTHAN), # Nonassociative operators
('left', PLUS, MINUS),
('left', TIMES, DIVIDE)
#('right', UMINUS), # Unary minus operator
)
@_('statement_list')
def program(self, p):
print('program', p[0])
return ParsedOp(SupportedOp.PROGRAM, p[0])
@_('statement BACK_IN_LINES statement_list')
def statement_list(self, p):
print('statement_list', p[0], p[1], p[2])
lst: list = p[1].values[0]
lst.append(p[0])
return ParsedOp(SupportedOp.STATEMENT_LIST, lst)
@_('statement')
def statement_list(self, p):
print('statement_list', p[0])
return ParsedOp(SupportedOp.STATEMENT_LIST, [p[0]])
@_('empty')
def statement_list(self, p):
print('empty statement_list')
return ParsedOp(SupportedOp.STATEMENT_LIST, [])
@_('NL BACK_IN_LINES', 'NL')
def BACK_IN_LINES(self, p):
print('BACK_IN_LINES', p[0])
#unused
return 'NL'
@_('assignment', 'expr')
def statement(self, p):
print('statement', p[0])
return ParsedOp(SupportedOp.STATEMENT, p[0])
@_('ID ASSIGN expr')
def assignment(self, p):
print('assignment', p[0], p[1], p[2])
return ParsedOp(SupportedOp.ASSIGNMENT, p[0], p[2])
@_('expr COMMA expr_list')
def expr_list(self, p):
print('expr_list', p[0], p[1], p[2])
lst: list = p[1].values[0]
lst.append(p[0])
return ParsedOp(SupportedOp.ARGS_LIST, lst)
@_('expr')
def expr_list(self, p):
print('expr_list', p[0])
return ParsedOp(SupportedOp.ARGS_LIST, [p[0]])
@_('empty')
def expr_list(self, p):
print('empty expr_list')
return ParsedOp(SupportedOp.ARGS_LIST, [])
@_('constant')
def expr(self, p):
print('expr', p[0])
return p[0]
@_('ID')
def expr(self, p):
print('expr', p[0])
return ParsedOp(SupportedOp.VARIABLE, p[0])
@_('LPAREN expr RPAREN')
def expr(self, p):
print('expr', p[0], p[1], p[2])
return p[1]
@_('ID LPAREN expr_list RPAREN')
def expr(self, p):
print('expr', p[0], p[1], p[2], p[3])
#if exists p.ID in functions
return ParsedOp(SupportedOp.FUNC_CALL, p.ID, p.expr_list)
@_( 'expr PLUS expr',
'expr MINUS expr',
'expr TIMES expr',
'expr DIVIDE expr')
def expr(self, p):
print('expr', p[0], p[1], p[2])
return ParsedOp(SupportedOp(p[1]), p[0], p[2])
@_('NUMBER', 'STRING', 'BOOL')
def constant(self, p):
print('constant', p[0])
return ParsedOp(SupportedOp.CONSTANT, p[0])
@_('')
def empty(self, p):
print('empty')
pass
def error(self, p):
if p:
print("Syntax error at token", p.type)
# Just discard the token and tell the parser it's okay.
self.errok()
else:
print("Syntax error at EOF")
I don't know if all my rules are ok but I commented every rule leaving uncommented only the "constant" rule which is straightforward, still can't recognize it.
Main:
tokens_out = lexer.ALexer().tokenize(event.get("code"))
tree = AParser().parse(tokens_out)
All my tokens are well recognized so the Lexer is ok. The parser can't recognize any rule. Any idea?
|
[
"As far as I can see, your code works fine up to the point at which you attempt to parse the second statement. I tried it with the input x=2 as suggested in your comment, and it produced the following result (pretty-printed with the pprint module):\n{ 'op': <SupportedOp.PROGRAM: 'PROGRAM'>,\n 'values': ( { 'op': <SupportedOp.STATEMENT_LIST: 'STATEMENT_LIST'>,\n 'values': ( [ { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,\n 'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,\n 'values': ( 'x',\n { 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,\n 'values': ( 2,)})},)}],)},)}\n\nBut once you try to parse two statements --say x=2 and y=2 on separate lines-- things start to fall apart.\nThere are several issues, which I'll try to deal with one at a time.\nThe first problem is that your NL lexer rule does not return anything, which means that no token is emitted. That means that the BACK_IN_LINES rule cannot match, because it is expecting to see one or more NL tokens. This generates a cascade of parser errors, which you should have seen on your console.\nIt's easy to get confused about the parser's progress. Since the parser doesn't see the NL token, what it sees is x = 2 y .... At the moment at which it sees the y, it hasn't yet reduced expr; after all, the next token might have been a + or other operator. But an ID is not one of the possible tokens which can follow 2, so a syntax error is thrown immediately, with the result that expr, statement and statement_list are not reduced, and so their reduction actions never execute, and thus you never see any of the debugging output you've put in the reduction actions. That doesn't really mean that the rule was not recognised; it would be more accurate to say that the rule was recognised but a longer match was still possible.\nIf you fix the lexer by adding return t at the end of the NL rule, then you run into the second problem, which is the reduction action for statement_list: statement BACK_IN_LINES statement_list. This bug causes the parse to fail even for an input consisting only of x=2, if that input is terminated with a newline character. The action is triggered because BACK_IN_LINES is now recognised, so the grammar requires that the statement_list has two subcomponents, a statement (x=2) and a statement_listconsisting of the rest of the input. The rest of the input is empty, which is OK because you allow astatement_list` to match an empty input. But, as I said, that causes the reduction action to execute, and that reduction action includes:\nlst: list = p[1].values[0]\n\nThat line has several problems. First, p[1] is the BACK_IN_LINES grammar symbol; you obviously intended to use p[2], which is the statement_list. So p[1] is the string NL, which doesn't have a values attribute. (That should be evident from the Python traceback, assuming that you can see the exception tracebacks. If you can't, you should seriously consider debugging in a Python console instead of whatever you are using.)\nBut when we fix it to use p[2] instead, we still get a Python TypeError exception. Instead of complaining that a str has no values attribute, it now complains that a builtin_function_or_method is not subscriptable. The builtin_function_or_method is the values method of a dict object, becasue p[2] is a SupportedOp, which is subclassed from dict. If you had intended to use the values method, you would have had to have called it, but I don't think that was what you intended (and therefore the values key is perhaps badly named). What you actually meant was the value associated with the values key, which means that the line should read:\nlst: list = p[2][\"values\"][0]\n\nBut that's still a bit problematic. Let's take a look at the parsed result of the input consisting of three lines:\nfirst = 1\nsecond = 2\nthird = 3\n\nThat produces (again, pretty printed with pprint):\n{ 'op': <SupportedOp.PROGRAM: 'PROGRAM'>,\n 'values': ( { 'op': <SupportedOp.STATEMENT_LIST: 'STATEMENT_LIST'>,\n 'values': ( [ { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,\n 'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,\n 'values': ( 'third',\n { 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,\n 'values': ( 3,)})},)},\n { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,\n 'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,\n 'values': ( 'second',\n { 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,\n 'values': ( 2,)})},)},\n { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,\n 'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,\n 'values': ( 'first',\n { 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,\n 'values': ( 1,)})},)}],)},)}\n\nIf you look carefully at that output, you'll see that the three statements are indeed there, but in the wrong order.\nThat's the result of your choosing to use a right-recursive rule for statement_list:\nstatement_list: statement BACK_IN_LINES statement_list\n\nRight-recursive rules are practically never correct for bottom-up parsers (such as the LALR(1) parser generated by Sly), although there are times when they are needed. If you can choose between a left-recursive rule and a right-recursive rule, your best option is the left-recursive rule:\nstatement_list: statement_list BACK_IN_LINES statement\n\nThis has two advantages. First, it doesn't require use of the parser stack to hold all the intermediate and incomplete subparses of statement_list until the end of the list is reached. More importantly, it executes the reduction actions for the recursive non-terminal in the order you probably expect them to be executed, which is left-to-right.\nThe right-recursive rule executes the reduction actions right-to-left, because the first recursive reduction is the last nested statement_list. And the consequence is that which we have already seen: the statements are appended to the statement_list in reverse order, starting with the last one.\nIt's easy to rewrite the rule as left-recursive. But if we do a naive change, we'll end up with a different problem. It's (probably) desirable that the input is allowed to but not required to end with a newline. That worked with the right-recursive production because statement_list was allowed to be empty. But that won't help with the left-recursive rule; a left-recursive rule with an empty option puts the empty option at the beginning of the list (precisely because it produces the list left-to-right). With the left-recursive rule, it's more convenient to allow statement to be empty. But instead of adding an \"empty statement\", which will clutter up the AST, we can just add a rule to statement_list which accepts an empty sequence instead of a statement. Once we do that, we eliminate the need for BACK_IN_LINES, because the grammatical logic is kept in statement_list.\nSo we can remove BACK_IN_LINES and replace the rules for statement_list with the following:\n @_('statement')\n def statement_list(self, p):\n print('statement_list', p[0])\n return ParsedOp(SupportedOp.STATEMENT_LIST, [p[0]])\n \n @_('empty')\n def statement_list(self, p):\n print('empty statement_list')\n return ParsedOp(SupportedOp.STATEMENT_LIST, [])\n \n @_('statement_list NL')\n def statement_list(self, p):\n print('statement_list', p[0])\n return p[0]\n \n @_('statement_list NL statement')\n def statement_list(self, p):\n print('statement_list', p[0], p[1], p[2])\n lst: list = p[0][\"values\"][0]\n lst.append(p[2])\n return ParsedOp(SupportedOp.STATEMENT_LIST, lst)\n\nNow, finally, we get the expected parse:\n{ 'op': <SupportedOp.PROGRAM: 'PROGRAM'>,\n 'values': ( { 'op': <SupportedOp.STATEMENT_LIST: 'STATEMENT_LIST'>,\n 'values': ( [ { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,\n 'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,\n 'values': ( 'first',\n { 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,\n 'values': ( 1,)})},)},\n { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,\n 'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,\n 'values': ( 'second',\n { 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,\n 'values': ( 2,)})},)},\n { 'op': <SupportedOp.STATEMENT: 'STATEMENT'>,\n 'values': ( { 'op': <SupportedOp.ASSIGNMENT: '='>,\n 'values': ( 'third',\n { 'op': <SupportedOp.CONSTANT: 'CONSTANT'>,\n 'values': ( 3,)})},)}],)},)}\n\n"
] |
[
1
] |
[] |
[] |
[
"parsing",
"ply",
"python",
"sly",
"token"
] |
stackoverflow_0074509434_parsing_ply_python_sly_token.txt
|
Q:
Having a difficult time reading a certain Binary file with Python
I am working on a mod for a game and all of the games strings are in a file called a .dat file. Its a binary file and I'm pretty sure I am missing quite a few strings that I need to add. I have a way to add them into the file I just don't have a way to search for every instance of a missing string. So I decided to write a program to find the missing strings for me. The only problem is I don't know how to open a binary file. Can anyone help me out here. I've included the file I'm using and a link to the .dat editor just in case you want so see what the end result is.
Ive tried to open a binary file the way that others have explained using
with open(dat_file_location, mode='rb') as file:
fileContent = file.read()
print(fileContent)
but all I get back in my terminal are hundreds of lines that look like this
00d\x00a\x00r\x00k\x00 \x00m\x00i\x00n\x00e\x00s\x00,\x00 \x00w\x00h\x00e\x00r\x00e\x00
A:
Since it's binary you need to know exact format of data. Looking at file I see there is some header and then at offset 0x0038790 string block begins.
Google for <game title> file format to get idea how to properly parse it or reverse engineer it yourself (there is guide how to do it for another game). btw I think distributing game data files this way is illegal :)
from site you linked we can read that *.DAT- Language files. All text in the game is defined here. Similar to Command and Conquer Generals csf file.
Probably there is description of file format somewhere on another page
|
Having a difficult time reading a certain Binary file with Python
|
I am working on a mod for a game and all of the games strings are in a file called a .dat file. Its a binary file and I'm pretty sure I am missing quite a few strings that I need to add. I have a way to add them into the file I just don't have a way to search for every instance of a missing string. So I decided to write a program to find the missing strings for me. The only problem is I don't know how to open a binary file. Can anyone help me out here. I've included the file I'm using and a link to the .dat editor just in case you want so see what the end result is.
Ive tried to open a binary file the way that others have explained using
with open(dat_file_location, mode='rb') as file:
fileContent = file.read()
print(fileContent)
but all I get back in my terminal are hundreds of lines that look like this
00d\x00a\x00r\x00k\x00 \x00m\x00i\x00n\x00e\x00s\x00,\x00 \x00w\x00h\x00e\x00r\x00e\x00
|
[
"Since it's binary you need to know exact format of data. Looking at file I see there is some header and then at offset 0x0038790 string block begins.\nGoogle for <game title> file format to get idea how to properly parse it or reverse engineer it yourself (there is guide how to do it for another game). btw I think distributing game data files this way is illegal :)\n\nfrom site you linked we can read that *.DAT- Language files. All text in the game is defined here. Similar to Command and Conquer Generals csf file.\nProbably there is description of file format somewhere on another page\n"
] |
[
0
] |
[] |
[] |
[
"binaryfiles",
"python"
] |
stackoverflow_0074513380_binaryfiles_python.txt
|
Q:
Validation Error when filtering by UUID Django
I am attempting to return all the friends of friends of a certain user who is the author of the relationship.
However, I keep getting this error:
ValidationError at /author/posts
["“[UUID('8c02a503-7784-42f0-a367-1876bbfad6ff')]” is not a valid UUID."]
class Author(AbstractUser):
...
uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False, unique=True)
...
class Post(models.Model):
...
author = models.ForeignKey(Author, on_delete=models.CASCADE)
...
class Friend(models.Model):
class Meta:
unique_together = (('author','friend'),)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author')
friend = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='friend')
This foaf line in particular is where the error is coming from. How else could I do this?
friends = Friend.objects.filter(author=userUUID)
foafs = Friend.objects.filter(friend=[friend.friend.uuid for friend in friends])
A:
I'm seeing two things to fix here:
The lookup should be friend__in 'cause you are passing a list o UUIDs.
You need to convert the UUID object to a string using friend.friend.uuid)
The solution proposed is the follwing:
foafs = Friend.objects.filter(friend__in=[str(friend.friend.uuid) for friend in friends])
|
Validation Error when filtering by UUID Django
|
I am attempting to return all the friends of friends of a certain user who is the author of the relationship.
However, I keep getting this error:
ValidationError at /author/posts
["“[UUID('8c02a503-7784-42f0-a367-1876bbfad6ff')]” is not a valid UUID."]
class Author(AbstractUser):
...
uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False, unique=True)
...
class Post(models.Model):
...
author = models.ForeignKey(Author, on_delete=models.CASCADE)
...
class Friend(models.Model):
class Meta:
unique_together = (('author','friend'),)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author')
friend = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='friend')
This foaf line in particular is where the error is coming from. How else could I do this?
friends = Friend.objects.filter(author=userUUID)
foafs = Friend.objects.filter(friend=[friend.friend.uuid for friend in friends])
|
[
"I'm seeing two things to fix here:\n\nThe lookup should be friend__in 'cause you are passing a list o UUIDs.\nYou need to convert the UUID object to a string using friend.friend.uuid)\n\nThe solution proposed is the follwing:\nfoafs = Friend.objects.filter(friend__in=[str(friend.friend.uuid) for friend in friends])\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_models",
"django_rest_framework",
"python",
"validation"
] |
stackoverflow_0060795135_django_django_models_django_rest_framework_python_validation.txt
|
Q:
Pandas dataframe plot 's' argument
I have the statement and I really don't understand the s= part. I know it sets the area of the plot but is it taking the data from pop_2007 and raising it to 1^6 to create the area ?
df.plot(kind='scatter', x='gdp_2007', y='lifeExp_2007', s=df['pop_2007']/1e6)
I'm trying to understand the area of a plot better and the s=
A:
The 's' parameter in the pandas dataframe plot function is changing the size of the markers in your scatter plot. See these two outputs where I change the 's' value from 1 to 100. So right now, your plot is taking the value in the df['pop_2007'] column and dividing it by 1e6 to get your value for the marker size.
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
df.plot(kind = 'scatter', x = 'Duration', y = 'Maxpulse', s=1)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Plot with s=1
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
df.plot(kind = 'scatter', x = 'Duration', y = 'Maxpulse', s=100)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Plot with s=100
Test it out here: https://www.w3schools.com/python/pandas/trypandas.asp?filename=demo_pandas_plot_scatter2
|
Pandas dataframe plot 's' argument
|
I have the statement and I really don't understand the s= part. I know it sets the area of the plot but is it taking the data from pop_2007 and raising it to 1^6 to create the area ?
df.plot(kind='scatter', x='gdp_2007', y='lifeExp_2007', s=df['pop_2007']/1e6)
I'm trying to understand the area of a plot better and the s=
|
[
"The 's' parameter in the pandas dataframe plot function is changing the size of the markers in your scatter plot. See these two outputs where I change the 's' value from 1 to 100. So right now, your plot is taking the value in the df['pop_2007'] column and dividing it by 1e6 to get your value for the marker size.\n#Three lines to make our compiler able to draw:\nimport sys\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv('data.csv')\n\ndf.plot(kind = 'scatter', x = 'Duration', y = 'Maxpulse', s=1)\n\nplt.show()\n\n#Two lines to make our compiler able to draw:\nplt.savefig(sys.stdout.buffer)\nsys.stdout.flush()\n\nPlot with s=1\n#Three lines to make our compiler able to draw:\nimport sys\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv('data.csv')\n\ndf.plot(kind = 'scatter', x = 'Duration', y = 'Maxpulse', s=100)\n\nplt.show()\n\n#Two lines to make our compiler able to draw:\nplt.savefig(sys.stdout.buffer)\nsys.stdout.flush()\n\nPlot with s=100\nTest it out here: https://www.w3schools.com/python/pandas/trypandas.asp?filename=demo_pandas_plot_scatter2\n"
] |
[
0
] |
[] |
[] |
[
"matplotlib",
"pandas",
"plot",
"python"
] |
stackoverflow_0074513477_matplotlib_pandas_plot_python.txt
|
Q:
4D heat map in matplotlib
I want to plot a 4D heatmap in Python through matplotlib, like this 4d map.
I have already a set of 3D grid points (x,y,z) and its corresponding function value f.
I am thinking of plotting it using plot_surface with x, y, z as the three required arrays, and alter the color gradient using f.
There is a way here to use f for the color gradient, but I have trouble plotting the 3D grid, which I will emphasize that the third dimension is independent of the first two. (The second link shows otherwise.)
Or are there any way to better visualize this 4D data using matplotlib?
A:
Your data is of a slightly different form I imagine, but as long as you have a point for every thing you need to be plotted you could use something like they did here:
How to make a 4d plot using Python with matplotlib
A:
There aren't great existing ways to visualize true 4D functions (where the third dimension is independent of the first two as you described), so I wrote a small package plot4d. It should be able to help you visualize your function.
from plot4d import plotter
f = lambda x, y, z: sin(x)*y*cos(z)-x**3
z_range = np.linspace(0,2,10)
frame = plotter.Frame2D(xmin=0, xmax=1, ymin=0, ymax=1)
plotter.plot4d(f, z_range, frame=frame, func_name='f')
Installation:
pip install plot4d
|
4D heat map in matplotlib
|
I want to plot a 4D heatmap in Python through matplotlib, like this 4d map.
I have already a set of 3D grid points (x,y,z) and its corresponding function value f.
I am thinking of plotting it using plot_surface with x, y, z as the three required arrays, and alter the color gradient using f.
There is a way here to use f for the color gradient, but I have trouble plotting the 3D grid, which I will emphasize that the third dimension is independent of the first two. (The second link shows otherwise.)
Or are there any way to better visualize this 4D data using matplotlib?
|
[
"Your data is of a slightly different form I imagine, but as long as you have a point for every thing you need to be plotted you could use something like they did here:\nHow to make a 4d plot using Python with matplotlib\n",
"There aren't great existing ways to visualize true 4D functions (where the third dimension is independent of the first two as you described), so I wrote a small package plot4d. It should be able to help you visualize your function.\nfrom plot4d import plotter\nf = lambda x, y, z: sin(x)*y*cos(z)-x**3\nz_range = np.linspace(0,2,10)\nframe = plotter.Frame2D(xmin=0, xmax=1, ymin=0, ymax=1)\nplotter.plot4d(f, z_range, frame=frame, func_name='f')\n\n\nInstallation:\npip install plot4d\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"4d",
"matplotlib",
"python"
] |
stackoverflow_0042250095_4d_matplotlib_python.txt
|
Q:
Checking if a function from the sources of a website is executed
With the "Inspect Element" option in a common browser it is possible to access the "Sources" tab and, not only see the files which the website uses, but also mark a line of code (as shown in the image below at line 463 with a .js file), which will make the browser pause when that line of code is executed (essentially a debugger). In this sense, it seems possible to check if a certain line of code is executed, which is what I need to finish an automation with Python, preferably with Selenium, but which I also don't know how to do.
A:
Selenium tests are intended to be "black box". That is, you load a page and only access the things that are available in the browser window to verify that behavior is correct. You should NOT try to verify that specific parts of code were written. Even if you can figure out a way to do this, it will make your tests extremely brittle.
If you are writing the JavaScript code, then I suggest using a framework such as Jest or Mocha to test it directly. You still shouldn't verify that a specific line of code is executed, but you can test a function by calling it directly and checking the return value or side effects to make sure they are correct.
|
Checking if a function from the sources of a website is executed
|
With the "Inspect Element" option in a common browser it is possible to access the "Sources" tab and, not only see the files which the website uses, but also mark a line of code (as shown in the image below at line 463 with a .js file), which will make the browser pause when that line of code is executed (essentially a debugger). In this sense, it seems possible to check if a certain line of code is executed, which is what I need to finish an automation with Python, preferably with Selenium, but which I also don't know how to do.
|
[
"Selenium tests are intended to be \"black box\". That is, you load a page and only access the things that are available in the browser window to verify that behavior is correct. You should NOT try to verify that specific parts of code were written. Even if you can figure out a way to do this, it will make your tests extremely brittle.\nIf you are writing the JavaScript code, then I suggest using a framework such as Jest or Mocha to test it directly. You still shouldn't verify that a specific line of code is executed, but you can test a function by calling it directly and checking the return value or side effects to make sure they are correct.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x",
"selenium",
"selenium_webdriver",
"web_scraping"
] |
stackoverflow_0074513493_python_python_3.x_selenium_selenium_webdriver_web_scraping.txt
|
Q:
Need help to solve a calculation issue and how to make a continuous list of elements for same input
Need help to solve a calculation issue and how to make a continuous list of elements for same input
Code itself
`
for T in range(12):
AskP1= str(input("Did the first player win, draw or lose, pick the correspoding letter: W,L,D "))
AskP2 = str(input("Did the second player win, draw or lose, pick the correspoding letter: W,L,D "))
def scorefunc(X,Y,T):
P1 = 0
P1A = []
P2 = 0
P2A = []
if X == "W" or "w":
P1 = P1 + 2
P1A.append("W")
if X == "D" or "d":
P1 = P1 + 1
P1A.append("D")
if X == "L" or "l":
P1 = P1 + 0
P1A.append("L")
if Y == "W" or "w":
P2 = P2 + 2
P2A.append("W")
if Y == "D" or "d":
P2 = P2 + 1
P2A.append("D")
if Y == "L" or "l":
P2 = P2 + 0
P2A.append("L")
if T == 11:
Data1 = print("The first player achieved a score of",P1,"/24."," The list of wins,draws and losses: ",P1A)
Data2 = print("The second player achieved a score of",P2,"/24."," The list of wins,draws and losses: ",P2A)
scorefunc(AskP1,AskP2,T)
`
Output:
For example if I just spam "W" I end up with:
The first player achieved a score of 3 /24. The list of wins, draws and losses: ['W', 'D', 'L']
The second player achieved a score of 3 /24. The list of wins, draws and losses: ['W', 'D', 'L']
or
I spam "L" also I end up with the same response of:
The first player achieved a score of 3 /24. The list of wins, draws and losses: ['W', 'D', 'L']
The second player achieved a score of 3 /24. The list of wins, draws and losses: ['W', 'D', 'L']
How can I fix the actual score given out of 24 and the list to output the pattern in which they inputted something E.g like if they won 3 games first time, lost one after and drew one it would be like [W,W,W,L,D]
Any alterations would be welcome
Thanks in advance
A:
if X == "W" or "w":
Changed to
if X == "W" or X == "w":
Because bool('w') always equals True
Here's my adjusted program
P1A = []
P2A = []
P1 = 0
P2 = 0
times = 3
for T in range(times):
X = str(
input(
"Did the first player win, draw or lose, pick the correspoding letter: W,L,D "
))
Y = str(
input(
"Did the second player win, draw or lose, pick the correspoding letter: W,L,D "
))
if X == "W" or X == "w":
P1 = P1 + 2
P1A.append("W")
elif X == "D" or X == "d":
P1 = P1 + 1
P1A.append("D")
elif X == "L" or X == "l":
P1 = P1 + 0
P1A.append("L")
if Y == "W" or Y == "w":
P2 = P2 + 2
P2A.append("W")
elif Y == "D" or Y == "d":
P2 = P2 + 1
P2A.append("D")
elif Y == "L" or Y == "l":
P2 = P2 + 0
P2A.append("L")
Data1 = print("The first player achieved a score of ",
P1,
f"/{times*2}.",
" The list of wins,draws and losses: ",
P1A,
sep="")
Data2 = print("The second player achieved a score of ",
P2,
f"/{times*2}.",
" The list of wins,draws and losses: ",
P2A,
sep="")
|
Need help to solve a calculation issue and how to make a continuous list of elements for same input
|
Need help to solve a calculation issue and how to make a continuous list of elements for same input
Code itself
`
for T in range(12):
AskP1= str(input("Did the first player win, draw or lose, pick the correspoding letter: W,L,D "))
AskP2 = str(input("Did the second player win, draw or lose, pick the correspoding letter: W,L,D "))
def scorefunc(X,Y,T):
P1 = 0
P1A = []
P2 = 0
P2A = []
if X == "W" or "w":
P1 = P1 + 2
P1A.append("W")
if X == "D" or "d":
P1 = P1 + 1
P1A.append("D")
if X == "L" or "l":
P1 = P1 + 0
P1A.append("L")
if Y == "W" or "w":
P2 = P2 + 2
P2A.append("W")
if Y == "D" or "d":
P2 = P2 + 1
P2A.append("D")
if Y == "L" or "l":
P2 = P2 + 0
P2A.append("L")
if T == 11:
Data1 = print("The first player achieved a score of",P1,"/24."," The list of wins,draws and losses: ",P1A)
Data2 = print("The second player achieved a score of",P2,"/24."," The list of wins,draws and losses: ",P2A)
scorefunc(AskP1,AskP2,T)
`
Output:
For example if I just spam "W" I end up with:
The first player achieved a score of 3 /24. The list of wins, draws and losses: ['W', 'D', 'L']
The second player achieved a score of 3 /24. The list of wins, draws and losses: ['W', 'D', 'L']
or
I spam "L" also I end up with the same response of:
The first player achieved a score of 3 /24. The list of wins, draws and losses: ['W', 'D', 'L']
The second player achieved a score of 3 /24. The list of wins, draws and losses: ['W', 'D', 'L']
How can I fix the actual score given out of 24 and the list to output the pattern in which they inputted something E.g like if they won 3 games first time, lost one after and drew one it would be like [W,W,W,L,D]
Any alterations would be welcome
Thanks in advance
|
[
"if X == \"W\" or \"w\":\nChanged to\nif X == \"W\" or X == \"w\":\nBecause bool('w') always equals True\nHere's my adjusted program\nP1A = []\nP2A = []\nP1 = 0\nP2 = 0\ntimes = 3\nfor T in range(times):\n X = str(\n input(\n \"Did the first player win, draw or lose, pick the correspoding letter: W,L,D \"\n ))\n Y = str(\n input(\n \"Did the second player win, draw or lose, pick the correspoding letter: W,L,D \"\n ))\n\n if X == \"W\" or X == \"w\":\n P1 = P1 + 2\n P1A.append(\"W\")\n elif X == \"D\" or X == \"d\":\n P1 = P1 + 1\n P1A.append(\"D\")\n elif X == \"L\" or X == \"l\":\n P1 = P1 + 0\n P1A.append(\"L\")\n if Y == \"W\" or Y == \"w\":\n P2 = P2 + 2\n P2A.append(\"W\")\n elif Y == \"D\" or Y == \"d\":\n P2 = P2 + 1\n P2A.append(\"D\")\n elif Y == \"L\" or Y == \"l\":\n P2 = P2 + 0\n P2A.append(\"L\")\n\nData1 = print(\"The first player achieved a score of \",\n P1,\n f\"/{times*2}.\",\n \" The list of wins,draws and losses: \",\n P1A,\n sep=\"\")\nData2 = print(\"The second player achieved a score of \",\n P2,\n f\"/{times*2}.\",\n \" The list of wins,draws and losses: \",\n P2A,\n sep=\"\")\n\n"
] |
[
0
] |
[] |
[] |
[
"arrays",
"input",
"list",
"output",
"python"
] |
stackoverflow_0074513290_arrays_input_list_output_python.txt
|
Q:
How do I return the rows of DataFrame where every Country in each Continent has a Population of less of than 100?
df = pd.DataFrame({
"Continent": list("AAABBBCCD"),
"Country": list("FGHIJKLMN"),
"Population": [90, 140, 50, 80, 80, 70, 50, 125, 50]})
As explained, I want to return all of the rows, where all countries in each continent are less than 100.
Continent Country Population
0 A F 90
1 A G 140
2 A H 50
3 B I 80
4 B J 80
5 B K 70
6 C L 50
7 C M 125
8 D N 50
Every row in Continent A is removed because Country G has a population greater than 100. Every row in Continent C is removed because of Country M. I want the returned DataFrame to look like below:
Continent Country Population
3 B I 80
4 B J 80
5 B K 70
8 D N 50
I tried df[df["Population"] <= 100] but couldn't determine how to adjust for Continent.
A:
here is one way to do it
# groupby on continent
# using makes the row True/False, whether max for the group is below 100
out=df[df.groupby(['Continent'])['Population'].transform(lambda x: x.max()<100)]
out
Continent Country Population
3 B I 80
4 B J 80
5 B K 70
8 D N 50
A:
Here is another way to accomplish it
import pandas as pd
df = pd.DataFrame({
"Continent": list("AAABBBCCD"),
"Country": list("FGHIJKLMN"),
"Population": [90, 140, 50, 80, 80, 70, 50, 125, 50]})
df.loc[df.groupby(['Continent'])['Population'].transform('max') <= 100]
I usually don't like using lambda since it is so slow, but the above answer also works. This is just another option
|
How do I return the rows of DataFrame where every Country in each Continent has a Population of less of than 100?
|
df = pd.DataFrame({
"Continent": list("AAABBBCCD"),
"Country": list("FGHIJKLMN"),
"Population": [90, 140, 50, 80, 80, 70, 50, 125, 50]})
As explained, I want to return all of the rows, where all countries in each continent are less than 100.
Continent Country Population
0 A F 90
1 A G 140
2 A H 50
3 B I 80
4 B J 80
5 B K 70
6 C L 50
7 C M 125
8 D N 50
Every row in Continent A is removed because Country G has a population greater than 100. Every row in Continent C is removed because of Country M. I want the returned DataFrame to look like below:
Continent Country Population
3 B I 80
4 B J 80
5 B K 70
8 D N 50
I tried df[df["Population"] <= 100] but couldn't determine how to adjust for Continent.
|
[
"here is one way to do it\n# groupby on continent\n# using makes the row True/False, whether max for the group is below 100\nout=df[df.groupby(['Continent'])['Population'].transform(lambda x: x.max()<100)]\nout\n\n\nContinent Country Population\n3 B I 80\n4 B J 80\n5 B K 70\n8 D N 50\n\n",
"Here is another way to accomplish it\nimport pandas as pd\n\ndf = pd.DataFrame({\n \"Continent\": list(\"AAABBBCCD\"), \n \"Country\": list(\"FGHIJKLMN\"), \n \"Population\": [90, 140, 50, 80, 80, 70, 50, 125, 50]})\n\ndf.loc[df.groupby(['Continent'])['Population'].transform('max') <= 100]\n\nI usually don't like using lambda since it is so slow, but the above answer also works. This is just another option\n"
] |
[
0,
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"pandas_loc",
"python"
] |
stackoverflow_0074513188_dataframe_pandas_pandas_loc_python.txt
|
Q:
kwargs different behavior
Dear pythonist that question is for you!
I don't ask to solve my task, just ask for explaining why it happens)
I know what is args and kwargs when they using but has been really shoked, when have found one thing. So, please check my example, here we pass arguments to the function
def firstFunc(*args, **kwargs):
print('args' )
print(args)
print('kwargs')
print(kwargs)
firstFunc([1, 2], {'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'})
My second question is, why we can get the dictonary from the second function,
if we will set it like this kwargs['second'] = 222,
that's my code
def firstFunc(*args, **kwargs):
print('args' )
print(*args)
print('kwargs')
print(**kwargs)
kwargs['second'] = 222
secondFunc([1, 2], **kwargs)
def secondFunc(*args, **kwargs):
print('args' )
print(args)
print('kwargs')
print(kwargs)
firstFunc([1, 2], {'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'})
hope I described understandable, I am waiting for u answer, please tell me why it hapens, and why I cannot just pass dictionarie as kwargs!
many thanks for u
#python #pythonic #kwargs #args #functions
I expected just mine dictionary in kwargs
A:
You're passing the list and the dictionary as two positional arguments, so those two positional arguments are what shows up in your *args in the function body, and **kwargs is an empty dictionary since no keyword arguments were provided.
If you want to pass each element of the list as its own positional argument, use the * operator:
firstFunc(*[1, 2])
If you want to also pass each element of the dictionary as a keyword argument, use the ** operator:
firstFunc(
*[1, 2],
**{'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'}
)
This is equivalent to doing:
firstFunc(
1,
2,
firstFirst='firstFirst',
first='123',
second='999'
)
|
kwargs different behavior
|
Dear pythonist that question is for you!
I don't ask to solve my task, just ask for explaining why it happens)
I know what is args and kwargs when they using but has been really shoked, when have found one thing. So, please check my example, here we pass arguments to the function
def firstFunc(*args, **kwargs):
print('args' )
print(args)
print('kwargs')
print(kwargs)
firstFunc([1, 2], {'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'})
My second question is, why we can get the dictonary from the second function,
if we will set it like this kwargs['second'] = 222,
that's my code
def firstFunc(*args, **kwargs):
print('args' )
print(*args)
print('kwargs')
print(**kwargs)
kwargs['second'] = 222
secondFunc([1, 2], **kwargs)
def secondFunc(*args, **kwargs):
print('args' )
print(args)
print('kwargs')
print(kwargs)
firstFunc([1, 2], {'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'})
hope I described understandable, I am waiting for u answer, please tell me why it hapens, and why I cannot just pass dictionarie as kwargs!
many thanks for u
#python #pythonic #kwargs #args #functions
I expected just mine dictionary in kwargs
|
[
"You're passing the list and the dictionary as two positional arguments, so those two positional arguments are what shows up in your *args in the function body, and **kwargs is an empty dictionary since no keyword arguments were provided.\nIf you want to pass each element of the list as its own positional argument, use the * operator:\nfirstFunc(*[1, 2])\n\nIf you want to also pass each element of the dictionary as a keyword argument, use the ** operator:\nfirstFunc(\n *[1, 2],\n **{'firstFirst': 'firstFirst', 'first' : '123', 'second' : '999'}\n)\n\nThis is equivalent to doing:\nfirstFunc(\n 1,\n 2,\n firstFirst='firstFirst',\n first='123',\n second='999'\n)\n\n"
] |
[
1
] |
[
"Thank you guys !\nI found the difference when I passing arguments, that for first function I didn't passed ** with argument(applied expanding), but for second functtion I passed it(applied expanding), just my syntax mistake. but what conclusion when we can make - that if u passing dictionarie as kwargs always use **(always expand it), otherwise it will be just element of the list(*args)\nBest regards to all!\n"
] |
[
-1
] |
[
"function",
"keyword_argument",
"python"
] |
stackoverflow_0074513447_function_keyword_argument_python.txt
|
Q:
Better way to write this code? 3D position update of an object
I have an array for the position of the particle in cartesian coordinates and velocity in 3D. So that position[0] represents the x component of the position and so on. I'm curious if there is a better way to write this code, maybe shorter, maybe faster.
`
def update_position(self):
self.position[0] = self.position[0] + self.velocity[0] * self.tick # x coordinate update
self.position[1] = self.position[1] + self.velocity[1] * self.tick # y coordinate update
self.position[2] = self.position[2] + self.velocity[2] * self.tick # z coordinate update
...
`
A:
def update_position(self):
for i in range(3):
self.position[i] += self.velocity[i] * self.tick
A:
Just use the numpy library. It's a lot faster and easier to use. Here's an example of how to use it:
import numpy as np
...
def __init__(self):
self.position = np.array([0.0, 0.0, 0.0])
self.velocity = np.array([1.0, 1.0, 1.0])
...
self.position += self.velocity * self.tick
|
Better way to write this code? 3D position update of an object
|
I have an array for the position of the particle in cartesian coordinates and velocity in 3D. So that position[0] represents the x component of the position and so on. I'm curious if there is a better way to write this code, maybe shorter, maybe faster.
`
def update_position(self):
self.position[0] = self.position[0] + self.velocity[0] * self.tick # x coordinate update
self.position[1] = self.position[1] + self.velocity[1] * self.tick # y coordinate update
self.position[2] = self.position[2] + self.velocity[2] * self.tick # z coordinate update
...
`
|
[
"def update_position(self):\n for i in range(3):\n self.position[i] += self.velocity[i] * self.tick\n\n",
"Just use the numpy library. It's a lot faster and easier to use. Here's an example of how to use it:\nimport numpy as np\n...\ndef __init__(self):\n self.position = np.array([0.0, 0.0, 0.0])\n self.velocity = np.array([1.0, 1.0, 1.0])\n...\nself.position += self.velocity * self.tick\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"multidimensional_array",
"optimization",
"python"
] |
stackoverflow_0074513537_multidimensional_array_optimization_python.txt
|
Q:
Perl to python open() command translation
How do I write open(SCRPT, ">$script") or die...; in python??
Im trying to run a script in python to automate a slurm job. For that, I am trying to create and open a file names SCRPT and write a block of code to be read and executed.
Is it
SCRPT = open(script)
with open(SCRPT)
A:
The builtin open is typically used to create a filehandle. open raises IOError if anything goes wrong. The functional equivalent of open(SCRIPT,">$script") or die $error_message would be
import sys
try:
script = open("script", "w")
except IOError as ioe:
print(error_message, file=sys.stderr)
sys.exit(1)
A:
File IO in Python is most commonly done using the with ... as operators and the open function, like so:
script = '/path/to/some/script.sh'
with open(script, 'w') as file:
file.write(
'#!/bin/bash\n'
'echo hello world\n'
)
os.chmod(script, 0o755) # optional
Note: You only need to do the os.chmod if you need the new script to be directly executed.
|
Perl to python open() command translation
|
How do I write open(SCRPT, ">$script") or die...; in python??
Im trying to run a script in python to automate a slurm job. For that, I am trying to create and open a file names SCRPT and write a block of code to be read and executed.
Is it
SCRPT = open(script)
with open(SCRPT)
|
[
"The builtin open is typically used to create a filehandle. open raises IOError if anything goes wrong. The functional equivalent of open(SCRIPT,\">$script\") or die $error_message would be\nimport sys\ntry:\n script = open(\"script\", \"w\")\nexcept IOError as ioe:\n print(error_message, file=sys.stderr)\n sys.exit(1)\n\n",
"File IO in Python is most commonly done using the with ... as operators and the open function, like so:\nscript = '/path/to/some/script.sh'\nwith open(script, 'w') as file:\n file.write(\n '#!/bin/bash\\n'\n 'echo hello world\\n'\n )\nos.chmod(script, 0o755) # optional\n\nNote: You only need to do the os.chmod if you need the new script to be directly executed.\n"
] |
[
2,
1
] |
[] |
[] |
[
"perl",
"python"
] |
stackoverflow_0074513104_perl_python.txt
|
Q:
ValueError: 'images' must have either 3 or 4 dimensions. in Colab
I do object detection with tensorflow in Google Colab. I'm trying to get video from the webcam. This is the last stage. But I am getting the error below continent.How can I size the pictures?
ValueError: in user code:
<ipython-input-49-1e7efe9130ee>:11 detect_fn *
image, shapes = detection_model.preprocess(image)
/usr/local/lib/python3.7/dist-packages/object_detection/meta_architectures/ssd_meta_arch.py:484 preprocess *
normalized_inputs, self._image_resizer_fn)
/usr/local/lib/python3.7/dist-packages/object_detection/utils/shape_utils.py:492 resize_images_and_return_shapes *
outputs = static_or_dynamic_map_fn(
/usr/local/lib/python3.7/dist-packages/object_detection/utils/shape_utils.py:246 static_or_dynamic_map_fn *
outputs = [fn(arg) for arg in tf.unstack(elems)]
/usr/local/lib/python3.7/dist-packages/object_detection/core/preprocessor.py:3241 resize_image *
new_image = tf.image.resize_images(
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper **
return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/image_ops_impl.py:1468 resize_images
skip_resize_if_same=True)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/image_ops_impl.py:1320 _resize_images_common
raise ValueError('\'images\' must have either 3 or 4 dimensions.')
ValueError: 'images' must have either 3 or 4 dimensions.
How can i solve?
All Code:
while True:
ret, frame = cap.read()
image_np = np.array(frame)
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
detections = detect_fn(input_tensor)
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
label_id_offset = 1
image_np_with_detections = image_np.copy()
viz_utils.visualize_boxes_and_labels_on_image_array(
image_np_with_detections,
detections['detection_boxes'],
detections['detection_classes']+label_id_offset,
detections['detection_scores'],
category_index,
use_normalized_coordinates=True,
max_boxes_to_draw=5,
min_score_thresh=.5,
agnostic_mode=False)
cv2.imshow('object detection', cv2.resize(image_np_with_detections, (800, 600)))
if cv2.waitKey(1) & 0xFF == ord('q'):
cap.release()
break
A:
Verify that you are getting an image frame from the following line:
ret, frame = cap.read()
When I got the same error (albeit slightly different code), I was pointing to a non-existent directory rather than an image.
A:
cap = cv2.VideoCapture(0)
Try to listen with different values ranging between 0,1,2.... Worked for mine.
A:
maybe u should try this...u just got error from ur webcam, as specifically u got lag between ur webcam and ur system, and the solution is u need to change ur code cv2.waitKey(1) & 0xFF == ord('q'): to key == ord('q'): and before if u should add key = cv2.waitKey(1) & 0xFF and at the end of ur line add this cap.release() and this cv2.destroyAllWindows()
A:
Note: This problem may occur If you are using RTSP.
I was almost working on a license plate recognition program.
I had almost the same problem as you
When the program was running, it crashed after the first few seconds
Of course, I searched the web a lot, but I did not get anywhere. I made any changes to the camera settings that you can think of. I changed the whole code, I tried a lot and finally realized the problem.
The problem with the RTSP protocol is that you should know that RTSP runs on the UDP platform and UDP has no warranty or, in other words, no responsibility for packets. They do not have to reach their destination completely. Unlike TCP, what happens is that you may not receive any frame while running your program.
What exactly does the error tell us?
It tells us that I was expecting to receive image with 3 or 4 dimension but did not receive it, Or rather, It did not receive anything.
So you should be using Try and Except In Python For handling This Problem for if not frame captured App Does Not crash and It Does reconnect the RTSP.
Here is what you need:
cap = cv2.VideoCapture("rtsp://admin:admin@192.168.1.2:554/1/1")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS)) # Get video framerate
while True:
try:
ret, frame = cap.read()
if frame is None:
print("disconnected!")
image_np = np.array(frame)
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
detections = detect_fn(input_tensor)
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
label_id_offset = 1
image_np_with_detections = image_np.copy()
viz_utils.visualize_boxes_and_labels_on_image_array(
image_np_with_detections,
detections['detection_boxes'],
detections['detection_classes']+label_id_offset,
detections['detection_scores'],
category_index,
use_normalized_coordinates=True,
max_boxes_to_draw=5,
min_score_thresh=.8,
agnostic_mode=False)
#Extract Plate Shape On Entire Image
detection_thereshold = 0.7
image = image_np_with_detections
scores = list(filter(lambda x: x> detection_thereshold, detections['detection_scores']))
boxes = detections['detection_boxes'][:len(scores)]
classes = detections['detection_classes'][:len(scores)]
width = image.shape[1]
height = image.shape[0]
cv2.imshow('object detection', cv2.resize(image_np_with_detections, (800, 600)))
if cv2.waitKey(10) & 0xFF == ord('q'):
cap.release()
cv2.destroyAllWindows()
break
except:
cap.release()
cap = cv2.VideoCapture("rtsp://admin:admin@192.168.1.2:554/1/1")
print("Reconnected!")
continue
In the except section, as you can see, we re-create the RTSP connection.
You can use this app with no problem now.
I hope this helped you.
A:
I solved this issue by uninstalling OpenCV-python and reinstalling it.
$pip uninstall opencv-python
$pip install opencv-python
restart the kernel & ta-da....
A:
First Check the if the image is being captured or not in this point image_np = np.array(frame). because it shows there is no dimension so there is no image.
A:
I had a slightly different root cause but with the same error,
image_path_jpg = "path_to.jpg"
img = tf.io.read_file(image_path_jpg)
img_resized = tf.image.resize(img, [100, 100])
Also produced
ValueError: 'images' must have either 3 or 4 dimensions.
For me solution turned out I was missing the decoding step,
image_path_jpg = "path_to.jpg"
img = tf.io.read_file(image_path_jpg)
img.get_shape().as_list() # []
img = tf.image.decode_jpeg(img)
img.get_shape().as_list() # [300, 400, 3]
img_resized = tf.image.resize(img, [100, 100])
img_resized.get_shape().as_list() # [100, 100, 3]
No more errors.
|
ValueError: 'images' must have either 3 or 4 dimensions. in Colab
|
I do object detection with tensorflow in Google Colab. I'm trying to get video from the webcam. This is the last stage. But I am getting the error below continent.How can I size the pictures?
ValueError: in user code:
<ipython-input-49-1e7efe9130ee>:11 detect_fn *
image, shapes = detection_model.preprocess(image)
/usr/local/lib/python3.7/dist-packages/object_detection/meta_architectures/ssd_meta_arch.py:484 preprocess *
normalized_inputs, self._image_resizer_fn)
/usr/local/lib/python3.7/dist-packages/object_detection/utils/shape_utils.py:492 resize_images_and_return_shapes *
outputs = static_or_dynamic_map_fn(
/usr/local/lib/python3.7/dist-packages/object_detection/utils/shape_utils.py:246 static_or_dynamic_map_fn *
outputs = [fn(arg) for arg in tf.unstack(elems)]
/usr/local/lib/python3.7/dist-packages/object_detection/core/preprocessor.py:3241 resize_image *
new_image = tf.image.resize_images(
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper **
return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/image_ops_impl.py:1468 resize_images
skip_resize_if_same=True)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/image_ops_impl.py:1320 _resize_images_common
raise ValueError('\'images\' must have either 3 or 4 dimensions.')
ValueError: 'images' must have either 3 or 4 dimensions.
How can i solve?
All Code:
while True:
ret, frame = cap.read()
image_np = np.array(frame)
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
detections = detect_fn(input_tensor)
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
label_id_offset = 1
image_np_with_detections = image_np.copy()
viz_utils.visualize_boxes_and_labels_on_image_array(
image_np_with_detections,
detections['detection_boxes'],
detections['detection_classes']+label_id_offset,
detections['detection_scores'],
category_index,
use_normalized_coordinates=True,
max_boxes_to_draw=5,
min_score_thresh=.5,
agnostic_mode=False)
cv2.imshow('object detection', cv2.resize(image_np_with_detections, (800, 600)))
if cv2.waitKey(1) & 0xFF == ord('q'):
cap.release()
break
|
[
"Verify that you are getting an image frame from the following line:\nret, frame = cap.read()\n\nWhen I got the same error (albeit slightly different code), I was pointing to a non-existent directory rather than an image.\n",
"cap = cv2.VideoCapture(0)\n\nTry to listen with different values ranging between 0,1,2.... Worked for mine.\n",
"maybe u should try this...u just got error from ur webcam, as specifically u got lag between ur webcam and ur system, and the solution is u need to change ur code cv2.waitKey(1) & 0xFF == ord('q'): to key == ord('q'): and before if u should add key = cv2.waitKey(1) & 0xFF and at the end of ur line add this cap.release() and this cv2.destroyAllWindows()\n",
"\nNote: This problem may occur If you are using RTSP.\n\nI was almost working on a license plate recognition program.\nI had almost the same problem as you\nWhen the program was running, it crashed after the first few seconds\nOf course, I searched the web a lot, but I did not get anywhere. I made any changes to the camera settings that you can think of. I changed the whole code, I tried a lot and finally realized the problem.\nThe problem with the RTSP protocol is that you should know that RTSP runs on the UDP platform and UDP has no warranty or, in other words, no responsibility for packets. They do not have to reach their destination completely. Unlike TCP, what happens is that you may not receive any frame while running your program.\nWhat exactly does the error tell us?\nIt tells us that I was expecting to receive image with 3 or 4 dimension but did not receive it, Or rather, It did not receive anything.\nSo you should be using Try and Except In Python For handling This Problem for if not frame captured App Does Not crash and It Does reconnect the RTSP.\nHere is what you need:\ncap = cv2.VideoCapture(\"rtsp://admin:admin@192.168.1.2:554/1/1\")\nwidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nheight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\nfps = int(cap.get(cv2.CAP_PROP_FPS)) # Get video framerate\n\nwhile True:\n try:\n ret, frame = cap.read()\n if frame is None:\n print(\"disconnected!\")\n\n image_np = np.array(frame)\n\n input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)\n detections = detect_fn(input_tensor)\n\n num_detections = int(detections.pop('num_detections'))\n detections = {key: value[0, :num_detections].numpy()\n for key, value in detections.items()}\n detections['num_detections'] = num_detections\n\n # detection_classes should be ints.\n detections['detection_classes'] = detections['detection_classes'].astype(np.int64)\n\n label_id_offset = 1\n image_np_with_detections = image_np.copy()\n\n viz_utils.visualize_boxes_and_labels_on_image_array(\n image_np_with_detections,\n detections['detection_boxes'],\n detections['detection_classes']+label_id_offset,\n detections['detection_scores'],\n category_index,\n use_normalized_coordinates=True,\n max_boxes_to_draw=5,\n min_score_thresh=.8,\n agnostic_mode=False)\n\n #Extract Plate Shape On Entire Image\n detection_thereshold = 0.7\n image = image_np_with_detections\n scores = list(filter(lambda x: x> detection_thereshold, detections['detection_scores']))\n boxes = detections['detection_boxes'][:len(scores)]\n classes = detections['detection_classes'][:len(scores)]\n\n width = image.shape[1]\n height = image.shape[0]\n\n cv2.imshow('object detection', cv2.resize(image_np_with_detections, (800, 600)))\n \n if cv2.waitKey(10) & 0xFF == ord('q'):\n cap.release()\n cv2.destroyAllWindows()\n break\n except:\n cap.release()\n cap = cv2.VideoCapture(\"rtsp://admin:admin@192.168.1.2:554/1/1\")\n print(\"Reconnected!\")\n continue\n\nIn the except section, as you can see, we re-create the RTSP connection.\nYou can use this app with no problem now.\nI hope this helped you.\n",
"I solved this issue by uninstalling OpenCV-python and reinstalling it.\n\n$pip uninstall opencv-python\n$pip install opencv-python\n\nrestart the kernel & ta-da....\n",
"First Check the if the image is being captured or not in this point image_np = np.array(frame). because it shows there is no dimension so there is no image.\n",
"I had a slightly different root cause but with the same error,\nimage_path_jpg = \"path_to.jpg\"\nimg = tf.io.read_file(image_path_jpg)\nimg_resized = tf.image.resize(img, [100, 100])\n\nAlso produced\nValueError: 'images' must have either 3 or 4 dimensions.\n\nFor me solution turned out I was missing the decoding step,\nimage_path_jpg = \"path_to.jpg\"\nimg = tf.io.read_file(image_path_jpg)\nimg.get_shape().as_list() # []\nimg = tf.image.decode_jpeg(img)\nimg.get_shape().as_list() # [300, 400, 3]\nimg_resized = tf.image.resize(img, [100, 100])\nimg_resized.get_shape().as_list() # [100, 100, 3]\n\nNo more errors.\n"
] |
[
2,
1,
0,
0,
0,
0,
0
] |
[
"So let me explain this. This is not any error, its just lag in between your laptop's webcam and programming accessing it. Just restart your laptop. It will work fine. I faced the same problem...and just restarting solved it.\n"
] |
[
-2
] |
[
"object_detection",
"python",
"tensorflow"
] |
stackoverflow_0066356797_object_detection_python_tensorflow.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.