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:
Combine several columns into one column when there is only one value per row
I have this df with only one value per column between y1 and y4
x y1 y2 y3 y4
0 -17.7 -0.785430 NaN NaN NaN
1 -15.0 NaN NaN NaN -3820.085000
2 -12.5 NaN NaN 2.138833 NaN
I want to combine all y columns in one column y.
Edit: Also, I forgot I need another column to tell me which of the 4 y columns the value belongs to.
The output I need is this:
x y no
0 -17.7 -0.785430 y1
1 -15.0 -3820.085000 y4
2 -12.5 2.138833 y3
A:
Let us try groupby with first
out = df.groupby(df.columns.str[0],axis=1).first()
Out[60]:
x y
0 -17.7 -0.785430
1 -15.0 -3820.085000
2 -12.5 2.138833
A:
Another possible solution:
df.assign(y = df.iloc[:,1:].sum(axis=1)).dropna(axis=1)
Output:
x y
0 -17.7 -0.785430
1 -15.0 -3820.085000
2 -12.5 2.138833
A:
You can achieve this with groupby, similar to @BENY's:
grouped = df.filter(like='y')
cols = grouped.columns.str[0]
grouper = grouped.groupby(cols, axis = 1)
out = [df.x,
grouper.first(),
grouper.idxmax(axis=1, numeric_only=True).rename(columns={'y':'no'})]
pd.concat(out, axis = 1)
x y no
0 -17.7 -0.785430 y1
1 -15.0 -3820.085000 y4
2 -12.5 2.138833 y3
Another option is to flip it into long form:
df.columns = [f"y_{y}" if y.startswith('y') else y for y in temp]
(pd
.wide_to_long(
temp,
stubnames = 'y',
i = 'x',
j='no',
sep='_',
suffix ='.+')
.dropna()
.reset_index()
)
x no y
0 -17.7 y1 -0.785430
1 -12.5 y3 2.138833
2 -15.0 y4 -3820.085000
Another option is with pivot_longer from pyjanitor, where for this particular use case, you want to grab both the column labels and the values:
# pip install pyjanitor
import pandas as pd
import janitor
# use the original dataframe,
# with no modifications on the columns
(df
.pivot_longer(
index = 'x',
names_to = 'no',
values_to = 'y',
names_pattern='(.+)',
dropna=True)
)
x no y
0 -17.7 y1 -0.785430
1 -12.5 y3 2.138833
2 -15.0 y4 -3820.085000
The groupby should be faster than the long form approach, since flipping to long form isn't necessary - the lesser the number of rows to deal with, the more performant it should be.
|
Combine several columns into one column when there is only one value per row
|
I have this df with only one value per column between y1 and y4
x y1 y2 y3 y4
0 -17.7 -0.785430 NaN NaN NaN
1 -15.0 NaN NaN NaN -3820.085000
2 -12.5 NaN NaN 2.138833 NaN
I want to combine all y columns in one column y.
Edit: Also, I forgot I need another column to tell me which of the 4 y columns the value belongs to.
The output I need is this:
x y no
0 -17.7 -0.785430 y1
1 -15.0 -3820.085000 y4
2 -12.5 2.138833 y3
|
[
"Let us try groupby with first\nout = df.groupby(df.columns.str[0],axis=1).first()\nOut[60]: \n x y\n0 -17.7 -0.785430\n1 -15.0 -3820.085000\n2 -12.5 2.138833\n\n",
"Another possible solution:\ndf.assign(y = df.iloc[:,1:].sum(axis=1)).dropna(axis=1)\n\nOutput:\n x y\n0 -17.7 -0.785430\n1 -15.0 -3820.085000\n2 -12.5 2.138833\n\n",
"You can achieve this with groupby, similar to @BENY's:\ngrouped = df.filter(like='y')\ncols = grouped.columns.str[0]\ngrouper = grouped.groupby(cols, axis = 1)\nout = [df.x, \n grouper.first(), \n grouper.idxmax(axis=1, numeric_only=True).rename(columns={'y':'no'})]\npd.concat(out, axis = 1)\n\n x y no\n0 -17.7 -0.785430 y1\n1 -15.0 -3820.085000 y4\n2 -12.5 2.138833 y3\n\nAnother option is to flip it into long form:\ndf.columns = [f\"y_{y}\" if y.startswith('y') else y for y in temp]\n(pd\n.wide_to_long(\n temp, \n stubnames = 'y', \n i = 'x', \n j='no', \n sep='_', \n suffix ='.+')\n.dropna()\n.reset_index()\n)\n\n x no y\n0 -17.7 y1 -0.785430\n1 -12.5 y3 2.138833\n2 -15.0 y4 -3820.085000\n\nAnother option is with pivot_longer from pyjanitor, where for this particular use case, you want to grab both the column labels and the values:\n# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\n# use the original dataframe, \n# with no modifications on the columns\n(df\n.pivot_longer(\n index = 'x', \n names_to = 'no', \n values_to = 'y', \n names_pattern='(.+)', \n dropna=True)\n) \n x no y\n0 -17.7 y1 -0.785430\n1 -12.5 y3 2.138833\n2 -15.0 y4 -3820.085000\n\nThe groupby should be faster than the long form approach, since flipping to long form isn't necessary - the lesser the number of rows to deal with, the more performant it should be.\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074495928_dataframe_pandas_python.txt
|
Q:
python interpreter from spyder works but python from console has no modules found
I need to run Python 3.8 for my ROS2 installation on Ubuntu 22.04.
When I open Spyder it defaults to Python 3.10.6 and all the scripts work, however when I run Python from the console it uses Python 3.8.15 and no modules are found.
How do I ensure that all pip installations can be seen by Python 3.8?
update-alternatives --config python is set to version 3.8
* 0 /usr/bin/python3.8 3 auto mode
$PATH variable outputs: /home/ros2/ros2_dashing/install/cyclonedds/bin:/home/ros2/ros2_dashing/install/ament_flake8/bin:/home/ros2/ros2_dashing/install/ament_cppcheck/bin:/opt/ros/humble/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/ros2/.local/bin
A:
I've found a solution that works for me.
From the console, install each module specifically for the required python version:
python3.8 -m pip install <module>
|
python interpreter from spyder works but python from console has no modules found
|
I need to run Python 3.8 for my ROS2 installation on Ubuntu 22.04.
When I open Spyder it defaults to Python 3.10.6 and all the scripts work, however when I run Python from the console it uses Python 3.8.15 and no modules are found.
How do I ensure that all pip installations can be seen by Python 3.8?
update-alternatives --config python is set to version 3.8
* 0 /usr/bin/python3.8 3 auto mode
$PATH variable outputs: /home/ros2/ros2_dashing/install/cyclonedds/bin:/home/ros2/ros2_dashing/install/ament_flake8/bin:/home/ros2/ros2_dashing/install/ament_cppcheck/bin:/opt/ros/humble/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/ros2/.local/bin
|
[
"I've found a solution that works for me.\nFrom the console, install each module specifically for the required python version:\npython3.8 -m pip install <module>\n"
] |
[
0
] |
[] |
[] |
[
"pip",
"python",
"python_3.8"
] |
stackoverflow_0074497339_pip_python_python_3.8.txt
|
Q:
Syntax confusion with class
This is the given code:
class Person:
def __init__(self, name):
self.name = name
def greeting(self):
return "hi, my name is " + self.name
some_person = Person("yeabsira")
print(some_person.greeting())
However, I was expecting the syntax in which the constructor method uses like:
class Name:
def __init__(self,atribute1,atribute2):
self.atribute1=atribute1
self.atribute2=atribute2
new_instance=Name("example")
print(new_instance.atribute1)
expect answer="example"
So my question is how "some_person.greeting()" symantic works?
A:
some_person.name returns the value of the person's name, while some_person.greeting() returns a greeting with the name, it is just a function defined within the class Person and works normally like any other function. You could use some_person.name if you only need the name.
However, by using some_person.greeting(), you implemented data hiding, which hides internal object details, and the user (in the future) only needs to access greeting() and not the value of name itself.
|
Syntax confusion with class
|
This is the given code:
class Person:
def __init__(self, name):
self.name = name
def greeting(self):
return "hi, my name is " + self.name
some_person = Person("yeabsira")
print(some_person.greeting())
However, I was expecting the syntax in which the constructor method uses like:
class Name:
def __init__(self,atribute1,atribute2):
self.atribute1=atribute1
self.atribute2=atribute2
new_instance=Name("example")
print(new_instance.atribute1)
expect answer="example"
So my question is how "some_person.greeting()" symantic works?
|
[
"some_person.name returns the value of the person's name, while some_person.greeting() returns a greeting with the name, it is just a function defined within the class Person and works normally like any other function. You could use some_person.name if you only need the name.\nHowever, by using some_person.greeting(), you implemented data hiding, which hides internal object details, and the user (in the future) only needs to access greeting() and not the value of name itself.\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074497540_python.txt
|
Q:
Scraping what's inside the links
I don't really have code for this problem. But I will try my best to actually explain everything.
alright, say you are scraping a website, and in the website there are 3 different links and you want to scrape what is inside each and everyone one of them without having to manually do it. Is this possible for just BeautifulSoup and the Requests library? Or would you have to use another library, for e.g scrapy.
If you want you can try it on this website: https://www.bleepingcomputer.com/
What I am trying to achieve is scrape the website, and what is inside the links at the same time.
If it's not possible to do it with only requests & Beautifulsoup feel free to use scrapy as well.
A:
you can scrape the links via tag. The html template will have the hyperlink listed and the actual website it links you to should be listed in href. Ex:
<li href=“https://google.com > Site 1 </li>
The href would be the destination link and the site 1 is just the text shown in page
A:
scrape the website, and what is inside the links at the same time
Assuming that you mean you want to scrape all the pages that the links on the site lead to, I have this recursive crawler which should be able to do it. Just calling linkTreeMapper('https://www.bleepingcomputer.com/', None, 1) gave an output like this; the fuction was actually meant to go further, like linkTreeMapper('https://www.bleepingcomputer.com/', pageLimit=2) would return
{
"url": "https://www.bleepingcomputer.com/",
"atDepth": 0,
"pageTitle": "BleepingComputer | Cybersecurity, Technology News and Support",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...n in with Twitter Not a member yet? Register Now",
"pageUrls": [
{
"url": "https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/",
"atDepth": 1,
"pageTitle": "US govt: Iranian hackers breached federal agency using Log4Shell exploit",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT",
"pageUrls": [
{
"url": "https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/",
"atDepth": 2,
"pageTitle": "US govt: Iranian hackers breached federal agency using Log4Shell exploit",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT",
"pageUrls": [
{
"url": "https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/",
"atDepth": 3,
"pageTitle": "US govt: Iranian hackers breached federal agency using Log4Shell exploit",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT"
},
{
"url": "https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/",
"atDepth": 3,
"pageTitle": "Google to roll out Privacy Sandbox on Android 13 starting early 2023",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT"
}
]
},
{
"url": "https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/",
"atDepth": 2,
"pageTitle": "Google to roll out Privacy Sandbox on Android 13 starting early 2023",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT",
"pageUrls": [
{
"url": "https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/",
"atDepth": 3,
"errorMessage": "Message: timeout: Timed out receiving message from renderer: -0.009\n (Session info: chrome=107.0.5304.88)\n"
},
{
"url": "https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/",
"atDepth": 3,
"pageTitle": "Google to roll out Privacy Sandbox on Android 13 starting early 2023",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT"
}
]
}
]
},
{
"url": "https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/",
"atDepth": 1,
"pageTitle": "Google to roll out Privacy Sandbox on Android 13 starting early 2023",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT",
"pageUrls": [
{
"url": "https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/",
"atDepth": 2,
"pageTitle": "US govt: Iranian hackers breached federal agency using Log4Shell exploit",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT",
"pageUrls": [
{
"url": "https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/",
"atDepth": 3,
"pageTitle": "US govt: Iranian hackers breached federal agency using Log4Shell exploit",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT"
},
{
"url": "https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/",
"atDepth": 3,
"pageTitle": "Google to roll out Privacy Sandbox on Android 13 starting early 2023",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...SUBMIT advertisement advertisement advertisement"
}
]
},
{
"url": "https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/",
"atDepth": 2,
"pageTitle": "Google to roll out Privacy Sandbox on Android 13 starting early 2023",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT",
"pageUrls": [
{
"url": "https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/",
"atDepth": 3,
"pageTitle": "US govt: Iranian hackers breached federal agency using Log4Shell exploit",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT"
},
{
"url": "https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/",
"atDepth": 3,
"pageTitle": "Google to roll out Privacy Sandbox on Android 13 starting early 2023",
"pageBodyText": "News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT"
}
]
}
]
}
]
}
(I set pageLimit=2 so that the output would be small enough to view here)
However, using recursion can be dangerous in cases like these, and as you can see, it's harder to eliminate repeated scrawling of the same page; so, it might be better to use this queue-based scrawler
## FIRST COPY [OR DOWNLOAD&IMPORT] REQUIREMENTS FROM https://pastebin.com/TBtYja5D ##
setGlobals(varDict={
'starterUrl': 'https://www.bleepingcomputer.com/',
'pageLimit': None, 'maxScrapes': 55, 'scrapeCt': 0, 'curUrlId': 0
}, clearLog=True)
nextUrl = get_next_fromScrawlQ()
while nextUrl: nextUrl = logScrape(scrapeUrl(nextUrl))
saveScrawlSess('qScrawl_bleepingComp.csv', 'vScrawl_bleepC.json')
and "qScrawl_bleepingComp.csv" would look like
url
refUrlId
status
urlId
pageTitle
pageText
pageUrlCt
newToQueue
https://www.bleepingcomputer.com/
[starter]
scraped
1
BleepingComputer | Cybersecurity, Technology News and Support
News Featured Latest Exploit rele...er Not a member yet? Register Now
237.0
129.0
https://www.facebook.com/BleepingComputer
1
?scraped
2
BleepingComputer | New York NY
NaN
0.0
0.0
https://twitter.com/BleepinComputer
1
scraped
3
NaN
JavaScript is not available. We’v...ret — let’s give it another shot.
6.0
6.0
https://www.youtube.com/user/BleepingComputer
1
?scraped
4
YouTube
BleepingComputer - YouTube
0.0
0.0
https://www.bleepingcomputer.com/news/security/exploit-released-for-actively-abused-proxynotshell-exchange-bug/
1
scraped
5
Exploit released for actively abused ProxyNotShell Exchange bug
News Featured Latest Exploit rele... prohibited. Submitting... SUBMIT
148.0
26.0
(Only the first five rows [of 1.6k+] are above, and the last 2 columns have not been included - see uploaded csv for full output.)
The "pageUrlIds" columns has a list of numbers, each of which should correspond to a row according to the "urlId" column; so, if you wanted to, you could use that to form a nested dictionary like the output of the recursive crawler.
Is this possible for just BeautifulSoup and the Requests library?
For some sites, it might be - both of my crawlers use a linkToSoup function [to fetch and parse the html of each page], and I have several versions of it; the simple requests version didn't work for bleepingcomputer, so I used cloudscraper. However, I'm not skilled with setting headers for requests [beyond the the very basics], so someone else may have be able to figure out the perfect set of parameters...
|
Scraping what's inside the links
|
I don't really have code for this problem. But I will try my best to actually explain everything.
alright, say you are scraping a website, and in the website there are 3 different links and you want to scrape what is inside each and everyone one of them without having to manually do it. Is this possible for just BeautifulSoup and the Requests library? Or would you have to use another library, for e.g scrapy.
If you want you can try it on this website: https://www.bleepingcomputer.com/
What I am trying to achieve is scrape the website, and what is inside the links at the same time.
If it's not possible to do it with only requests & Beautifulsoup feel free to use scrapy as well.
|
[
"you can scrape the links via tag. The html template will have the hyperlink listed and the actual website it links you to should be listed in href. Ex:\n<li href=“https://google.com > Site 1 </li> \nThe href would be the destination link and the site 1 is just the text shown in page\n",
"\nscrape the website, and what is inside the links at the same time\n\nAssuming that you mean you want to scrape all the pages that the links on the site lead to, I have this recursive crawler which should be able to do it. Just calling linkTreeMapper('https://www.bleepingcomputer.com/', None, 1) gave an output like this; the fuction was actually meant to go further, like linkTreeMapper('https://www.bleepingcomputer.com/', pageLimit=2) would return\n{\n \"url\": \"https://www.bleepingcomputer.com/\",\n \"atDepth\": 0,\n \"pageTitle\": \"BleepingComputer | Cybersecurity, Technology News and Support\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...n in with Twitter Not a member yet? Register Now\",\n \"pageUrls\": [\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/\",\n \"atDepth\": 1,\n \"pageTitle\": \"US govt: Iranian hackers breached federal agency using Log4Shell exploit\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\",\n \"pageUrls\": [\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/\",\n \"atDepth\": 2,\n \"pageTitle\": \"US govt: Iranian hackers breached federal agency using Log4Shell exploit\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\",\n \"pageUrls\": [\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/\",\n \"atDepth\": 3,\n \"pageTitle\": \"US govt: Iranian hackers breached federal agency using Log4Shell exploit\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\"\n },\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/\",\n \"atDepth\": 3,\n \"pageTitle\": \"Google to roll out Privacy Sandbox on Android 13 starting early 2023\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\"\n }\n ]\n },\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/\",\n \"atDepth\": 2,\n \"pageTitle\": \"Google to roll out Privacy Sandbox on Android 13 starting early 2023\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\",\n \"pageUrls\": [\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/\",\n \"atDepth\": 3,\n \"errorMessage\": \"Message: timeout: Timed out receiving message from renderer: -0.009\\n (Session info: chrome=107.0.5304.88)\\n\"\n },\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/\",\n \"atDepth\": 3,\n \"pageTitle\": \"Google to roll out Privacy Sandbox on Android 13 starting early 2023\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\"\n }\n ]\n }\n ]\n },\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/\",\n \"atDepth\": 1,\n \"pageTitle\": \"Google to roll out Privacy Sandbox on Android 13 starting early 2023\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\",\n \"pageUrls\": [\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/\",\n \"atDepth\": 2,\n \"pageTitle\": \"US govt: Iranian hackers breached federal agency using Log4Shell exploit\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\",\n \"pageUrls\": [\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/\",\n \"atDepth\": 3,\n \"pageTitle\": \"US govt: Iranian hackers breached federal agency using Log4Shell exploit\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\"\n },\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/\",\n \"atDepth\": 3,\n \"pageTitle\": \"Google to roll out Privacy Sandbox on Android 13 starting early 2023\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...SUBMIT advertisement advertisement advertisement\"\n }\n ]\n },\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/\",\n \"atDepth\": 2,\n \"pageTitle\": \"Google to roll out Privacy Sandbox on Android 13 starting early 2023\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\",\n \"pageUrls\": [\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/us-govt-iranian-hackers-breached-federal-agency-using-log4shell-exploit/\",\n \"atDepth\": 3,\n \"pageTitle\": \"US govt: Iranian hackers breached federal agency using Log4Shell exploit\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\"\n },\n {\n \"url\": \"https://www.bleepingcomputer.com/news/security/google-to-roll-out-privacy-sandbox-on-android-13-starting-early-2023/\",\n \"atDepth\": 3,\n \"pageTitle\": \"Google to roll out Privacy Sandbox on Android 13 starting early 2023\",\n \"pageBodyText\": \"News Featured Latest US govt: Iranian hackers br...what content is prohibited. Submitting... SUBMIT\"\n }\n ]\n }\n ]\n }\n ]\n}\n\n(I set pageLimit=2 so that the output would be small enough to view here)\n\nHowever, using recursion can be dangerous in cases like these, and as you can see, it's harder to eliminate repeated scrawling of the same page; so, it might be better to use this queue-based scrawler\n## FIRST COPY [OR DOWNLOAD&IMPORT] REQUIREMENTS FROM https://pastebin.com/TBtYja5D ##\nsetGlobals(varDict={\n 'starterUrl': 'https://www.bleepingcomputer.com/', \n 'pageLimit': None, 'maxScrapes': 55, 'scrapeCt': 0, 'curUrlId': 0\n}, clearLog=True)\nnextUrl = get_next_fromScrawlQ()\nwhile nextUrl: nextUrl = logScrape(scrapeUrl(nextUrl))\nsaveScrawlSess('qScrawl_bleepingComp.csv', 'vScrawl_bleepC.json')\n\nand \"qScrawl_bleepingComp.csv\" would look like\n\n\n\n\nurl\nrefUrlId\nstatus\nurlId\npageTitle\npageText\npageUrlCt\nnewToQueue\n\n\n\n\nhttps://www.bleepingcomputer.com/\n[starter]\nscraped\n1\nBleepingComputer | Cybersecurity, Technology News and Support\nNews Featured Latest Exploit rele...er Not a member yet? Register Now\n237.0\n129.0\n\n\nhttps://www.facebook.com/BleepingComputer\n1\n?scraped\n2\nBleepingComputer | New York NY\nNaN\n0.0\n0.0\n\n\nhttps://twitter.com/BleepinComputer\n1\nscraped\n3\nNaN\nJavaScript is not available. We’v...ret — let’s give it another shot.\n6.0\n6.0\n\n\nhttps://www.youtube.com/user/BleepingComputer\n1\n?scraped\n4\nYouTube\nBleepingComputer - YouTube\n0.0\n0.0\n\n\nhttps://www.bleepingcomputer.com/news/security/exploit-released-for-actively-abused-proxynotshell-exchange-bug/\n1\nscraped\n5\nExploit released for actively abused ProxyNotShell Exchange bug\nNews Featured Latest Exploit rele... prohibited. Submitting... SUBMIT\n148.0\n26.0\n\n\n\n\n(Only the first five rows [of 1.6k+] are above, and the last 2 columns have not been included - see uploaded csv for full output.)\nThe \"pageUrlIds\" columns has a list of numbers, each of which should correspond to a row according to the \"urlId\" column; so, if you wanted to, you could use that to form a nested dictionary like the output of the recursive crawler.\n\n\nIs this possible for just BeautifulSoup and the Requests library?\n\nFor some sites, it might be - both of my crawlers use a linkToSoup function [to fetch and parse the html of each page], and I have several versions of it; the simple requests version didn't work for bleepingcomputer, so I used cloudscraper. However, I'm not skilled with setting headers for requests [beyond the the very basics], so someone else may have be able to figure out the perfect set of parameters...\n"
] |
[
0,
0
] |
[
"You can do it with only requests and BeautifulSoup. Just add the links to a list or a dict and iterate the list.\n"
] |
[
-1
] |
[
"python",
"web_scraping"
] |
stackoverflow_0074420235_python_web_scraping.txt
|
Q:
SQLAlchemy: AttributeError: 'Connection' object has no attribute 'commit'
When using SQLAlchemy (version 1.4.44) to create, drop or otherwise modify tables, the updates don't appear to be committing. Attempting to solve this, I'm following the docs and using the commit() function. Here's a simple example
from sqlalchemy import create_engine, text
engine = create_engine("postgresql://user:password@connection_string:5432/database_name")
with engine.connect() as connection:
sql = "create table test as (select count(1) as result from userquery);"
result = connection.execute(text(sql))
connection.commit()
This produces the error:
AttributeError: 'Connection' object has no attribute 'commit'
What am I missing?
A:
The comment on the question is correct you are looking at the 2.0 docs but all you need to do is set future=True when calling create_engine() to use the "commit as you go" functionality provided in 2.0.
SEE migration-core-connection-transaction
When using 2.0 style with the create_engine.future flag, “commit as
you go” style may also be used, as the Connection features autobegin
behavior, which takes place when a statement is first invoked in the
absence of an explicit call to Connection.begin():
|
SQLAlchemy: AttributeError: 'Connection' object has no attribute 'commit'
|
When using SQLAlchemy (version 1.4.44) to create, drop or otherwise modify tables, the updates don't appear to be committing. Attempting to solve this, I'm following the docs and using the commit() function. Here's a simple example
from sqlalchemy import create_engine, text
engine = create_engine("postgresql://user:password@connection_string:5432/database_name")
with engine.connect() as connection:
sql = "create table test as (select count(1) as result from userquery);"
result = connection.execute(text(sql))
connection.commit()
This produces the error:
AttributeError: 'Connection' object has no attribute 'commit'
What am I missing?
|
[
"The comment on the question is correct you are looking at the 2.0 docs but all you need to do is set future=True when calling create_engine() to use the \"commit as you go\" functionality provided in 2.0.\nSEE migration-core-connection-transaction\n\nWhen using 2.0 style with the create_engine.future flag, “commit as\nyou go” style may also be used, as the Connection features autobegin\nbehavior, which takes place when a statement is first invoked in the\nabsence of an explicit call to Connection.begin():\n\n"
] |
[
2
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0074495598_python_sqlalchemy.txt
|
Q:
Keep the row for which the values of two columns match by group otherwise keep the first row by group
I wanted to left join df2 on df1 and then keep the row that matches by group and if there is no matching group then I would like to keep the first row of the group in order to achieve df3 (the desired result). I was hoping you guys could help me with finding the optimal solution.
Here is my code to create the two dataframes and the required result.
import pandas as pd
import numpy as np
market = ['SP', 'SP', 'SP']
underlying = ['TSLA', 'GOOG', 'MSFT']
# DF1
df = pd.DataFrame(list(zip(market, underlying)),
columns=['market', 'underlying'])
market2 = ['SP', 'SP', 'SP', 'SP', 'SP']
underlying2 = [None, 'TSLA', 'GBX', 'GBM', 'GBS']
client2 = [17, 12, 100, 21, 10]
# DF2
df2 = pd.DataFrame(list(zip(market2, underlying2, client2)),
columns=['market', 'underlying', 'client'])
market3 = ['SP', 'SP', 'SP']
underlying3 = ['TSLA', 'GOOG', 'MSFT']
client3 = [12, 17, 17]
# Desired
df3 = pd.DataFrame(list(zip(market3, underlying3, client3)),
columns =['market', 'underlying', 'client'])
# This works but feels sub optimal
df3 = pd.merge(df,
df2,
how='left',
on=['market', 'underlying'])
df3 = pd.merge(df3,
df2,
how='left',
on=['market'])
df3 = df3.drop_duplicates(['market', 'underlying_x'])
df3['client'] = df3['client_x'].combine_first(df3['client_y'])
df3 = df3.drop(labels=['underlying_y', 'client_x', 'client_y'], axis=1)
df3 = df3.rename(columns={'underlying_x': 'underlying'})
Hope you guys could help, thankyou so much!
A:
Store the first value (a groupby might not be necessary if every single one in market is 'SP'), merge and fill with the first value:
fill_value = df2.groupby('market').client.first()
# if you are interested in filtering for None:
fill_value = df2.set_index('market').loc[lambda df: df.underlying.isna(), 'client']
(df
.merge(
df2,
on = ['market', 'underlying'],
how = 'left')
.set_index('market')
.fillna({'client':fill_value}, downcast='infer')
)
underlying client
market
SP TSLA 12
SP GOOG 17
SP MSFT 17
|
Keep the row for which the values of two columns match by group otherwise keep the first row by group
|
I wanted to left join df2 on df1 and then keep the row that matches by group and if there is no matching group then I would like to keep the first row of the group in order to achieve df3 (the desired result). I was hoping you guys could help me with finding the optimal solution.
Here is my code to create the two dataframes and the required result.
import pandas as pd
import numpy as np
market = ['SP', 'SP', 'SP']
underlying = ['TSLA', 'GOOG', 'MSFT']
# DF1
df = pd.DataFrame(list(zip(market, underlying)),
columns=['market', 'underlying'])
market2 = ['SP', 'SP', 'SP', 'SP', 'SP']
underlying2 = [None, 'TSLA', 'GBX', 'GBM', 'GBS']
client2 = [17, 12, 100, 21, 10]
# DF2
df2 = pd.DataFrame(list(zip(market2, underlying2, client2)),
columns=['market', 'underlying', 'client'])
market3 = ['SP', 'SP', 'SP']
underlying3 = ['TSLA', 'GOOG', 'MSFT']
client3 = [12, 17, 17]
# Desired
df3 = pd.DataFrame(list(zip(market3, underlying3, client3)),
columns =['market', 'underlying', 'client'])
# This works but feels sub optimal
df3 = pd.merge(df,
df2,
how='left',
on=['market', 'underlying'])
df3 = pd.merge(df3,
df2,
how='left',
on=['market'])
df3 = df3.drop_duplicates(['market', 'underlying_x'])
df3['client'] = df3['client_x'].combine_first(df3['client_y'])
df3 = df3.drop(labels=['underlying_y', 'client_x', 'client_y'], axis=1)
df3 = df3.rename(columns={'underlying_x': 'underlying'})
Hope you guys could help, thankyou so much!
|
[
"Store the first value (a groupby might not be necessary if every single one in market is 'SP'), merge and fill with the first value:\nfill_value = df2.groupby('market').client.first()\n\n# if you are interested in filtering for None:\nfill_value = df2.set_index('market').loc[lambda df: df.underlying.isna(), 'client']\n\n\n(df\n.merge(\n df2, \n on = ['market', 'underlying'], \n how = 'left')\n.set_index('market')\n.fillna({'client':fill_value}, downcast='infer')\n)\n\n underlying client\nmarket \nSP TSLA 12\nSP GOOG 17\nSP MSFT 17\n\n"
] |
[
0
] |
[] |
[] |
[
"numpy",
"pandas",
"python"
] |
stackoverflow_0074495249_numpy_pandas_python.txt
|
Q:
f(x)= number of ones in x . find the highest and average fitness for genetic algorithm , Alternate option to Map and reduce in python
i am trying to write a code which takes input as below and then find the highest and average where f(x)= number of ones in x .
['00111110011001010011', '01111101001101110010', '01100110111110000000', '01101101100111001001']
def fitness(genome):
return reduce((lambda x, y: int(x) + int(y)), list(genome))
# reference : https://www.geeksforgeeks.org/reduce-in-python/
def evaluateFitness(population):
sums = list(map(lambda x: fitness(x), population))
return [max(sums), sum(sums) / len(population)]
the above function works well. i want to know if there is any library in numpy or scipy which can do the same or pygad.basically trying to find alternate option to achieve the same result.
A:
A way using numpy.
import numpy as np
lst = ['00111110011001010011', '01111101001101110010', '01100110111110000000', '01101101100111001001']
population = np.fromiter(''.join(lst), dtype=np.int).reshape(len(lst), -1)
max_sum_over_row = population.sum(1).max()
avg_sum_over_row = population.mean(0).sum()
|
f(x)= number of ones in x . find the highest and average fitness for genetic algorithm , Alternate option to Map and reduce in python
|
i am trying to write a code which takes input as below and then find the highest and average where f(x)= number of ones in x .
['00111110011001010011', '01111101001101110010', '01100110111110000000', '01101101100111001001']
def fitness(genome):
return reduce((lambda x, y: int(x) + int(y)), list(genome))
# reference : https://www.geeksforgeeks.org/reduce-in-python/
def evaluateFitness(population):
sums = list(map(lambda x: fitness(x), population))
return [max(sums), sum(sums) / len(population)]
the above function works well. i want to know if there is any library in numpy or scipy which can do the same or pygad.basically trying to find alternate option to achieve the same result.
|
[
"A way using numpy.\nimport numpy as np\nlst = ['00111110011001010011', '01111101001101110010', '01100110111110000000', '01101101100111001001']\npopulation = np.fromiter(''.join(lst), dtype=np.int).reshape(len(lst), -1)\nmax_sum_over_row = population.sum(1).max()\navg_sum_over_row = population.mean(0).sum()\n\n"
] |
[
0
] |
[] |
[] |
[
"fitness",
"genetic_algorithm",
"python"
] |
stackoverflow_0074497629_fitness_genetic_algorithm_python.txt
|
Q:
Cumulative sum based on date not working as expected
My target on daily basis is 250. For any given date, if the cum-daily_result has reached 250 then subsequent rows should have only 250 as expected results
Input table:
col1 col2 col3
0 a 250 250
1 a 250 500
2 a -1290 -790
3 b -1392 -1392
4 b 250 -1142
5 b 250 -892
6 b 2238 1346
7 b 250 1596
8 c 2477 2477
9 c -3813 -1336
10 c 250 -1086
If I use the following code, the output is correct if the first row col3 starts with a positive value
Code:
idx = df[df['col3'] >= 250].groupby('col1').head(1).index
df.loc[idx, 'col4'] = 1
df['col4'] = df.groupby('col1')['col4'].bfill() * df['col3']
df['col4'] = df.groupby('col1')['col4'].ffill().astype('int')
Output:
col1 col2 col3 col4
0 a 250 250 250
1 a 250 500 250
2 a -1290 -790 250
3 b -1392 -1392 -1392
4 b 250 -1142 -1142
5 b 250 -892 -892
6 b 2238 1346 1346
7 b 250 1596 1346
8 c 2477 2477 2477
9 c -3813 -1336 2477
10 c 250 -1086 2477
But this is not working if the first row col3 is negative or all rows for specific col1 eg 'a' is negative.
Below is the example of input where the above code doesn't give desired result
col1 col2 col3
0 a -500 -500
1 a -250 -750
2 a -1000 -1750
3 b -1392 -1392
4 b 250 -1142
5 b 250 -892
6 b 2238 1346
7 b 250 1596
8 c 2477 2477
9 c -3813 -1336
10 c 250 -1086
Expected output is as under
col1 col2 col3 col4
0 a -500 -500 -500
1 a -250 -750 -750
2 a -1000 -1750 -1750
3 b -1392 -1392 -1392
4 b 250 -1142 -1142
5 b 250 -892 -892
6 b 2238 1346 1346
7 b 250 1596 1346
8 c 2477 2477 2477
9 c -3813 -1336 2477
10 c 250 -1086 2477
A:
I have a less elegant solution, but it worked for me.
idx = df[df['col3'] >= 250].groupby('col1').head(1).index
df.loc[idx, 'col4'] = 1
df['col4']=df['col3']*df['col4']
df['col4'] = df.groupby('col1')['col4'].ffill()
df['col4']=df['col4'].fillna(df['col3']).astype('int')
|
Cumulative sum based on date not working as expected
|
My target on daily basis is 250. For any given date, if the cum-daily_result has reached 250 then subsequent rows should have only 250 as expected results
Input table:
col1 col2 col3
0 a 250 250
1 a 250 500
2 a -1290 -790
3 b -1392 -1392
4 b 250 -1142
5 b 250 -892
6 b 2238 1346
7 b 250 1596
8 c 2477 2477
9 c -3813 -1336
10 c 250 -1086
If I use the following code, the output is correct if the first row col3 starts with a positive value
Code:
idx = df[df['col3'] >= 250].groupby('col1').head(1).index
df.loc[idx, 'col4'] = 1
df['col4'] = df.groupby('col1')['col4'].bfill() * df['col3']
df['col4'] = df.groupby('col1')['col4'].ffill().astype('int')
Output:
col1 col2 col3 col4
0 a 250 250 250
1 a 250 500 250
2 a -1290 -790 250
3 b -1392 -1392 -1392
4 b 250 -1142 -1142
5 b 250 -892 -892
6 b 2238 1346 1346
7 b 250 1596 1346
8 c 2477 2477 2477
9 c -3813 -1336 2477
10 c 250 -1086 2477
But this is not working if the first row col3 is negative or all rows for specific col1 eg 'a' is negative.
Below is the example of input where the above code doesn't give desired result
col1 col2 col3
0 a -500 -500
1 a -250 -750
2 a -1000 -1750
3 b -1392 -1392
4 b 250 -1142
5 b 250 -892
6 b 2238 1346
7 b 250 1596
8 c 2477 2477
9 c -3813 -1336
10 c 250 -1086
Expected output is as under
col1 col2 col3 col4
0 a -500 -500 -500
1 a -250 -750 -750
2 a -1000 -1750 -1750
3 b -1392 -1392 -1392
4 b 250 -1142 -1142
5 b 250 -892 -892
6 b 2238 1346 1346
7 b 250 1596 1346
8 c 2477 2477 2477
9 c -3813 -1336 2477
10 c 250 -1086 2477
|
[
"I have a less elegant solution, but it worked for me.\nidx = df[df['col3'] >= 250].groupby('col1').head(1).index\ndf.loc[idx, 'col4'] = 1\ndf['col4']=df['col3']*df['col4']\ndf['col4'] = df.groupby('col1')['col4'].ffill()\ndf['col4']=df['col4'].fillna(df['col3']).astype('int')\n\n"
] |
[
0
] |
[] |
[] |
[
"numpy",
"pandas",
"python"
] |
stackoverflow_0074497085_numpy_pandas_python.txt
|
Q:
Django manage.py migrate errors
I've been working on a project for CS50-Web for a while now and I was changing some of my models trying to add a unique attribute to some things. Long story short it wasn't working how I wanted so I went back to how I had it previously and now something is wrong and I can get it to migrate the changes to the model. I don't understand what to do because it was working fine before. Please can someone help I so frustrated and annoyed that I've broken it after so many hours of work. Sorry I know this error code is long but I don't know which part is important.
Error code
Operations to perform:
Apply all migrations: admin, auth, contenttypes, network, sessions
Running migrations:
Applying network.0019_alter_follower_user...Traceback (most recent call last):
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: new__network_follower.user_id
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 21, in <module>
main()
File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line
utility.execute()
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 419, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 373, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 417, in execute
output = self.handle(*args, **options)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 90, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\migrate.py", line 253, in handle
post_migrate_state = executor.migrate(
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\executor.py", line 126, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\executor.py", line 156, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\executor.py", line 236, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\migration.py", line 125, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\operations\fields.py", line 225, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\schema.py", line 140, in alter_field
super().alter_field(model, old_field, new_field, strict=strict)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\base\schema.py", line 620, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type,
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\schema.py", line 362, in _alter_field
self._remake_table(model, alter_field=(old_field, new_field))
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\schema.py", line 285, in _remake_table
self.execute("INSERT INTO %s (%s) SELECT %s FROM %s" % (
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\base\schema.py", line 153, in execute
cursor.execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 99, in execute
return super().execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: new__network_follower.user_id
I went back to how I had the code before it failed but it doesn't work now
A:
Just try these 3 commands for migrations:
python manage.py makemigrations appname
python manage.py sqlmigrate appname 0001 #This value will generate afte makemigrations. it can be either 0001, 0002 or more.
python manage.py migrate
And see if it solves this error
|
Django manage.py migrate errors
|
I've been working on a project for CS50-Web for a while now and I was changing some of my models trying to add a unique attribute to some things. Long story short it wasn't working how I wanted so I went back to how I had it previously and now something is wrong and I can get it to migrate the changes to the model. I don't understand what to do because it was working fine before. Please can someone help I so frustrated and annoyed that I've broken it after so many hours of work. Sorry I know this error code is long but I don't know which part is important.
Error code
Operations to perform:
Apply all migrations: admin, auth, contenttypes, network, sessions
Running migrations:
Applying network.0019_alter_follower_user...Traceback (most recent call last):
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: new__network_follower.user_id
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 21, in <module>
main()
File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line
utility.execute()
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 419, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 373, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 417, in execute
output = self.handle(*args, **options)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\base.py", line 90, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\migrate.py", line 253, in handle
post_migrate_state = executor.migrate(
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\executor.py", line 126, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\executor.py", line 156, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\executor.py", line 236, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\migration.py", line 125, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\migrations\operations\fields.py", line 225, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\schema.py", line 140, in alter_field
super().alter_field(model, old_field, new_field, strict=strict)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\base\schema.py", line 620, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type,
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\schema.py", line 362, in _alter_field
self._remake_table(model, alter_field=(old_field, new_field))
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\schema.py", line 285, in _remake_table
self.execute("INSERT INTO %s (%s) SELECT %s FROM %s" % (
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\base\schema.py", line 153, in execute
cursor.execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 99, in execute
return super().execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: new__network_follower.user_id
I went back to how I had the code before it failed but it doesn't work now
|
[
"Just try these 3 commands for migrations:\npython manage.py makemigrations appname\n\npython manage.py sqlmigrate appname 0001 #This value will generate afte makemigrations. it can be either 0001, 0002 or more.\n\npython manage.py migrate\n\nAnd see if it solves this error\n"
] |
[
0
] |
[] |
[] |
[
"cs50",
"django",
"python"
] |
stackoverflow_0074497270_cs50_django_python.txt
|
Q:
bash: worker:: command not found on koyeb
I tried to deploy this botto koyeb but I got this error
bash: worker:: command not found
ERROR: failed to determine the run command to launch your application: add a run command in your Service configuration or create a procfile in your git repository.
procfile in bot repo
worker: python -m bot
I have no idea what to do . need detailed help plz !
A:
bash: worker:: command not found
The double : colon suggests that
you intended to run e.g. /usr/bin/worker
but bash attempted to execute /usr/bin/worker:
and found no file by that name.
Revise your command so it has fewer colons.
|
bash: worker:: command not found on koyeb
|
I tried to deploy this botto koyeb but I got this error
bash: worker:: command not found
ERROR: failed to determine the run command to launch your application: add a run command in your Service configuration or create a procfile in your git repository.
procfile in bot repo
worker: python -m bot
I have no idea what to do . need detailed help plz !
|
[
"\nbash: worker:: command not found\n\n\nThe double : colon suggests that\nyou intended to run e.g. /usr/bin/worker\nbut bash attempted to execute /usr/bin/worker:\nand found no file by that name.\nRevise your command so it has fewer colons.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074497684_python.txt
|
Q:
How to automatically unpack list that contains some 0 values?
When I try to unpack a list data for a MySQL database query that has some columns with value 0, I get an error.
Name (varchar)
Apples(int)
Candies(int)
Color (varchar)
John
5
0
Blue
If I unpack my query result like:
name, apples, candies, color = mylist
I'll get a NoneType error because candies values (in this example) is considered as None rather than 0.
The workaround I currently have is (which defeats the purpose and benefit of unpacking):
name = mylist[0]
if apples is None:
apples = 0
else apples = mylist[1]
if candies is None:
candies = 0
else candies = mylist[2]
color = mylist[3]
So my question is, is there anyway I can unpack mylist when one (or more) items have a value of 0 (and not null or None) without going through each one of them as "if x is None: x = 0"?
A:
You can still using unpacking, just fix up the None values afterward.
name, apples, candies, color = mylist
if apples is None:
apples = 0
if candies is None:
candies = 0
If you have lots of columns to fix, you can use a list comprehension to fix up all the None values in the list.
mylist = [0 if x is None else x for x in mylist]
name, apples, candies, color = mylist
I doubt that 0 is really being turned into None, you probably have NULL values in the table. You can use IFNULL() to convert them:
SELECT name, IFNULL(apples, 0), IFNULL(candies, 0), color
FROM tablename
|
How to automatically unpack list that contains some 0 values?
|
When I try to unpack a list data for a MySQL database query that has some columns with value 0, I get an error.
Name (varchar)
Apples(int)
Candies(int)
Color (varchar)
John
5
0
Blue
If I unpack my query result like:
name, apples, candies, color = mylist
I'll get a NoneType error because candies values (in this example) is considered as None rather than 0.
The workaround I currently have is (which defeats the purpose and benefit of unpacking):
name = mylist[0]
if apples is None:
apples = 0
else apples = mylist[1]
if candies is None:
candies = 0
else candies = mylist[2]
color = mylist[3]
So my question is, is there anyway I can unpack mylist when one (or more) items have a value of 0 (and not null or None) without going through each one of them as "if x is None: x = 0"?
|
[
"You can still using unpacking, just fix up the None values afterward.\nname, apples, candies, color = mylist\nif apples is None:\n apples = 0\nif candies is None:\n candies = 0\n\nIf you have lots of columns to fix, you can use a list comprehension to fix up all the None values in the list.\nmylist = [0 if x is None else x for x in mylist]\nname, apples, candies, color = mylist\n\nI doubt that 0 is really being turned into None, you probably have NULL values in the table. You can use IFNULL() to convert them:\nSELECT name, IFNULL(apples, 0), IFNULL(candies, 0), color\nFROM tablename\n\n"
] |
[
1
] |
[] |
[] |
[
"iterable_unpacking",
"mysql",
"python"
] |
stackoverflow_0074497706_iterable_unpacking_mysql_python.txt
|
Q:
got ZeroDivisionError: float division by zero
So i make a streamlit app and implemented some math formula
import streamlit as st
st.title("SISTEM PERSAMAAN LINEAR DUA VARIABEL")
st.subheader("Persamaan 1: ax+by=c")
a = st.number_input("Masukan Nilai Variabel a")
b = st.number_input("Masukan Nilai Variabel b")
c = st.number_input("Masukan Nilai Variabel c")
st.subheader("Persamaan 2: px+qy=r")
p = st.number_input("Masukan Nilai Variabel p")
q = st.number_input("Masukan Nilai Variabel q")
r = st.number_input("Masukan Nilai Variabel r")
x = (c*q-r*b)/(a*q-p*b)
st.write(x)
st.caption("Note: AI KAKURU akan mencari variabel x dengan metode eliminasi lalu mencari variabel y dengan metode subtitusi")
it work properly using vanilla python, any idea?
so i want to implement some math formula, 2 variabel linear or something, i don't know what is proper english translate for it. It works properly when i use vanilla python, but when i write it in streamlit. it doesn't work
A:
The default value of number_input is 0. Hence, when you first start the app, c, q, r, b, a, q, p, b is all 0. It would be quite obvious to see that (a*q-p*b) is 0, and hence it will result a Zero Division Error.
A solution to this is to add an if statement to check if the value of (a*q-p*b) is 0. Refer to the code below.
import streamlit as st
st.title("SISTEM PERSAMAAN LINEAR DUA VARIABEL")
st.subheader("Persamaan 1: ax+by=c")
a = st.number_input("Masukan Nilai Variabel a")
b = st.number_input("Masukan Nilai Variabel b")
c = st.number_input("Masukan Nilai Variabel c")
st.subheader("Persamaan 2: px+qy=r")
p = st.number_input("Masukan Nilai Variabel p")
q = st.number_input("Masukan Nilai Variabel q")
r = st.number_input("Masukan Nilai Variabel r")
if a*q-b*p == 0:
st.write("Tidak ada solusi")
else:
x = (c*q-r*b)/(a*q-p*b)
st.write(x)
st.caption("Note: AI KAKURU akan mencari variabel x dengan metode eliminasi lalu mencari variabel y dengan metode subtitusi")
|
got ZeroDivisionError: float division by zero
|
So i make a streamlit app and implemented some math formula
import streamlit as st
st.title("SISTEM PERSAMAAN LINEAR DUA VARIABEL")
st.subheader("Persamaan 1: ax+by=c")
a = st.number_input("Masukan Nilai Variabel a")
b = st.number_input("Masukan Nilai Variabel b")
c = st.number_input("Masukan Nilai Variabel c")
st.subheader("Persamaan 2: px+qy=r")
p = st.number_input("Masukan Nilai Variabel p")
q = st.number_input("Masukan Nilai Variabel q")
r = st.number_input("Masukan Nilai Variabel r")
x = (c*q-r*b)/(a*q-p*b)
st.write(x)
st.caption("Note: AI KAKURU akan mencari variabel x dengan metode eliminasi lalu mencari variabel y dengan metode subtitusi")
it work properly using vanilla python, any idea?
so i want to implement some math formula, 2 variabel linear or something, i don't know what is proper english translate for it. It works properly when i use vanilla python, but when i write it in streamlit. it doesn't work
|
[
"The default value of number_input is 0. Hence, when you first start the app, c, q, r, b, a, q, p, b is all 0. It would be quite obvious to see that (a*q-p*b) is 0, and hence it will result a Zero Division Error.\nA solution to this is to add an if statement to check if the value of (a*q-p*b) is 0. Refer to the code below.\nimport streamlit as st\n\nst.title(\"SISTEM PERSAMAAN LINEAR DUA VARIABEL\")\nst.subheader(\"Persamaan 1: ax+by=c\")\na = st.number_input(\"Masukan Nilai Variabel a\")\nb = st.number_input(\"Masukan Nilai Variabel b\")\nc = st.number_input(\"Masukan Nilai Variabel c\")\nst.subheader(\"Persamaan 2: px+qy=r\")\np = st.number_input(\"Masukan Nilai Variabel p\")\nq = st.number_input(\"Masukan Nilai Variabel q\")\nr = st.number_input(\"Masukan Nilai Variabel r\")\nif a*q-b*p == 0:\n st.write(\"Tidak ada solusi\")\nelse:\n x = (c*q-r*b)/(a*q-p*b)\n st.write(x)\nst.caption(\"Note: AI KAKURU akan mencari variabel x dengan metode eliminasi lalu mencari variabel y dengan metode subtitusi\")\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"streamlit"
] |
stackoverflow_0074497484_python_streamlit.txt
|
Q:
determine if datetime index is within a list of date ranges
i have the following code data...
import pandas as pd, numpy as np
from datetime import datetime
end_dt = datetime.today()
st_dt = (end_dt + pd.DateOffset(-10)).date()
df_index = pd.date_range(st_dt, end_dt)
df = pd.DataFrame(index=df_index, columns=['in_range'])
data = [pd.to_datetime(['2022-11-08','2022-11-10']), pd.to_datetime(['2022-11-13','2022-11-15'])]
dt_ranges = pd.DataFrame(data,columns={'st_dt':'datetimens[64]', 'end_dt': 'datetimens[64]'})
this produces the following two dataframes:
df:
in_range
2022-11-08 NaN
2022-11-09 NaN
2022-11-10 NaN
2022-11-11 NaN
2022-11-12 NaN
2022-11-13 NaN
2022-11-14 NaN
2022-11-15 NaN
2022-11-16 NaN
2022-11-17 NaN
2022-11-18 NaN
and date_ranges:
st_dt end_dt
0 2022-11-08 2022-11-10
1 2022-11-13 2022-11-15
I would like to update the 'in_range' column to indicate if the index falls within any of the pairs of start and end dates of the 2nd dataframe. so i should end up with this:
in_range
2022-11-08 True
2022-11-09 True
2022-11-10 True
2022-11-11 NaN
2022-11-12 NaN
2022-11-13 True
2022-11-14 True
2022-11-15 True
2022-11-16 NaN
2022-11-17 NaN
2022-11-18 NaN
I've gone down the path of trying to do this with using lambda and iteration. but to me that seems in efficient.
def in_range(index_date, date_ranges):
for r in date_ranges.values:
if (r[0] >= index_date) & (r[1] <= index_date):
return True
return False
df['in_range'] = df.reset_index().apply(lambda x: in_range(x.date, dt_ranges), axis=1)
the above sets in_range to NaNs always, despite the code returning the correct values. i suspect it's because i am resetting the index and so it can not align. Also, as mentioned - this solution probably is pretty inefficient
is there a more pythonic/pandemic way of doing this?
A:
Use merge_asof and boolean indexing:
s = df.index.to_series()
m = (pd.merge_asof(s.rename('st_dt'), dt_ranges)
['end_dt'].ge(s.to_numpy()).to_numpy()
)
df.loc[m, 'in_range'] = True
NB. The intervals in dt_ranges should be non-overlapping.
Output:
in_range
2022-11-08 True
2022-11-09 True
2022-11-10 True
2022-11-11 NaN
2022-11-12 NaN
2022-11-13 True
2022-11-14 True
2022-11-15 True
2022-11-16 NaN
2022-11-17 NaN
2022-11-18 NaN
A:
One option is to compute the non-equi join is with conditional_join, which can handle overlaps:
# pip install pyjanitor
import pandas as pd
import janitor
(
df
.reset_index()
.conditional_join(
dt_ranges,
('index', 'st_dt', '>='),
('index', 'end_dt', '<='),
# depending on your data size
# setting use_numba to True
# can improve performance
# of course, this requires numba installed
use_numba = False,
how = 'left',
# performance is better when
# sort_by_appearance is False
sort_by_appearance=True)
.assign(in_range = lambda df: df.in_range.mask(df.st_dt.notna(), True))
.iloc[:, :2]
.set_index('index')
)
in_range
index
2022-11-08 True
2022-11-09 True
2022-11-10 True
2022-11-11 NaN
2022-11-12 NaN
2022-11-13 True
2022-11-14 True
2022-11-15 True
2022-11-16 NaN
2022-11-17 NaN
2022-11-18 NaN
|
determine if datetime index is within a list of date ranges
|
i have the following code data...
import pandas as pd, numpy as np
from datetime import datetime
end_dt = datetime.today()
st_dt = (end_dt + pd.DateOffset(-10)).date()
df_index = pd.date_range(st_dt, end_dt)
df = pd.DataFrame(index=df_index, columns=['in_range'])
data = [pd.to_datetime(['2022-11-08','2022-11-10']), pd.to_datetime(['2022-11-13','2022-11-15'])]
dt_ranges = pd.DataFrame(data,columns={'st_dt':'datetimens[64]', 'end_dt': 'datetimens[64]'})
this produces the following two dataframes:
df:
in_range
2022-11-08 NaN
2022-11-09 NaN
2022-11-10 NaN
2022-11-11 NaN
2022-11-12 NaN
2022-11-13 NaN
2022-11-14 NaN
2022-11-15 NaN
2022-11-16 NaN
2022-11-17 NaN
2022-11-18 NaN
and date_ranges:
st_dt end_dt
0 2022-11-08 2022-11-10
1 2022-11-13 2022-11-15
I would like to update the 'in_range' column to indicate if the index falls within any of the pairs of start and end dates of the 2nd dataframe. so i should end up with this:
in_range
2022-11-08 True
2022-11-09 True
2022-11-10 True
2022-11-11 NaN
2022-11-12 NaN
2022-11-13 True
2022-11-14 True
2022-11-15 True
2022-11-16 NaN
2022-11-17 NaN
2022-11-18 NaN
I've gone down the path of trying to do this with using lambda and iteration. but to me that seems in efficient.
def in_range(index_date, date_ranges):
for r in date_ranges.values:
if (r[0] >= index_date) & (r[1] <= index_date):
return True
return False
df['in_range'] = df.reset_index().apply(lambda x: in_range(x.date, dt_ranges), axis=1)
the above sets in_range to NaNs always, despite the code returning the correct values. i suspect it's because i am resetting the index and so it can not align. Also, as mentioned - this solution probably is pretty inefficient
is there a more pythonic/pandemic way of doing this?
|
[
"Use merge_asof and boolean indexing:\ns = df.index.to_series()\nm = (pd.merge_asof(s.rename('st_dt'), dt_ranges)\n ['end_dt'].ge(s.to_numpy()).to_numpy()\n )\n\ndf.loc[m, 'in_range'] = True\n\nNB. The intervals in dt_ranges should be non-overlapping.\nOutput:\n in_range\n2022-11-08 True\n2022-11-09 True\n2022-11-10 True\n2022-11-11 NaN\n2022-11-12 NaN\n2022-11-13 True\n2022-11-14 True\n2022-11-15 True\n2022-11-16 NaN\n2022-11-17 NaN\n2022-11-18 NaN\n\n",
"One option is to compute the non-equi join is with conditional_join, which can handle overlaps:\n# pip install pyjanitor\nimport pandas as pd\nimport janitor\n(\ndf\n.reset_index()\n.conditional_join(\n dt_ranges, \n ('index', 'st_dt', '>='), \n ('index', 'end_dt', '<='), \n # depending on your data size\n # setting use_numba to True\n # can improve performance\n # of course, this requires numba installed\n use_numba = False,\n how = 'left', \n # performance is better when\n # sort_by_appearance is False\n sort_by_appearance=True)\n.assign(in_range = lambda df: df.in_range.mask(df.st_dt.notna(), True))\n.iloc[:, :2]\n.set_index('index')\n)\n\n in_range\nindex \n2022-11-08 True\n2022-11-09 True\n2022-11-10 True\n2022-11-11 NaN\n2022-11-12 NaN\n2022-11-13 True\n2022-11-14 True\n2022-11-15 True\n2022-11-16 NaN\n2022-11-17 NaN\n2022-11-18 NaN\n\n"
] |
[
4,
3
] |
[] |
[] |
[
"data_science",
"numpy",
"pandas",
"python"
] |
stackoverflow_0074495142_data_science_numpy_pandas_python.txt
|
Q:
xml parsing with extra '\n' and whitespaces using lxml library
I wrote a python program with lxml library to parse a xml file using its xpath. The value and xpath are all correct but it returns many '\n' and white spaces just like the xml file's formatting.
here is my code:
from lxml import etree
from xml.dom import minidom
#data = minidom.parse('D:/LocalSpark/bitmap.xml')
sigxml = etree.parse('D:/LocalSpark/bitmap.xml',etree.XMLParser(remove_blank_text=True, load_dtd=True))
xpath = '/OneMessage[@Name="NR RRCReconfiguration"]/BalongMessage/Content/L3MessageContent/DL-DCCH-Message/message/c1/rrcReconfiguration/criticalExtensions/rrcReconfiguration/measConfig/measObjectToAddModList/MeasObjectToAddMod/measObject/measObjectNR/referenceSignalConfig/ssb-ConfigMobility/ssb-ToMeasure/setup/mediumBitmap'
info = 10000000
for node in sigxml.xpath(xpath):
print('node: ', node)
print('node.tag: ',node.tag)
print('node.text:',node.text)
print('node.item:',node.items())
print('node.attrib:',node.attrib)
if info == node.text:
print("%s info do exist!"%info)
else:
print("%s info do not exist!!!"%info)
here is the xml file:
<OneMessage Name="NR RRCReconfiguration" MsgTimeStamp="1668594368290"><BalongMessage><Header><usRsvd>4608</usRsvd><ucbMdmId>0</ucbMdmId><ucbMsgType>3</ucbMsgType><ucbRsvd>0</ucbRsvd><ulMsgClsID>26080000</ulMsgClsID><ullbTimeStamp>1853637.763054</ullbTimeStamp><ullbCpuTransID>38693</ullbCpuTransID><usSocpTransID>20388</usSocpTransID><ullLocalTime>133129368818699187</ullLocalTime><ulTransNo>6107</ulTransNo><ulSendPID>131072</ulSendPID><ulRecvPID>0</ulRecvPID><ulPrimID>00000003</ulPrimID><ucbOtaDirect>DL(1)</ucbOtaDirect><ucbPrintLevel>63</ucbPrintLevel><ulDataSize>56</ulDataSize></Header><Content><L3MessageContent><DL-DCCH-Message>
<message>
<c1>
<rrcReconfiguration>
<criticalExtensions>
<rrcReconfiguration>
<measConfig>
<measObjectToAddModList>
<MeasObjectToAddMod>
<measObject>
<measObjectNR>
<referenceSignalConfig>
<ssb-ConfigMobility>
<ssb-ToMeasure>
<setup>
<mediumBitmap>
10000000
</mediumBitmap>
</setup>
</ssb-ToMeasure>
</ssb-ConfigMobility>
</referenceSignalConfig>
</measObjectNR>
</measObject>
</MeasObjectToAddMod>
</measObjectToAddModList>
</measConfig>
</rrcReconfiguration>
</criticalExtensions>
</rrcReconfiguration>
</c1>
</message>
</DL-DCCH-Message>
</L3MessageContent></Content></BalongMessage></OneMessage>
Here is the result:
node: <Element mediumBitmap at 0x22e3c645f80>
node.tag: mediumBitmap
node.text:
10000000
node.item: []
node.attrib: {}
10000000 info do not exist!!!
My problem is that clearly the code can read and find mediumBitmap this element but as it shows in xml file, it has \n before and after it. So when the program goes on, it returns that mediumBitmap's text value is
\n 10000000 \n
but not just 10000000
It is a standard xml from a project so I can't edit it.
I tried to add remove_blank_text=True to parse or using minidom
all failed
A:
There are many ways to strip spaces and newlines, however, a simple technique would be to use regex to remove them.
The critical line is this one:
int(re.sub(r'[\\n\s]*', '', node.text))
Which searches and substitutes all carriage returns and spaces in node.text and converts them to '' nothing. Then cast to int so that the info variable matches accordingly.
Here is the code:
from lxml import etree
from xml.dom import minidom
import re
#data = minidom.parse('D:/LocalSpark/bitmap.xml')
sigxml = etree.parse('D:/LocalSpark/bitmap.xml',etree.XMLParser(remove_blank_text=True, load_dtd=True))
xpath = '/OneMessage[@Name="NR RRCReconfiguration"]/BalongMessage/Content/L3MessageContent/DL-DCCH-Message/message/c1/rrcReconfiguration/criticalExtensions/rrcReconfiguration/measConfig/measObjectToAddModList/MeasObjectToAddMod/measObject/measObjectNR/referenceSignalConfig/ssb-ConfigMobility/ssb-ToMeasure/setup/mediumBitmap'
info = 10000000
for node in sigxml.xpath(xpath):
print('node: ', node)
print('node.tag: ',node.tag)
print('node.text:',node.text)
print('node.item:',node.items())
print('node.attrib:',node.attrib)
if info == int(re.sub(r'[\\n\s]*', '', node.text)):
print("%s info do exist!"%info)
else:
print("%s info do not exist!!!"%info)
|
xml parsing with extra '\n' and whitespaces using lxml library
|
I wrote a python program with lxml library to parse a xml file using its xpath. The value and xpath are all correct but it returns many '\n' and white spaces just like the xml file's formatting.
here is my code:
from lxml import etree
from xml.dom import minidom
#data = minidom.parse('D:/LocalSpark/bitmap.xml')
sigxml = etree.parse('D:/LocalSpark/bitmap.xml',etree.XMLParser(remove_blank_text=True, load_dtd=True))
xpath = '/OneMessage[@Name="NR RRCReconfiguration"]/BalongMessage/Content/L3MessageContent/DL-DCCH-Message/message/c1/rrcReconfiguration/criticalExtensions/rrcReconfiguration/measConfig/measObjectToAddModList/MeasObjectToAddMod/measObject/measObjectNR/referenceSignalConfig/ssb-ConfigMobility/ssb-ToMeasure/setup/mediumBitmap'
info = 10000000
for node in sigxml.xpath(xpath):
print('node: ', node)
print('node.tag: ',node.tag)
print('node.text:',node.text)
print('node.item:',node.items())
print('node.attrib:',node.attrib)
if info == node.text:
print("%s info do exist!"%info)
else:
print("%s info do not exist!!!"%info)
here is the xml file:
<OneMessage Name="NR RRCReconfiguration" MsgTimeStamp="1668594368290"><BalongMessage><Header><usRsvd>4608</usRsvd><ucbMdmId>0</ucbMdmId><ucbMsgType>3</ucbMsgType><ucbRsvd>0</ucbRsvd><ulMsgClsID>26080000</ulMsgClsID><ullbTimeStamp>1853637.763054</ullbTimeStamp><ullbCpuTransID>38693</ullbCpuTransID><usSocpTransID>20388</usSocpTransID><ullLocalTime>133129368818699187</ullLocalTime><ulTransNo>6107</ulTransNo><ulSendPID>131072</ulSendPID><ulRecvPID>0</ulRecvPID><ulPrimID>00000003</ulPrimID><ucbOtaDirect>DL(1)</ucbOtaDirect><ucbPrintLevel>63</ucbPrintLevel><ulDataSize>56</ulDataSize></Header><Content><L3MessageContent><DL-DCCH-Message>
<message>
<c1>
<rrcReconfiguration>
<criticalExtensions>
<rrcReconfiguration>
<measConfig>
<measObjectToAddModList>
<MeasObjectToAddMod>
<measObject>
<measObjectNR>
<referenceSignalConfig>
<ssb-ConfigMobility>
<ssb-ToMeasure>
<setup>
<mediumBitmap>
10000000
</mediumBitmap>
</setup>
</ssb-ToMeasure>
</ssb-ConfigMobility>
</referenceSignalConfig>
</measObjectNR>
</measObject>
</MeasObjectToAddMod>
</measObjectToAddModList>
</measConfig>
</rrcReconfiguration>
</criticalExtensions>
</rrcReconfiguration>
</c1>
</message>
</DL-DCCH-Message>
</L3MessageContent></Content></BalongMessage></OneMessage>
Here is the result:
node: <Element mediumBitmap at 0x22e3c645f80>
node.tag: mediumBitmap
node.text:
10000000
node.item: []
node.attrib: {}
10000000 info do not exist!!!
My problem is that clearly the code can read and find mediumBitmap this element but as it shows in xml file, it has \n before and after it. So when the program goes on, it returns that mediumBitmap's text value is
\n 10000000 \n
but not just 10000000
It is a standard xml from a project so I can't edit it.
I tried to add remove_blank_text=True to parse or using minidom
all failed
|
[
"There are many ways to strip spaces and newlines, however, a simple technique would be to use regex to remove them.\nThe critical line is this one:\nint(re.sub(r'[\\\\n\\s]*', '', node.text))\n\nWhich searches and substitutes all carriage returns and spaces in node.text and converts them to '' nothing. Then cast to int so that the info variable matches accordingly.\nHere is the code:\nfrom lxml import etree\nfrom xml.dom import minidom\nimport re\n\n\n#data = minidom.parse('D:/LocalSpark/bitmap.xml')\nsigxml = etree.parse('D:/LocalSpark/bitmap.xml',etree.XMLParser(remove_blank_text=True, load_dtd=True))\nxpath = '/OneMessage[@Name=\"NR RRCReconfiguration\"]/BalongMessage/Content/L3MessageContent/DL-DCCH-Message/message/c1/rrcReconfiguration/criticalExtensions/rrcReconfiguration/measConfig/measObjectToAddModList/MeasObjectToAddMod/measObject/measObjectNR/referenceSignalConfig/ssb-ConfigMobility/ssb-ToMeasure/setup/mediumBitmap'\ninfo = 10000000 \n\nfor node in sigxml.xpath(xpath):\n print('node: ', node)\n print('node.tag: ',node.tag)\n print('node.text:',node.text)\n print('node.item:',node.items()) \n print('node.attrib:',node.attrib)\n \n if info == int(re.sub(r'[\\\\n\\s]*', '', node.text)):\n print(\"%s info do exist!\"%info)\n else:\n print(\"%s info do not exist!!!\"%info)\n\n"
] |
[
0
] |
[] |
[] |
[
"elementtree",
"lxml",
"python",
"python_3.x",
"xml_parsing"
] |
stackoverflow_0074497687_elementtree_lxml_python_python_3.x_xml_parsing.txt
|
Q:
Copying columns into from worksheet into separate Excel files with Python
Sorry I am new to openpyxl and pandas and I am looking to take the columns of one excel sheet and create separate workbooks containing the first column and one column from the sheet.
| Column A | Column B |Column C |
| -------- | -------- |-------- |
| Cell 1 | Cell 2 | Cell 5 |
| Cell 3 | Cell 4 | Cell 6 |
I would like the output of each table to be column a followed by one of the other columns.
Sample Data
This prints all of the columns out to separate files but no matter where the save function is placed it will always just copy the whole sheet.
from openpyxl import Workbook, load_workbook
wb = load_workbook('billingTest.xlsx')
ws = wb.active
column_a = ws['A']
#row_1 = ws['1']
row = ws['1']
counter = 0
for col in ws.iter_cols():
counter+=1
for a in column_a:
print(a.value)
for cell in col:
print(cell.value)
wb.save('billingTest'+str(counter)+'.xlsx')
A:
If my assumption of your requirement is correct, the usual way is to copy the required columns to a new excel file and save. There are many questions/answers on how to do this on SO just need to search.
This is an example uses the different angle of deleting the unwanted columns so that only the two columns you require remain then saving the workbook.
The code loads 'billingTest.xlsx' as a binary file then loads the openpyxl workbook from this data using a loop from Column B to the maximum number of columns. Each loop deletes the unwanted columns from the sheet leaving Column A and the next current required. It then saves the numbered workbook.
The workbook needs to be reloaded each time since the columns deleted on the previous loop will be missing on the next loop. Rather than loading the workbook from the file each time its refreshed from the initial file load.
I'm guessing from your example image that B10, C10, D10 and E10 are formulas summing the columns so the other requirement is to update these formulas as openpyxl does not manage formulas when columns/rows are deleted.
This method can be good for retaining formatting since it is basically saving the original file each time minus the unwanted columns.
from openpyxl import load_workbook
from io import BytesIO
file = 'billingTest.xlsx'
with open(file, "rb") as fh:
wb_data = BytesIO(fh.read())
max_columns = load_workbook(wb_data).active.max_column
for counter in range(2, max_columns+1):
wb = load_workbook(wb_data)
ws = wb.active
for i in reversed(range(2, max_columns+1)):
if i != counter:
ws.delete_cols(idx=i)
ws.cell(10,2).value = '=SUM(B2:B9)'
wb.save('billingTest' + str(counter-1) + '.xlsx')
The result of this code run is 4 excel files, billingTest1.xlsx - billingTest4.xlsx each containing Column A and then for each file, Column B being column B then C then D the E.
|
Copying columns into from worksheet into separate Excel files with Python
|
Sorry I am new to openpyxl and pandas and I am looking to take the columns of one excel sheet and create separate workbooks containing the first column and one column from the sheet.
| Column A | Column B |Column C |
| -------- | -------- |-------- |
| Cell 1 | Cell 2 | Cell 5 |
| Cell 3 | Cell 4 | Cell 6 |
I would like the output of each table to be column a followed by one of the other columns.
Sample Data
This prints all of the columns out to separate files but no matter where the save function is placed it will always just copy the whole sheet.
from openpyxl import Workbook, load_workbook
wb = load_workbook('billingTest.xlsx')
ws = wb.active
column_a = ws['A']
#row_1 = ws['1']
row = ws['1']
counter = 0
for col in ws.iter_cols():
counter+=1
for a in column_a:
print(a.value)
for cell in col:
print(cell.value)
wb.save('billingTest'+str(counter)+'.xlsx')
|
[
"If my assumption of your requirement is correct, the usual way is to copy the required columns to a new excel file and save. There are many questions/answers on how to do this on SO just need to search.\n\nThis is an example uses the different angle of deleting the unwanted columns so that only the two columns you require remain then saving the workbook.\nThe code loads 'billingTest.xlsx' as a binary file then loads the openpyxl workbook from this data using a loop from Column B to the maximum number of columns. Each loop deletes the unwanted columns from the sheet leaving Column A and the next current required. It then saves the numbered workbook.\nThe workbook needs to be reloaded each time since the columns deleted on the previous loop will be missing on the next loop. Rather than loading the workbook from the file each time its refreshed from the initial file load.\nI'm guessing from your example image that B10, C10, D10 and E10 are formulas summing the columns so the other requirement is to update these formulas as openpyxl does not manage formulas when columns/rows are deleted.\nThis method can be good for retaining formatting since it is basically saving the original file each time minus the unwanted columns.\nfrom openpyxl import load_workbook\nfrom io import BytesIO\n\nfile = 'billingTest.xlsx'\n\nwith open(file, \"rb\") as fh:\n wb_data = BytesIO(fh.read())\n\nmax_columns = load_workbook(wb_data).active.max_column\n\nfor counter in range(2, max_columns+1):\n wb = load_workbook(wb_data)\n ws = wb.active\n for i in reversed(range(2, max_columns+1)):\n if i != counter:\n ws.delete_cols(idx=i)\n ws.cell(10,2).value = '=SUM(B2:B9)'\n wb.save('billingTest' + str(counter-1) + '.xlsx')\n\nThe result of this code run is 4 excel files, billingTest1.xlsx - billingTest4.xlsx each containing Column A and then for each file, Column B being column B then C then D the E.\n"
] |
[
0
] |
[] |
[] |
[
"excel",
"openpyxl",
"pandas",
"python"
] |
stackoverflow_0074493230_excel_openpyxl_pandas_python.txt
|
Q:
NTEventLogHandler and "The description cannot be found"
When trying to log something using NTEventLogHandler, I get the following message in "View Events":
"The description for Event ID ( 1 ) in Source ( Python Logging Test ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. ..."
Logger initialization is as follows:
def _create_windows_service_log(self):
if getattr(sys, 'frozen', False):
dllname = None
elif __file__:
dllname = os.path.dirname(__file__)
ntl = logging.handlers.NTEventLogHandler(self._app_name, dllname, self._app_name)
self._logger = logging.getLogger(self._app_name)
self._logger.setLevel(logging.INFO)
self._logger.addHandler(ntl)
And its use is like that:
self._logger.info(a_msg)
I checked the data in the registry. The key "EventMessageFile" indicates the correct path to the file "win32service.pyd".
I tried to use that solution, but it didn’t work.
A:
As mentioned in the documentation about the dllname parameter:
The dllname should give the fully qualified pathname of a .dll or .exe which contains message definitions to hold in the log (if not specified, 'win32service.pyd' is used - this is installed with the Win32 extensions and contains some basic placeholder message definitions ...)
I think that if the message IDs aren't found in the named DLL, you will get this problem. You seem to be passing dllname as either None or the name of a directory, which can't be a DLL!
|
NTEventLogHandler and "The description cannot be found"
|
When trying to log something using NTEventLogHandler, I get the following message in "View Events":
"The description for Event ID ( 1 ) in Source ( Python Logging Test ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. ..."
Logger initialization is as follows:
def _create_windows_service_log(self):
if getattr(sys, 'frozen', False):
dllname = None
elif __file__:
dllname = os.path.dirname(__file__)
ntl = logging.handlers.NTEventLogHandler(self._app_name, dllname, self._app_name)
self._logger = logging.getLogger(self._app_name)
self._logger.setLevel(logging.INFO)
self._logger.addHandler(ntl)
And its use is like that:
self._logger.info(a_msg)
I checked the data in the registry. The key "EventMessageFile" indicates the correct path to the file "win32service.pyd".
I tried to use that solution, but it didn’t work.
|
[
"As mentioned in the documentation about the dllname parameter:\n\nThe dllname should give the fully qualified pathname of a .dll or .exe which contains message definitions to hold in the log (if not specified, 'win32service.pyd' is used - this is installed with the Win32 extensions and contains some basic placeholder message definitions ...)\n\nI think that if the message IDs aren't found in the named DLL, you will get this problem. You seem to be passing dllname as either None or the name of a directory, which can't be a DLL!\n"
] |
[
0
] |
[] |
[] |
[
"event_log",
"logging",
"python",
"windows"
] |
stackoverflow_0074490112_event_log_logging_python_windows.txt
|
Q:
Function does not print the randomness of two other functions. NameError: the name 'x' is not defined
I have a problem with the All function. I would like to use the random result of the Template1 function and the random result of the Template2 function. Then I apply another random to the two functions inside All, but I get the error:
NameError: the name 'Template1' is not defined
How can I fix? By solving the definition, will the script print correctly what I asked? Thank you
The output I would like to receive is only one (1) of these: "aaa", "bbb", "ccc", "ddd", "eee", "fff"
import random
class Main:
def __init__(self):
self.templ1 = ("aaa", "bbb", "ccc")
self.templ2 = ("ddd", "eee", "fff")
def Template1(self):
templ1_random = print(random.choice(self.templ1))
return templ1_random
def Template2(self):
templ2_random = print(random.choice(self.templ2))
return templ2_random
def All(self):
list0 = [Template1(self), Template2(self)]
all_random = print(random.choice(list0))
return all_random
final = Main()
final.All()
A:
Remove all the print() calls from your methods. They're setting the return variables to None, since print() prints its argument, it doesn't return it.
To see the result, use print(final.All()) at the end.
import random
class Main:
def __init__(self):
self.templ1 = ("aaa", "bbb", "ccc")
self.templ2 = ("ddd", "eee", "fff")
def Template1(self):
templ1_random =random.choice(self.templ1)
return templ1_random
def Template2(self):
templ2_random = random.choice(self.templ2)
return templ2_random
def All(self):
list0 = [self.Template1(), self.Template2()]
all_random = random.choice(list0)
return all_random
final = Main()
print(final.All())
DEMO
A:
Change list0 = [Template1(self), Template2(self)] to [self.Template1(), self.Template2()]
import random
class Main:
def __init__(self):
self.templ1 = ("aaa", "bbb", "ccc")
self.templ2 = ("ddd", "eee", "fff")
def Template1(self):
templ1_random = random.choice(self.templ1)
return templ1_random
def Template2(self):
templ2_random = random.choice(self.templ2)
return templ2_random
def All(self):
list0 = [self.Template1(), self.Template2()]
all_random = random.choice(list0)
return all_random
final = Main()
print(final.All())
|
Function does not print the randomness of two other functions. NameError: the name 'x' is not defined
|
I have a problem with the All function. I would like to use the random result of the Template1 function and the random result of the Template2 function. Then I apply another random to the two functions inside All, but I get the error:
NameError: the name 'Template1' is not defined
How can I fix? By solving the definition, will the script print correctly what I asked? Thank you
The output I would like to receive is only one (1) of these: "aaa", "bbb", "ccc", "ddd", "eee", "fff"
import random
class Main:
def __init__(self):
self.templ1 = ("aaa", "bbb", "ccc")
self.templ2 = ("ddd", "eee", "fff")
def Template1(self):
templ1_random = print(random.choice(self.templ1))
return templ1_random
def Template2(self):
templ2_random = print(random.choice(self.templ2))
return templ2_random
def All(self):
list0 = [Template1(self), Template2(self)]
all_random = print(random.choice(list0))
return all_random
final = Main()
final.All()
|
[
"Remove all the print() calls from your methods. They're setting the return variables to None, since print() prints its argument, it doesn't return it.\nTo see the result, use print(final.All()) at the end.\nimport random\n\nclass Main:\n\n def __init__(self):\n self.templ1 = (\"aaa\", \"bbb\", \"ccc\")\n self.templ2 = (\"ddd\", \"eee\", \"fff\")\n\n def Template1(self):\n templ1_random =random.choice(self.templ1)\n return templ1_random\n\n def Template2(self):\n templ2_random = random.choice(self.templ2)\n return templ2_random\n\n def All(self):\n list0 = [self.Template1(), self.Template2()]\n all_random = random.choice(list0)\n return all_random\n\n\nfinal = Main()\nprint(final.All())\n\nDEMO\n",
"Change list0 = [Template1(self), Template2(self)] to [self.Template1(), self.Template2()]\nimport random\nclass Main:\ndef __init__(self):\n self.templ1 = (\"aaa\", \"bbb\", \"ccc\")\n self.templ2 = (\"ddd\", \"eee\", \"fff\")\n\ndef Template1(self):\n templ1_random = random.choice(self.templ1)\n return templ1_random\n\ndef Template2(self):\n templ2_random = random.choice(self.templ2)\n return templ2_random\n\ndef All(self):\n list0 = [self.Template1(), self.Template2()]\n all_random = random.choice(list0)\n return all_random\n\n\nfinal = Main()\nprint(final.All())\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074497758_python_python_3.x.txt
|
Q:
CSRF verification failed when used csrf_token and CSRF_TRUSTED_ORIGINS
I try to change my profile but when i subbmit my form, it shows CSRF verification failed even when i used csrf_token and CSRF_TRUSTED_ORIGINS.
Here is my models:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
avatar = models.ImageField(default='static/images/default.jpg', upload_to='static/images')
@classmethod
def create(cls, authenticated_user):
profile = cls(user=authenticated_user, name= authenticated_user)
# do something with the book
return profile
def __str__(self):
return self.user.username
My view:
@login_required
def profile(request):
"""Show profile"""
# profile = UserProfile.objects.get(id= request.user)
profile = UserProfile.objects.get(user=request.user)
if request.method != 'POST':
# No data submitted; create a blank form.
form = UserProfileForm(instance=profile)
else:
# POST data submitted; process data.
form = UserProfileForm(instance=profile, data= request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('base:index'))
context = {'profile': profile}
return render(request, 'users/profile.html', context)
My template:
{% if user.is_authenticated %}
<p>Thong tin nguoi dung:</p>
<a>Ten nguoi dung: {{profile.name}}</a>
<p>Anh dai dien: <img src="{{profile.avatar.url}}" alt=""></p>
<form action="{% url 'users:profile'%}" method="post">
{% csrf_token %}
<input type="hidden" name="csrfmiddlewaretoken">
<p>
<label for="id_name">Name:</label>
<input type="text" name="name" maxlength="200" required="" id="id_name">
</p>
<p>
<label for="id_avatar">Avatar:</label>
<input type="file" name="avatar" accept="image/*" id="id_avatar">
</p>
<button name="submit">save changes</button>
</form>
{% else %}
{% endif %}
My setting:
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join (BASE_DIR, "static"), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1']
How can i sumit my form ?
A:
Simply try to add type to button tag because when you set action to form tag then you must add type to button tag or input tag.
change this:
<button name="submit">save changes</button>
To this:
<button type="submit">save changes</button>
And see if it solves
|
CSRF verification failed when used csrf_token and CSRF_TRUSTED_ORIGINS
|
I try to change my profile but when i subbmit my form, it shows CSRF verification failed even when i used csrf_token and CSRF_TRUSTED_ORIGINS.
Here is my models:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
avatar = models.ImageField(default='static/images/default.jpg', upload_to='static/images')
@classmethod
def create(cls, authenticated_user):
profile = cls(user=authenticated_user, name= authenticated_user)
# do something with the book
return profile
def __str__(self):
return self.user.username
My view:
@login_required
def profile(request):
"""Show profile"""
# profile = UserProfile.objects.get(id= request.user)
profile = UserProfile.objects.get(user=request.user)
if request.method != 'POST':
# No data submitted; create a blank form.
form = UserProfileForm(instance=profile)
else:
# POST data submitted; process data.
form = UserProfileForm(instance=profile, data= request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('base:index'))
context = {'profile': profile}
return render(request, 'users/profile.html', context)
My template:
{% if user.is_authenticated %}
<p>Thong tin nguoi dung:</p>
<a>Ten nguoi dung: {{profile.name}}</a>
<p>Anh dai dien: <img src="{{profile.avatar.url}}" alt=""></p>
<form action="{% url 'users:profile'%}" method="post">
{% csrf_token %}
<input type="hidden" name="csrfmiddlewaretoken">
<p>
<label for="id_name">Name:</label>
<input type="text" name="name" maxlength="200" required="" id="id_name">
</p>
<p>
<label for="id_avatar">Avatar:</label>
<input type="file" name="avatar" accept="image/*" id="id_avatar">
</p>
<button name="submit">save changes</button>
</form>
{% else %}
{% endif %}
My setting:
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join (BASE_DIR, "static"), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1']
How can i sumit my form ?
|
[
"Simply try to add type to button tag because when you set action to form tag then you must add type to button tag or input tag.\nchange this:\n<button name=\"submit\">save changes</button>\n\nTo this:\n <button type=\"submit\">save changes</button>\n\nAnd see if it solves\n"
] |
[
0
] |
[] |
[] |
[
"csrf",
"django",
"html",
"post",
"python"
] |
stackoverflow_0074497521_csrf_django_html_post_python.txt
|
Q:
Checking if an element exists with Python Selenium
I have a problem; I am using the Selenium (Firefox) web driver to open a webpage, click a few links, etc., and then capture a screenshot.
My script runs fine from the CLI, but when run via a cron job it is not getting past the first find_element() test. I need to add some debug, or something to help me figure out why it is failing.
Basically, I have to click a 'log in' anchor before going to the login page. The construct of the element is:
<a class="lnk" rel="nofollow" href="/login.jsp?destination=/secure/Dash.jspa">log in</a>
I am using the find_element By LINK_TEXT method:
login = driver.find_element(By.LINK_TEXT, "log in").click()
A) How do I check that the link is actually being picked up by Python? Should I use try/catch block?
B) Is there a better/more reliable way to locate the DOM element than by LINK_TEXT? E.g., in jQuery, you can use a more specific selector, $('a.lnk:contains(log in)').do_something();
I have solved the main problem and it was just finger trouble. I was calling the script with incorrect parameters - a simple mistake.
I'd still like some pointers on how to check whether an element exists. Also, an example/explanation of implicit / explicit Waits instead of using a crappy time.sleep() call.
A:
For a):
from selenium.common.exceptions import NoSuchElementException
def check_exists_by_xpath(xpath):
try:
webdriver.find_element_by_xpath(xpath)
except NoSuchElementException:
return False
return True
For b): Moreover, you can take the XPath expression as a standard throughout all your scripts and create functions as above mentions for universal use.
I recommend to use CSS selectors. I recommend not to mix/use "by id", "by name", etc. and use one single approach instead.
A:
You can grab a list of elements instead of a single element. An empty list in python is falsey. Example:
if driver.find_elements(By.CSS_SELECTOR, '#element'):
print "Element exists!"
You can also use By.ID and By.NAME, but that just turns your id or name into a css selector anyway. Source
A:
A) Yes. The easiest way to check if an element exists is to simply call find_element inside a try/catch.
B) Yes, I always try to identify elements without using their text for two reasons:
the text is more likely to change and;
if it is important to you, you won't be able to run your tests against localized builds.
The solution is either:
You can use XPath to find a parent or ancestor element that has an ID or some other unique identifier and then find its child/descendant that matches or;
you could request an ID or name or some other unique identifier for the link itself.
For the follow-up questions, using try/catch is how you can tell if an element exists or not and good examples of waits can be found here: http://seleniumhq.org/docs/04_webdriver_advanced.html
A:
A solution without try&catch and without new imports:
if len(driver.find_elements_by_id('blah')) > 0: # Pay attention: find_element*s*
driver.find_element_by_id('blah').click # Pay attention: find_element
A:
The same as Brian, but add to this answer from tstempko:
I tried and it works quickly:
driver.implicitly_wait(0)
if driver.find_element_by_id("show_reflist"):
driver.find_element_by_id("show_reflist").find_element_by_tag_name("img").click()
After this, I restore my default value:
driver.implicitly_wait(30)
A:
You could also do it more concisely using
driver.find_element_by_id("some_id").size != 0
A:
driver.find_element_by_id("some_id").size() is a class method.
We need:
driver.find_element_by_id("some_id").size which is a dictionary, so:
if driver.find_element_by_id("some_id").size['width'] != 0:
print 'button exist'
A:
You could use is_displayed() like below:
res = driver.find_element_by_id("some_id").is_displayed()
assert res, 'element not displayed!'
A:
When you know the element could not be there, the implicit wait could be a problem. I've created a simple context manager to avoid those waiting times
class PauseExplicitWait(object):
"""
Example usage:
with PauseExplicitWait(driver, 0):
driver.find_element(By.ID, 'element-that-might-not-be-there')
"""
def __init__(self, driver, new_wait=0):
self.driver = driver
self.original_wait = driver.timeouts.implicit_wait
self.new_wait = new_wait
def __enter__(self):
self.driver.implicitly_wait(self.new_wait)
def __exit__(self, exc_type, exc_value, exc_tb):
self.driver.implicitly_wait(self.original_wait)
A:
With the latest Selenium, you can now use you can now use .is_displayed():
https://www.selenium.dev/documentation/webdriver/elements/information/
A:
You can find elements by available methods and check response array length if the length of an array equal the 0 element not exist.
element_exist = False if len(driver.find_elements_by_css_selector('div.eiCW-')) > 0 else True
A:
You can check by find_elements. If the result is null, that element does not exist.
if driver.find_elements(By.SOMETHING, "#someselector") == []:
continue # That element does not exist
A:
A) Use .is_displayed() as explained at Information about web elements:
# After navigating to the URL,
# get the Boolean value for if this element is displayed
is_button_visible = driver.find_element(By.CSS_SELECTOR, "[name='login']").is_displayed()
Continue your Visual Studio Code logic using "is_button_visible" for branching.
B) Refer to Sam Woods's answer
|
Checking if an element exists with Python Selenium
|
I have a problem; I am using the Selenium (Firefox) web driver to open a webpage, click a few links, etc., and then capture a screenshot.
My script runs fine from the CLI, but when run via a cron job it is not getting past the first find_element() test. I need to add some debug, or something to help me figure out why it is failing.
Basically, I have to click a 'log in' anchor before going to the login page. The construct of the element is:
<a class="lnk" rel="nofollow" href="/login.jsp?destination=/secure/Dash.jspa">log in</a>
I am using the find_element By LINK_TEXT method:
login = driver.find_element(By.LINK_TEXT, "log in").click()
A) How do I check that the link is actually being picked up by Python? Should I use try/catch block?
B) Is there a better/more reliable way to locate the DOM element than by LINK_TEXT? E.g., in jQuery, you can use a more specific selector, $('a.lnk:contains(log in)').do_something();
I have solved the main problem and it was just finger trouble. I was calling the script with incorrect parameters - a simple mistake.
I'd still like some pointers on how to check whether an element exists. Also, an example/explanation of implicit / explicit Waits instead of using a crappy time.sleep() call.
|
[
"For a):\nfrom selenium.common.exceptions import NoSuchElementException\ndef check_exists_by_xpath(xpath):\n try:\n webdriver.find_element_by_xpath(xpath)\n except NoSuchElementException:\n return False\n return True\n\nFor b): Moreover, you can take the XPath expression as a standard throughout all your scripts and create functions as above mentions for universal use.\nI recommend to use CSS selectors. I recommend not to mix/use \"by id\", \"by name\", etc. and use one single approach instead.\n",
"You can grab a list of elements instead of a single element. An empty list in python is falsey. Example:\nif driver.find_elements(By.CSS_SELECTOR, '#element'):\n print \"Element exists!\"\n\n\nYou can also use By.ID and By.NAME, but that just turns your id or name into a css selector anyway. Source\n",
"A) Yes. The easiest way to check if an element exists is to simply call find_element inside a try/catch.\nB) Yes, I always try to identify elements without using their text for two reasons:\n\nthe text is more likely to change and;\nif it is important to you, you won't be able to run your tests against localized builds.\n\nThe solution is either:\n\nYou can use XPath to find a parent or ancestor element that has an ID or some other unique identifier and then find its child/descendant that matches or;\nyou could request an ID or name or some other unique identifier for the link itself.\n\nFor the follow-up questions, using try/catch is how you can tell if an element exists or not and good examples of waits can be found here: http://seleniumhq.org/docs/04_webdriver_advanced.html\n",
"A solution without try&catch and without new imports:\nif len(driver.find_elements_by_id('blah')) > 0: # Pay attention: find_element*s*\n driver.find_element_by_id('blah').click # Pay attention: find_element\n\n",
"The same as Brian, but add to this answer from tstempko:\nI tried and it works quickly:\ndriver.implicitly_wait(0)\n\nif driver.find_element_by_id(\"show_reflist\"):\n driver.find_element_by_id(\"show_reflist\").find_element_by_tag_name(\"img\").click()\n\nAfter this, I restore my default value:\ndriver.implicitly_wait(30)\n\n",
"You could also do it more concisely using\ndriver.find_element_by_id(\"some_id\").size != 0\n\n",
"driver.find_element_by_id(\"some_id\").size() is a class method.\nWe need:\ndriver.find_element_by_id(\"some_id\").size which is a dictionary, so:\nif driver.find_element_by_id(\"some_id\").size['width'] != 0:\n print 'button exist'\n\n",
"You could use is_displayed() like below:\nres = driver.find_element_by_id(\"some_id\").is_displayed()\nassert res, 'element not displayed!'\n\n",
"When you know the element could not be there, the implicit wait could be a problem. I've created a simple context manager to avoid those waiting times\nclass PauseExplicitWait(object):\n \"\"\"\n Example usage:\n\n with PauseExplicitWait(driver, 0):\n driver.find_element(By.ID, 'element-that-might-not-be-there')\n \"\"\"\n def __init__(self, driver, new_wait=0):\n self.driver = driver\n self.original_wait = driver.timeouts.implicit_wait\n self.new_wait = new_wait\n \n def __enter__(self):\n self.driver.implicitly_wait(self.new_wait)\n \n def __exit__(self, exc_type, exc_value, exc_tb):\n self.driver.implicitly_wait(self.original_wait)\n \n\n",
"With the latest Selenium, you can now use you can now use .is_displayed():\nhttps://www.selenium.dev/documentation/webdriver/elements/information/\n",
"You can find elements by available methods and check response array length if the length of an array equal the 0 element not exist.\nelement_exist = False if len(driver.find_elements_by_css_selector('div.eiCW-')) > 0 else True\n\n",
"You can check by find_elements. If the result is null, that element does not exist.\nif driver.find_elements(By.SOMETHING, \"#someselector\") == []:\n continue # That element does not exist\n\n",
"A) Use .is_displayed() as explained at Information about web elements:\n# After navigating to the URL,\n# get the Boolean value for if this element is displayed\nis_button_visible = driver.find_element(By.CSS_SELECTOR, \"[name='login']\").is_displayed()\n\nContinue your Visual Studio Code logic using \"is_button_visible\" for branching.\nB) Refer to Sam Woods's answer\n"
] |
[
165,
106,
68,
26,
8,
6,
2,
1,
1,
1,
0,
0,
0
] |
[
"el = WebDriverWait(driver, timeout=3).until(lambda d: d.find_element(By.TAG_NAME,\"p\"))\n\ndoc\n"
] |
[
-1
] |
[
"html",
"python",
"selenium",
"webdriver"
] |
stackoverflow_0009567069_html_python_selenium_webdriver.txt
|
Q:
import janitor as jn TypeError: 'type' object is not subscriptable
after sucessfully downloading the module
!pip install pyjanitor # works successfully
import janitor as jn # which worked just fine in the past, but suddenly throwing the following TypeError
TypeError: 'type' object is not subscriptable
I am using google colab.
I also tried just import janitor instead of import janitor as jn, that also didn't work
any help to fix this is greatly appreciated.
A:
I think that's the package's error.
Another person also reported the error that he can't import the package.
https://github.com/pyjanitor-devs/pyjanitor/issues/1201
Wait for the fix.
Until the fix is released, use the previous package.
To remove the current pyjanitor in jupyter
!pip uninstall pyjanitor --yes
To install the previous version of the package in jupyter.
!pip install pyjanitor==0.23.1
|
import janitor as jn TypeError: 'type' object is not subscriptable
|
after sucessfully downloading the module
!pip install pyjanitor # works successfully
import janitor as jn # which worked just fine in the past, but suddenly throwing the following TypeError
TypeError: 'type' object is not subscriptable
I am using google colab.
I also tried just import janitor instead of import janitor as jn, that also didn't work
any help to fix this is greatly appreciated.
|
[
"I think that's the package's error.\nAnother person also reported the error that he can't import the package.\nhttps://github.com/pyjanitor-devs/pyjanitor/issues/1201\nWait for the fix.\nUntil the fix is released, use the previous package.\nTo remove the current pyjanitor in jupyter\n!pip uninstall pyjanitor --yes\n\nTo install the previous version of the package in jupyter.\n!pip install pyjanitor==0.23.1\n\n"
] |
[
1
] |
[] |
[] |
[
"pyjanitor",
"python"
] |
stackoverflow_0074497801_pyjanitor_python.txt
|
Q:
How to group list items based on a specific condition?
I have this text:
>A1
KKKKKKKK
DDDDDDDD
>A2
FFFFFFFF
FFFFOOOO
DAA
>A3
OOOZDDD
KKAZAAA
A
When I split it and remove the line jumps, I get this list:
It gives me a list that looks like this:
['>A1', 'KKKKKKKK', 'DDDDDDDD', '>A2', 'FFFFFFFF', 'FFFFOOOO', 'DAA', '>A3', 'OOOZDDD', 'KKAZAAA', 'A']
I'm trying to merge all the strings between each part that starts with '>', such that it looks like:
['KKKKKKKKDDDDDDDD', 'FFFFFFFFFFFFOOOODAA', 'OOOZDDDKKAZAAAA']
What I have so far, but it doesn't do anything and I'm lost:
my_list = ['>A1', 'KKKKKKKK', 'DDDDDDDD', '>A2', 'FFFFFFFF', 'FFFFOOOO', 'DAA', '>A3', 'OOOZDDD', 'KKAZAAA', 'A']
result = []
for item in range(len(my_list)):
if my_list[item][0] == '>':
temp = ''
while my_list[item] != '>':
temp += my_list[item]
result.append(temp)
print(result)
A:
You can use itertools.groupby for the task:
from itertools import groupby
lst = [
">A1",
"KKKKKKKK",
"DDDDDDDD",
">A2",
"FFFFFFFF",
"FFFFOOOO",
"DAA",
">A3",
"OOOZDDD",
"KKAZAAA",
"A",
]
out = []
for k, g in groupby(lst, lambda s: s.startswith(">")):
if not k:
out.append("".join(g))
print(out)
Prints:
["KKKKKKKKDDDDDDDD", "FFFFFFFFFFFFOOOODAA", "OOOZDDDKKAZAAAA"]
A:
@Andrej has given a compact code for your problem, but I want to help you by pointing out some issues in your original code.
You have while in if, but when my_list[item] starts with '>', the inner while won't work. The correct thing is to add a else-statement to concatenate the following string.
You append a string temp to result at each iterative step, but temp is not a concatenated string. The correct time to append is when you meet '>' again.
After solving them, you may get something like this,
result = []
for item in range(len(my_list)):
if my_list[item][0] == '>':
if item != 0:
result.append(temp)
temp = ''
else:
temp += my_list[item]
if item != 0:
result.append(item)
print(result)
You can further simplify it.
Save list indexing by directly iterating over the list.
Save final repeated check by adding a sentinel.
result = []
concat_string = '' # just change a readable name
for string in my_list + ['>']: # iterate over list directly and add a sentinel
if string[0] == '>': # or string.startswith('>')
if concat_string:
result.append(concat_string)
concat_string = ''
else:
concat_string += string
print(result)
A:
Regex version:
data = """>A1
KKKKKKKK
DDDDDDDD
>A2
FFFFFFFF
FFFFOOOO
DAA
>A3
OOOZDDD
KKAZAAA
A"""
import re
patre = re.compile("^>.+\n",re.MULTILINE)
#split on `>xxx`
chunks = patre.split(data)
#remove whitespaces and newlines
blocks = [v.replace("\n","").strip() for v in chunks]
#get rid of leading trailing empty blocks
blocks = [v for v in blocks if v]
print(blocks)
output:
['KKKKKKKKDDDDDDDD', 'FFFFFFFFFFFFOOOODAA', 'OOOZDDDKKAZAAAA']
|
How to group list items based on a specific condition?
|
I have this text:
>A1
KKKKKKKK
DDDDDDDD
>A2
FFFFFFFF
FFFFOOOO
DAA
>A3
OOOZDDD
KKAZAAA
A
When I split it and remove the line jumps, I get this list:
It gives me a list that looks like this:
['>A1', 'KKKKKKKK', 'DDDDDDDD', '>A2', 'FFFFFFFF', 'FFFFOOOO', 'DAA', '>A3', 'OOOZDDD', 'KKAZAAA', 'A']
I'm trying to merge all the strings between each part that starts with '>', such that it looks like:
['KKKKKKKKDDDDDDDD', 'FFFFFFFFFFFFOOOODAA', 'OOOZDDDKKAZAAAA']
What I have so far, but it doesn't do anything and I'm lost:
my_list = ['>A1', 'KKKKKKKK', 'DDDDDDDD', '>A2', 'FFFFFFFF', 'FFFFOOOO', 'DAA', '>A3', 'OOOZDDD', 'KKAZAAA', 'A']
result = []
for item in range(len(my_list)):
if my_list[item][0] == '>':
temp = ''
while my_list[item] != '>':
temp += my_list[item]
result.append(temp)
print(result)
|
[
"You can use itertools.groupby for the task:\nfrom itertools import groupby\n\nlst = [\n \">A1\",\n \"KKKKKKKK\",\n \"DDDDDDDD\",\n \">A2\",\n \"FFFFFFFF\",\n \"FFFFOOOO\",\n \"DAA\",\n \">A3\",\n \"OOOZDDD\",\n \"KKAZAAA\",\n \"A\",\n]\n\nout = []\nfor k, g in groupby(lst, lambda s: s.startswith(\">\")):\n if not k:\n out.append(\"\".join(g))\n\nprint(out)\n\nPrints:\n[\"KKKKKKKKDDDDDDDD\", \"FFFFFFFFFFFFOOOODAA\", \"OOOZDDDKKAZAAAA\"]\n\n",
"@Andrej has given a compact code for your problem, but I want to help you by pointing out some issues in your original code.\n\nYou have while in if, but when my_list[item] starts with '>', the inner while won't work. The correct thing is to add a else-statement to concatenate the following string.\nYou append a string temp to result at each iterative step, but temp is not a concatenated string. The correct time to append is when you meet '>' again.\n\n\nAfter solving them, you may get something like this,\nresult = []\nfor item in range(len(my_list)):\n if my_list[item][0] == '>':\n if item != 0:\n result.append(temp)\n temp = ''\n else:\n temp += my_list[item]\nif item != 0:\n result.append(item)\nprint(result)\n\n\nYou can further simplify it.\n\nSave list indexing by directly iterating over the list.\nSave final repeated check by adding a sentinel.\n\nresult = []\nconcat_string = '' # just change a readable name\nfor string in my_list + ['>']: # iterate over list directly and add a sentinel\n if string[0] == '>': # or string.startswith('>')\n if concat_string:\n result.append(concat_string)\n concat_string = ''\n else:\n concat_string += string\nprint(result)\n\n",
"Regex version:\ndata = \"\"\">A1\nKKKKKKKK\nDDDDDDDD\n\n>A2\nFFFFFFFF\nFFFFOOOO\nDAA\n\n>A3\nOOOZDDD\nKKAZAAA\nA\"\"\"\n\nimport re\n\npatre = re.compile(\"^>.+\\n\",re.MULTILINE)\n#split on `>xxx`\nchunks = patre.split(data)\n#remove whitespaces and newlines\nblocks = [v.replace(\"\\n\",\"\").strip() for v in chunks]\n#get rid of leading trailing empty blocks\nblocks = [v for v in blocks if v]\n\nprint(blocks)\n\n\noutput:\n['KKKKKKKKDDDDDDDD', 'FFFFFFFFFFFFOOOODAA', 'OOOZDDDKKAZAAAA']\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"list",
"python",
"split"
] |
stackoverflow_0074497110_list_python_split.txt
|
Q:
Seven segment display in Tkinter
I am trying to create a GUI using Tkinter with Python 2.7. This must have a seven segment display or something similar to dynamically display values in accordance with a variable. Is there any way to create a seven segment display apart from a manual graphical design (that would slow down the entire system)?
A:
I don't know what you mean by 'maunal graphical design' but here is a single hex diget display designed to be easily upgraded to more digits. It will not slow the system noticeably.
'''Seven segment display of hex digits.'''
import tkinter as tk
root = tk.Tk()
screen = tk.Canvas(root)
screen.grid()
# Order 7 segments clockwise from top left, with crossbar last.
# Coordinates of each segment are (x0, y0, x1, y1)
# given as offsets from top left measured in segment lengths.
offsets = (
(0, 0, 1, 0), # top
(1, 0, 1, 1), # upper right
(1, 1, 1, 2), # lower right
(0, 2, 1, 2), # bottom
(0, 1, 0, 2), # lower left
(0, 0, 0, 1), # upper left
(0, 1, 1, 1), # middle
)
# Segments used for each digit; 0, 1 = off, on.
digits = (
(1, 1, 1, 1, 1, 1, 0), # 0
(0, 1, 1, 0, 0, 0, 0), # 1
(1, 1, 0, 1, 1, 0, 1), # 2
(1, 1, 1, 1, 0, 0, 1), # 3
(0, 1, 1, 0, 0, 1, 1), # 4
(1, 0, 1, 1, 0, 1, 1), # 5
(1, 0, 1, 1, 1, 1, 1), # 6
(1, 1, 1, 0, 0, 0, 0), # 7
(1, 1, 1, 1, 1, 1, 1), # 8
(1, 1, 1, 1, 0, 1, 1), # 9
(1, 1, 1, 0, 1, 1, 1), # 10=A
(0, 0, 1, 1, 1, 1, 1), # 11=b
(1, 0, 0, 1, 1, 1, 0), # 12=C
(0, 1, 1, 1, 1, 0, 1), # 13=d
(1, 0, 0, 1, 1, 1, 1), # 14=E
(1, 0, 0, 0, 1, 1, 1), # 15=F
)
class Digit:
def __init__(self, canvas, *, x=10, y=10, length=20, width=3):
self.canvas = canvas
l = length
self.segs = []
for x0, y0, x1, y1 in offsets:
self.segs.append(canvas.create_line(
x + x0*l, y + y0*l, x + x1*l, y + y1*l,
width=width, state = 'hidden'))
def show(self, num):
for iid, on in zip(self.segs, digits[num]):
self.canvas.itemconfigure(iid, state = 'normal' if on else 'hidden')
dig = Digit(screen)
n = 0
def update():
global n
dig.show(n)
n = (n+1) % 16
root.after(1000, update)
root.after(1000, update)
root.mainloop()
A:
You can just use a Sevent Segment Font to display any number you want.
Label(self, width=8, text="123", font=("Seven Segment",24), justify=LEFT, anchor="w", fg="red")
|
Seven segment display in Tkinter
|
I am trying to create a GUI using Tkinter with Python 2.7. This must have a seven segment display or something similar to dynamically display values in accordance with a variable. Is there any way to create a seven segment display apart from a manual graphical design (that would slow down the entire system)?
|
[
"I don't know what you mean by 'maunal graphical design' but here is a single hex diget display designed to be easily upgraded to more digits. It will not slow the system noticeably.\n'''Seven segment display of hex digits.'''\nimport tkinter as tk\nroot = tk.Tk()\nscreen = tk.Canvas(root)\nscreen.grid()\n\n# Order 7 segments clockwise from top left, with crossbar last.\n# Coordinates of each segment are (x0, y0, x1, y1) \n# given as offsets from top left measured in segment lengths.\noffsets = (\n (0, 0, 1, 0), # top\n (1, 0, 1, 1), # upper right\n (1, 1, 1, 2), # lower right\n (0, 2, 1, 2), # bottom\n (0, 1, 0, 2), # lower left\n (0, 0, 0, 1), # upper left\n (0, 1, 1, 1), # middle\n)\n# Segments used for each digit; 0, 1 = off, on.\ndigits = (\n (1, 1, 1, 1, 1, 1, 0), # 0\n (0, 1, 1, 0, 0, 0, 0), # 1\n (1, 1, 0, 1, 1, 0, 1), # 2\n (1, 1, 1, 1, 0, 0, 1), # 3\n (0, 1, 1, 0, 0, 1, 1), # 4\n (1, 0, 1, 1, 0, 1, 1), # 5\n (1, 0, 1, 1, 1, 1, 1), # 6\n (1, 1, 1, 0, 0, 0, 0), # 7\n (1, 1, 1, 1, 1, 1, 1), # 8\n (1, 1, 1, 1, 0, 1, 1), # 9\n (1, 1, 1, 0, 1, 1, 1), # 10=A\n (0, 0, 1, 1, 1, 1, 1), # 11=b\n (1, 0, 0, 1, 1, 1, 0), # 12=C\n (0, 1, 1, 1, 1, 0, 1), # 13=d\n (1, 0, 0, 1, 1, 1, 1), # 14=E\n (1, 0, 0, 0, 1, 1, 1), # 15=F\n)\n\n\nclass Digit:\n def __init__(self, canvas, *, x=10, y=10, length=20, width=3):\n self.canvas = canvas\n l = length\n self.segs = []\n for x0, y0, x1, y1 in offsets:\n self.segs.append(canvas.create_line(\n x + x0*l, y + y0*l, x + x1*l, y + y1*l,\n width=width, state = 'hidden'))\n def show(self, num):\n for iid, on in zip(self.segs, digits[num]):\n self.canvas.itemconfigure(iid, state = 'normal' if on else 'hidden')\n\n\n\ndig = Digit(screen)\nn = 0\ndef update():\n global n\n dig.show(n)\n n = (n+1) % 16\n root.after(1000, update)\nroot.after(1000, update)\nroot.mainloop()\n\n",
"You can just use a Sevent Segment Font to display any number you want.\nLabel(self, width=8, text=\"123\", font=(\"Seven Segment\",24), justify=LEFT, anchor=\"w\", fg=\"red\")\n\n"
] |
[
9,
0
] |
[] |
[] |
[
"python",
"python_2.7",
"tkinter"
] |
stackoverflow_0035551962_python_python_2.7_tkinter.txt
|
Q:
auto remove value or string from list if it start with
how can i remove the similar value from list if it start with and keep
one of the value if it has alot of
for example this is my code
list_ph = ['8002378990','8001378990','8202378990','8002378920','8002375990','8002378990','8001378890','8202398990']
so this value sould return 3 value when it will remove the value
if i[:5]
so the result of it will be something like this
['8002378990','8001378990','8202378990']
without i give it specific value or any thing just sub value[:5]
A:
Here is how I would approach this problem.
I would first create two empty lists, one for comparing the first five digits, and the other to save your result, say
first_five = []
res = []
Now, I would loop through all the entries in your list_ph and add the number to res if the first five digits are not already stored in first_five
i.e.
for ph in list_ph:
if ph[:5] not in first_five:
first_five.append(ph[:5])
res.append(ph)
All of your target numbers should be stored in res
|
auto remove value or string from list if it start with
|
how can i remove the similar value from list if it start with and keep
one of the value if it has alot of
for example this is my code
list_ph = ['8002378990','8001378990','8202378990','8002378920','8002375990','8002378990','8001378890','8202398990']
so this value sould return 3 value when it will remove the value
if i[:5]
so the result of it will be something like this
['8002378990','8001378990','8202378990']
without i give it specific value or any thing just sub value[:5]
|
[
"Here is how I would approach this problem.\nI would first create two empty lists, one for comparing the first five digits, and the other to save your result, say\nfirst_five = []\nres = []\n\nNow, I would loop through all the entries in your list_ph and add the number to res if the first five digits are not already stored in first_five\ni.e.\nfor ph in list_ph:\n if ph[:5] not in first_five:\n first_five.append(ph[:5])\n res.append(ph)\n\nAll of your target numbers should be stored in res\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074497888_python_python_3.x.txt
|
Q:
downloading CSV file in python using pandas
I am trying to download a csv file to python. For some reason I can not do it. I suppose I need to add an additional argument to read_csv?
import pandas as pd
url = "https://raw.githubusercontent.com/UofGAnalyticsData/"\
"DPIP/main/assesment_datasets/assessment3/starwars.csv"
df = pd.read_csv(url)
A:
The code you attempt is downloading the content from the url and pasting it in the data frame named 'df'.
You need to save the output csv by using the following line. You will find the output file in the same directory where the python script is saved.
import pandas as pd
url = "https://raw.githubusercontent.com/UofGAnalyticsData/"\
"DPIP/main/assesment_datasets/assessment3/starwars.csv"
df = pd.read_csv(url)
df.to_csv('output.csv')
|
downloading CSV file in python using pandas
|
I am trying to download a csv file to python. For some reason I can not do it. I suppose I need to add an additional argument to read_csv?
import pandas as pd
url = "https://raw.githubusercontent.com/UofGAnalyticsData/"\
"DPIP/main/assesment_datasets/assessment3/starwars.csv"
df = pd.read_csv(url)
|
[
"The code you attempt is downloading the content from the url and pasting it in the data frame named 'df'.\nYou need to save the output csv by using the following line. You will find the output file in the same directory where the python script is saved.\nimport pandas as pd\n\nurl = \"https://raw.githubusercontent.com/UofGAnalyticsData/\"\\\n \"DPIP/main/assesment_datasets/assessment3/starwars.csv\"\n\ndf = pd.read_csv(url)\ndf.to_csv('output.csv')\n\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074492049_pandas_python.txt
|
Q:
Using pycryptodome to decrypt encrypted data
I'm new to encryption/decryption, but I have sensitive data that I need to store as encrypted data. Our ETL has a built in encryption process which outputs the following
{
"data":{
"transformation":"AES/GCM/noPadding",
"iv":"jlemHiOD8uiyMsqY",
"type":"JSON",
"ciphertext":"TOtsmTYG1jKCZXewFNPBk5xWf+q4AO8OSZPoYw==",
"key_params":{
"symmetric":{
"key_algorithm":"AES"
}
}
}
}
From here, I'd like to use pycryptodome to decrypt the data when I need to consume the data. I am trying to run the following python script to decrypt but am running into some errors. I think it has to do with how the data is formatted?
import pandas as pd
from Crypto.Cipher import AES
test_encrypted_value = TOtsmTYG1jKCZXewFNPBk5xWf+q4AO8OSZPoYw==
aes_iv = 'jIemHiOD8uiyMsqY'
aes_key = '4E645267556B586E3272357538782F41'
cipher = AES.new(aes_key, AES.MODE_GCM, aes_iv)
error - TypeError: Nonce must be bytes, bytearray or memoryview
If I remove the IV, I also get an error on the key passed. Which leads me to think I am passing the wrong data type/format.
error - TypeError: Object type <class 'str'> cannot be passed to C code
UPDATE
Per the responses, I updated my code to transform data format. Additionally, I changed my example and saved the expected value. I am expecting the decrypted value to be 158100.
import pandas as pd
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import codecs
import base64
test_encrypted_value = 'SUXiDF6Dgtc8y3eY8Euqi/IYbSlQquLJAUKmZw=='
aes_iv = 'lMF2Jrruo9rR57Uy'
aes_key = '4E645267556B586E3272357538782F41'
byte_key = codecs.decode(aes_key, 'hex_codec')
base64_iv = base64.b64decode(aes_iv)
base64_encrypted_value = base64.b64decode(test_encrypted_value)
cipher = AES.new(byte_key, AES.MODE_GCM, base64_iv)
plaintext = cipher.decrypt(ciphertext)
print(plaintext.decode())
I am now getting the below error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 1: invalid start byte
For what it's worth, encryption is through snaplogic 'Encrypt Field' found here - https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1438346/Encrypt+Field
I am also generating the AES key at the following link with the 128-bit and HEX option set - https://www.allkeysgenerator.com/Random/Security-Encryption-Key-Generator.aspx
A:
You need to pass the data in bytes format. Your aes_iv and test_encrypted_value is in the base64 format, while your aes_key is in the hex format. In order to use it, you must first convert those to bytes.
byte_key = codecs.decode(aes_key, 'hex_codec')
base64_iv = base64.b64decode(aes_iv)
base64_encrypted_value = base64.b64decode(test_encrypted_value)
|
Using pycryptodome to decrypt encrypted data
|
I'm new to encryption/decryption, but I have sensitive data that I need to store as encrypted data. Our ETL has a built in encryption process which outputs the following
{
"data":{
"transformation":"AES/GCM/noPadding",
"iv":"jlemHiOD8uiyMsqY",
"type":"JSON",
"ciphertext":"TOtsmTYG1jKCZXewFNPBk5xWf+q4AO8OSZPoYw==",
"key_params":{
"symmetric":{
"key_algorithm":"AES"
}
}
}
}
From here, I'd like to use pycryptodome to decrypt the data when I need to consume the data. I am trying to run the following python script to decrypt but am running into some errors. I think it has to do with how the data is formatted?
import pandas as pd
from Crypto.Cipher import AES
test_encrypted_value = TOtsmTYG1jKCZXewFNPBk5xWf+q4AO8OSZPoYw==
aes_iv = 'jIemHiOD8uiyMsqY'
aes_key = '4E645267556B586E3272357538782F41'
cipher = AES.new(aes_key, AES.MODE_GCM, aes_iv)
error - TypeError: Nonce must be bytes, bytearray or memoryview
If I remove the IV, I also get an error on the key passed. Which leads me to think I am passing the wrong data type/format.
error - TypeError: Object type <class 'str'> cannot be passed to C code
UPDATE
Per the responses, I updated my code to transform data format. Additionally, I changed my example and saved the expected value. I am expecting the decrypted value to be 158100.
import pandas as pd
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import codecs
import base64
test_encrypted_value = 'SUXiDF6Dgtc8y3eY8Euqi/IYbSlQquLJAUKmZw=='
aes_iv = 'lMF2Jrruo9rR57Uy'
aes_key = '4E645267556B586E3272357538782F41'
byte_key = codecs.decode(aes_key, 'hex_codec')
base64_iv = base64.b64decode(aes_iv)
base64_encrypted_value = base64.b64decode(test_encrypted_value)
cipher = AES.new(byte_key, AES.MODE_GCM, base64_iv)
plaintext = cipher.decrypt(ciphertext)
print(plaintext.decode())
I am now getting the below error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 1: invalid start byte
For what it's worth, encryption is through snaplogic 'Encrypt Field' found here - https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1438346/Encrypt+Field
I am also generating the AES key at the following link with the 128-bit and HEX option set - https://www.allkeysgenerator.com/Random/Security-Encryption-Key-Generator.aspx
|
[
"You need to pass the data in bytes format. Your aes_iv and test_encrypted_value is in the base64 format, while your aes_key is in the hex format. In order to use it, you must first convert those to bytes.\nbyte_key = codecs.decode(aes_key, 'hex_codec')\nbase64_iv = base64.b64decode(aes_iv)\nbase64_encrypted_value = base64.b64decode(test_encrypted_value)\n\n"
] |
[
1
] |
[] |
[] |
[
"aes",
"encryption",
"pycryptodome",
"python"
] |
stackoverflow_0074497776_aes_encryption_pycryptodome_python.txt
|
Q:
Capturing columns with similar patterns with Python regex
I'm scraping a pdf using regex and Python. The patterns repeat through each column. I don't understand how to target each column of information separately.
Text string:
2000 2001 2002 2003\n
14,756 10,922 9,745 12,861\n
9,882 11,568 8,176 10,483\n
13,925 10,724 10,032 8,927\n
I need to return the data by year like:
[('2000', '14,756', '9,882', '13,925'),
('2001', '10,922', '11,568', '10,742'),
('2002', '9,745', '8,176', '10,032'),
('2003', '12,861', '10,483', '8,927')]
once I have the regex, I understand how to pull it from the page and put it into a df. I'm just not understanding how to target the columns separately. I just capture everything all at once.
A:
I am afraid it is impossible to capture columns, but you can combine regex with matching the groups of the columns and transpose with zip.
(?:^|\n)([\d,]+)\s([\d,]+)\s([\d,]+)\s([\d,]+)(?:$|\n)
See how this regex works.
import re
text = """2000 2001 2002 2003
14,756 10,922 9,745 12,861
9,882 11,568 8,176 10,483
13,925 10,724 10,032 8,927"""
pattern = r"(?:^|\n)([\d,]+)\s([\d,]+)\s([\d,]+)\s([\d,]+)(?:$|\n)"
grouped = re.findall(pattern, text, flags=re.M)
columns = list(zip(*grouped)) # the expected result
|
Capturing columns with similar patterns with Python regex
|
I'm scraping a pdf using regex and Python. The patterns repeat through each column. I don't understand how to target each column of information separately.
Text string:
2000 2001 2002 2003\n
14,756 10,922 9,745 12,861\n
9,882 11,568 8,176 10,483\n
13,925 10,724 10,032 8,927\n
I need to return the data by year like:
[('2000', '14,756', '9,882', '13,925'),
('2001', '10,922', '11,568', '10,742'),
('2002', '9,745', '8,176', '10,032'),
('2003', '12,861', '10,483', '8,927')]
once I have the regex, I understand how to pull it from the page and put it into a df. I'm just not understanding how to target the columns separately. I just capture everything all at once.
|
[
"I am afraid it is impossible to capture columns, but you can combine regex with matching the groups of the columns and transpose with zip.\n(?:^|\\n)([\\d,]+)\\s([\\d,]+)\\s([\\d,]+)\\s([\\d,]+)(?:$|\\n)\n\nSee how this regex works.\nimport re\n\ntext = \"\"\"2000 2001 2002 2003\n14,756 10,922 9,745 12,861\n9,882 11,568 8,176 10,483\n13,925 10,724 10,032 8,927\"\"\"\n\npattern = r\"(?:^|\\n)([\\d,]+)\\s([\\d,]+)\\s([\\d,]+)\\s([\\d,]+)(?:$|\\n)\"\ngrouped = re.findall(pattern, text, flags=re.M)\ncolumns = list(zip(*grouped)) # the expected result\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"web_scraping"
] |
stackoverflow_0074497037_python_web_scraping.txt
|
Q:
Why does my Pygame window flicker when animating objects?
So my pygame window just won't stop flickering. I know if only one item is in snake.snakearray, it won't flicker.
#class for the array
class snake:
snakearray = [[ScreenConfigs.width / 2,ScreenConfigs.height / 2],[ScreenConfigs.width / 2,ScreenConfigs.height / 2]]
direction = "up"
increment = 0.1
#loop to draw the snake
while Running:
for snakeBit in snake.snakearray:
pygame.draw.rect(display,"black",(0,0,ScreenConfigs.width,ScreenConfigs.height))
pygame.draw.rect(display,"white",(snakeBit[0],snakeBit[1],30,30))
pygame.display.flip()
I tried putting the pygame.display.flip() outside of the loop and it only drew that last rectangle. (because when you call pygame.draw.rect, it disregards the last one drew)
A:
Multiple calls to pygame.display.update() or pygame.display.flip() causes flickering. Updating the display once at the end of the application loop is sufficient. But you also need to clear the display only once before drawing the scene:
while Running:
# [...]
# clear display
pygame.draw.rect(display,"black", (0,0,ScreenConfigs.width,ScreenConfigs.height))
# draw scene
for snakeBit in snake.snakearray:
pygame.draw.rect(display,"white",(snakeBit[0],snakeBit[1],30,30))
# update display
pygame.display.flip()
Clearing the display can also be done with fill:
while Running:
# [...]
# clear display
display.fill("black")
# draw scene
for snakeBit in snake.snakearray:
pygame.draw.rect(display,"white",(snakeBit[0],snakeBit[1],30,30))
# update display
pygame.display.flip()
Each object in the scene is drawn to the pygame.Surface object associated with the display. To create animated objects, the entire scene must be redrawn in each frame. Therefore, the display must be cleared at the beginning of each frame in the application loop. If you draw on the Surface associated to the PyGame display, this is not immediately visible in the display. The changes become visible, when the display is updated with either pygame.display.update() or pygame.display.flip().
|
Why does my Pygame window flicker when animating objects?
|
So my pygame window just won't stop flickering. I know if only one item is in snake.snakearray, it won't flicker.
#class for the array
class snake:
snakearray = [[ScreenConfigs.width / 2,ScreenConfigs.height / 2],[ScreenConfigs.width / 2,ScreenConfigs.height / 2]]
direction = "up"
increment = 0.1
#loop to draw the snake
while Running:
for snakeBit in snake.snakearray:
pygame.draw.rect(display,"black",(0,0,ScreenConfigs.width,ScreenConfigs.height))
pygame.draw.rect(display,"white",(snakeBit[0],snakeBit[1],30,30))
pygame.display.flip()
I tried putting the pygame.display.flip() outside of the loop and it only drew that last rectangle. (because when you call pygame.draw.rect, it disregards the last one drew)
|
[
"Multiple calls to pygame.display.update() or pygame.display.flip() causes flickering. Updating the display once at the end of the application loop is sufficient. But you also need to clear the display only once before drawing the scene:\nwhile Running:\n # [...]\n\n # clear display \n pygame.draw.rect(display,\"black\", (0,0,ScreenConfigs.width,ScreenConfigs.height))\n\n # draw scene\n for snakeBit in snake.snakearray:\n pygame.draw.rect(display,\"white\",(snakeBit[0],snakeBit[1],30,30))\n \n # update display\n pygame.display.flip()\n\nClearing the display can also be done with fill:\nwhile Running:\n # [...]\n\n # clear display \n display.fill(\"black\")\n\n # draw scene\n for snakeBit in snake.snakearray:\n pygame.draw.rect(display,\"white\",(snakeBit[0],snakeBit[1],30,30))\n \n # update display\n pygame.display.flip()\n\n\nEach object in the scene is drawn to the pygame.Surface object associated with the display. To create animated objects, the entire scene must be redrawn in each frame. Therefore, the display must be cleared at the beginning of each frame in the application loop. If you draw on the Surface associated to the PyGame display, this is not immediately visible in the display. The changes become visible, when the display is updated with either pygame.display.update() or pygame.display.flip().\n"
] |
[
3
] |
[] |
[] |
[
"flicker",
"pygame",
"python",
"python_3.x"
] |
stackoverflow_0074496592_flicker_pygame_python_python_3.x.txt
|
Q:
ValueError: Could not find matching concrete function to call loaded from the SavedModel
I am trying to build a model for crop identification and keep getting this error:
import tensorflow as tf
import tensorflow_hub as hub
#Read crop details
import pandas as pd
crop_details_csv = pd.read_excel('/content/drive/MyDrive/Crop Identification/Crop_details.xlsx')
crop_details_csv.head()
#Get imamges filepaths
filename = ['drive/MyDrive/Crop Identification/Train2/' + fname for fname in crop_details_csv['path']]
import numpy as np
labels = crop_details_csv['croplabel']
labels=np.array(labels)
#if len(labels)==len(filename):
#print('Yes')
#else:
#print('NO')
unique_labels = np.unique(labels)
unique_labels
boolean_labels = [label == unique_labels for label in labels]#turn labels to numbers
#Split our data and creating Validation set
x = filename
y = boolean_labels
#Get validation set
from sklearn.model_selection import train_test_split
x_train,x_val,y_train,y_val=train_test_split(x,y,test_size=0.2,random_state=42)
#Turn Images to tensors
image_size=224
def preprocess_image(image_path,image_size=image_size):
#read an image file
image= tf.io.read_file(image_path)
#turn image into numerical tensors with RGB
image = tf.image.decode_jpeg(image,channels=3)
#convert color values from 0-255 to 0-1 #Normaliization
image = tf.image.convert_image_dtype(image,tf.float32)
#resize image to 224,224
image = tf.image.resize(image,size=[image_size,image_size])
return image
#Turn Data into batches
#Returns tuple (image,label)
def get_image_label(image_path,label):
image = preprocess_image(image_path)
return image,label
Batch_size=32
def create_batches(x,y=None,batch_size=Batch_size,valid_data=False,test_data=False):
if test_data:#test data has no labels
data= tf.data.Dataset.from_tensor_slices((tf.constant(x)))#no labels
data_batch = data.map(preprocess_image).batch(Batch_size)
return data_batch
elif valid_data:#no shuffling for valid data
data= tf.data.Dataset.from_tensor_slices((tf.constant(x),(tf.constant(y))))
data_batch = data.map(get_image_label).batch(Batch_size)
return data_batch
else:
data= tf.data.Dataset.from_tensor_slices((tf.constant(x),(tf.constant(y))))
data= data.shuffle(buffer_size=len(x))#shuffle for training data
data= data.map(get_image_label)
data_batch=data.batch(Batch_size)
return data_batch
train_data=create_batches(x_train,y_train)
val_data=create_batches(x_val,y_val,valid_data=True)
input_shape=[None,image_size,image_size,3]#batch ,height ,width , color channels
output_shape= len(unique_labels)
model_URL = "https://tfhub.dev/google/imagenet/mobilenet_v2_035_128/classification/5"
def create_model(input_shape=input_shape,output_shape=output_shape,model_URL=model_URL):
#model layers setup
model = tf.keras.Sequential([hub.KerasLayer(model_URL),#input layer
tf.keras.layers.Dense(units=output_shape,activation='softmax')])#output layer
#compile model
model.compile(loss=tf.keras.losses.CategoricalCrossentropy(),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
#Build model
model.build(input_shape)
return model
model = create_model()
-----------------------------------------------------------------
----------
ValueError Traceback (most recent call last)
<ipython-input-14-0fd4f47c95c0> in <module>()
----> 1 model = create_model()
2 model.summary()
5 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
697 except Exception as e: # pylint:disable=broad-except
698 if hasattr(e, 'ag_error_metadata'):
--> 699 raise e.ag_error_metadata.to_exception(e)
700 else:
701 raise
ValueError: Exception encountered when calling layer "keras_layer" (type KerasLayer).
in user code:
File "/usr/local/lib/python3.7/dist-packages/tensorflow_hub/keras_layer.py", line 237, in call *
result = smart_cond.smart_cond(training,
ValueError: Could not find matching concrete function to call loaded from the SavedModel. Got:
Positional arguments (4 total):
* Tensor("inputs:0", shape=(224, 224, 3), dtype=float32)
* False
* False
* 0.99
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* True
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 2:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* True
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 3:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* False
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 4:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* False
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Call arguments received:
• inputs=tf.Tensor(shape=(224, 224, 3), dtype=float32)
• training=None
A:
I was able to replicate the error using Agriculture crop images dataset.
You must change the image size from 224 to 128 because the mobilenet_v2_035_128 model takes an input size of (128, 128, 3).
Kindly refer to this gist for working code. Thank you!
A:
The error means the model's input shape should be (None, 128, 128, 3); but you give (224, 224, 3).
First, you should input the right data with shape (128, 128, 3), then you also need to add an outer sample num dimension, that is (1,128, 128, 3)
|
ValueError: Could not find matching concrete function to call loaded from the SavedModel
|
I am trying to build a model for crop identification and keep getting this error:
import tensorflow as tf
import tensorflow_hub as hub
#Read crop details
import pandas as pd
crop_details_csv = pd.read_excel('/content/drive/MyDrive/Crop Identification/Crop_details.xlsx')
crop_details_csv.head()
#Get imamges filepaths
filename = ['drive/MyDrive/Crop Identification/Train2/' + fname for fname in crop_details_csv['path']]
import numpy as np
labels = crop_details_csv['croplabel']
labels=np.array(labels)
#if len(labels)==len(filename):
#print('Yes')
#else:
#print('NO')
unique_labels = np.unique(labels)
unique_labels
boolean_labels = [label == unique_labels for label in labels]#turn labels to numbers
#Split our data and creating Validation set
x = filename
y = boolean_labels
#Get validation set
from sklearn.model_selection import train_test_split
x_train,x_val,y_train,y_val=train_test_split(x,y,test_size=0.2,random_state=42)
#Turn Images to tensors
image_size=224
def preprocess_image(image_path,image_size=image_size):
#read an image file
image= tf.io.read_file(image_path)
#turn image into numerical tensors with RGB
image = tf.image.decode_jpeg(image,channels=3)
#convert color values from 0-255 to 0-1 #Normaliization
image = tf.image.convert_image_dtype(image,tf.float32)
#resize image to 224,224
image = tf.image.resize(image,size=[image_size,image_size])
return image
#Turn Data into batches
#Returns tuple (image,label)
def get_image_label(image_path,label):
image = preprocess_image(image_path)
return image,label
Batch_size=32
def create_batches(x,y=None,batch_size=Batch_size,valid_data=False,test_data=False):
if test_data:#test data has no labels
data= tf.data.Dataset.from_tensor_slices((tf.constant(x)))#no labels
data_batch = data.map(preprocess_image).batch(Batch_size)
return data_batch
elif valid_data:#no shuffling for valid data
data= tf.data.Dataset.from_tensor_slices((tf.constant(x),(tf.constant(y))))
data_batch = data.map(get_image_label).batch(Batch_size)
return data_batch
else:
data= tf.data.Dataset.from_tensor_slices((tf.constant(x),(tf.constant(y))))
data= data.shuffle(buffer_size=len(x))#shuffle for training data
data= data.map(get_image_label)
data_batch=data.batch(Batch_size)
return data_batch
train_data=create_batches(x_train,y_train)
val_data=create_batches(x_val,y_val,valid_data=True)
input_shape=[None,image_size,image_size,3]#batch ,height ,width , color channels
output_shape= len(unique_labels)
model_URL = "https://tfhub.dev/google/imagenet/mobilenet_v2_035_128/classification/5"
def create_model(input_shape=input_shape,output_shape=output_shape,model_URL=model_URL):
#model layers setup
model = tf.keras.Sequential([hub.KerasLayer(model_URL),#input layer
tf.keras.layers.Dense(units=output_shape,activation='softmax')])#output layer
#compile model
model.compile(loss=tf.keras.losses.CategoricalCrossentropy(),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
#Build model
model.build(input_shape)
return model
model = create_model()
-----------------------------------------------------------------
----------
ValueError Traceback (most recent call last)
<ipython-input-14-0fd4f47c95c0> in <module>()
----> 1 model = create_model()
2 model.summary()
5 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
697 except Exception as e: # pylint:disable=broad-except
698 if hasattr(e, 'ag_error_metadata'):
--> 699 raise e.ag_error_metadata.to_exception(e)
700 else:
701 raise
ValueError: Exception encountered when calling layer "keras_layer" (type KerasLayer).
in user code:
File "/usr/local/lib/python3.7/dist-packages/tensorflow_hub/keras_layer.py", line 237, in call *
result = smart_cond.smart_cond(training,
ValueError: Could not find matching concrete function to call loaded from the SavedModel. Got:
Positional arguments (4 total):
* Tensor("inputs:0", shape=(224, 224, 3), dtype=float32)
* False
* False
* 0.99
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* True
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 2:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* True
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 3:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* False
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 4:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* False
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Call arguments received:
• inputs=tf.Tensor(shape=(224, 224, 3), dtype=float32)
• training=None
|
[
"I was able to replicate the error using Agriculture crop images dataset.\nYou must change the image size from 224 to 128 because the mobilenet_v2_035_128 model takes an input size of (128, 128, 3).\nKindly refer to this gist for working code. Thank you!\n",
"The error means the model's input shape should be (None, 128, 128, 3); but you give (224, 224, 3).\nFirst, you should input the right data with shape (128, 128, 3), then you also need to add an outer sample num dimension, that is (1,128, 128, 3)\n"
] |
[
0,
0
] |
[] |
[] |
[
"classification",
"keras",
"machine_learning",
"python",
"tensorflow"
] |
stackoverflow_0070706671_classification_keras_machine_learning_python_tensorflow.txt
|
Q:
How to copy one class function variable value in another class window in pyqt5
this is the small part of source code of the project
i want to copy user variable from userlogin class to usermain class
tried to make a userlogin object in usermain class but no working
from ftplib import parse150
import time
import sys
import sqlite3
from PyQt5 import QtWidgets
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QDialog,QApplication,QStackedWidget ,QMainWindow ,QWidget
conn =sqlite3.connect(r"C:\\Users\\Admin\\Desktop\\courier\\courier.db")
cur = conn.cursor()
class userlogin(QMainWindow):
def _init_(self):
super(userlogin,self)._init_()
loadUi(r"C:\\Users\\Admin\\Desktop\\courier\\userlogin.ui",self)
user = self.username.text()
self.upass.setEchoMode(QtWidgets.QLineEdit.Password)
self.login.clicked.connect(self.loginfunction)
def loginfunction(self):
\#---- WANT TO COPY THE USER VARIABLE IN USERMAIN CLASS----
user = self.username.text()
password = self.upass.text()
class usermain(QMainWindow):
def _init_(self):
super(usermain,self)._init_()
loadUi(r"C:\\Users\\Admin\\Desktop\\courier\\usermain.ui",self)
\#--------COPY THE VALUE OF USER VARIABLE HERE
\#--------------main---------------------
app = QApplication(sys.argv)
welcome=welcomescreen()
widget = QStackedWidget()
widget.addWidget(welcome)
widget.setFixedHeight(750)
widget.setFixedWidth(1000)
widget.show()
try:
sys.exit(app.exec\_())
except:
conn.close()
print("existing")
Tried to derived class but not getting results
|
How to copy one class function variable value in another class window in pyqt5
|
this is the small part of source code of the project
i want to copy user variable from userlogin class to usermain class
tried to make a userlogin object in usermain class but no working
from ftplib import parse150
import time
import sys
import sqlite3
from PyQt5 import QtWidgets
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QDialog,QApplication,QStackedWidget ,QMainWindow ,QWidget
conn =sqlite3.connect(r"C:\\Users\\Admin\\Desktop\\courier\\courier.db")
cur = conn.cursor()
class userlogin(QMainWindow):
def _init_(self):
super(userlogin,self)._init_()
loadUi(r"C:\\Users\\Admin\\Desktop\\courier\\userlogin.ui",self)
user = self.username.text()
self.upass.setEchoMode(QtWidgets.QLineEdit.Password)
self.login.clicked.connect(self.loginfunction)
def loginfunction(self):
\#---- WANT TO COPY THE USER VARIABLE IN USERMAIN CLASS----
user = self.username.text()
password = self.upass.text()
class usermain(QMainWindow):
def _init_(self):
super(usermain,self)._init_()
loadUi(r"C:\\Users\\Admin\\Desktop\\courier\\usermain.ui",self)
\#--------COPY THE VALUE OF USER VARIABLE HERE
\#--------------main---------------------
app = QApplication(sys.argv)
welcome=welcomescreen()
widget = QStackedWidget()
widget.addWidget(welcome)
widget.setFixedHeight(750)
widget.setFixedWidth(1000)
widget.show()
try:
sys.exit(app.exec\_())
except:
conn.close()
print("existing")
Tried to derived class but not getting results
|
[] |
[] |
[
"I think signal/slot helps you, using signal and slot you can connect objects to each other and any value you want can transfer\n"
] |
[
-2
] |
[
"pyqt5",
"python"
] |
stackoverflow_0074497829_pyqt5_python.txt
|
Q:
How can I code a timer to run simultaneously with my code?
import time
import threading
import random
#declare variables and constant
guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"]
nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]
wronganswers = ["Wrong answer...", "Nope", "Try again next time.", "Wrong answer. Nice effort"]
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
guess_no = 0
score = 0
def countdown():
global my_timer
my_timer = 5
for i in range(7):
randomelement = random.choice(guessingelement)
guessingelement.remove(randomelement)
time.sleep(1)
for x in range(5):
my_timer = my_timer - 1
time.sleep(1)
print("Out of time.Haiya!")
countdown_thread = threading.Thread(target = countdown)
countdown_thread.start()
while my_timer > 0:
#tips of the element
if randomelement == "Hydrogen" and not out_of_guesses:
print("Tip 1: It is the most flammable of all the known substances.")
print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.")
print("Tip 3: It reacts with oxygen to form water.")
#test the number of tries so that it doesn't exceed 3 times if answer is wrong
while guess != randomelement and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True
#add score, praise when answer is correct and encourage when answer is wrong for 3 times
if out_of_guesses:
print(random.choice(wronganswers))
print(f"{randomelement} was the element.")
else:
print(random.choice(nicephrases), ", YOU GET IT!")
score = score + 1
if randomelement == "Magnesium" and not out_of_guesses:
print("Tip 1: It has the atomic number of 12.")
print("Tip 2: It's oxide can be extracted into free metal through electrolysis.")
print("Tip 3: It is a type of metal.")
procedure same as the first question. And so on with my questions.
However, it shows that my_timer variable is not defined. The process that I would want it to undergo is that it will countdown for 5 seconds for every questions, and when the timer reaches 0, it will print out of time and proceed to the next question.
A:
In the code you've shown, you haven't assigned a value to my_timer.
my_timer = 5
By assigning the global within countdown() you've merely allowed countdown to change the value of my_timer. You still need to assign a value.
|
How can I code a timer to run simultaneously with my code?
|
import time
import threading
import random
#declare variables and constant
guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"]
nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]
wronganswers = ["Wrong answer...", "Nope", "Try again next time.", "Wrong answer. Nice effort"]
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
guess_no = 0
score = 0
def countdown():
global my_timer
my_timer = 5
for i in range(7):
randomelement = random.choice(guessingelement)
guessingelement.remove(randomelement)
time.sleep(1)
for x in range(5):
my_timer = my_timer - 1
time.sleep(1)
print("Out of time.Haiya!")
countdown_thread = threading.Thread(target = countdown)
countdown_thread.start()
while my_timer > 0:
#tips of the element
if randomelement == "Hydrogen" and not out_of_guesses:
print("Tip 1: It is the most flammable of all the known substances.")
print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.")
print("Tip 3: It reacts with oxygen to form water.")
#test the number of tries so that it doesn't exceed 3 times if answer is wrong
while guess != randomelement and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True
#add score, praise when answer is correct and encourage when answer is wrong for 3 times
if out_of_guesses:
print(random.choice(wronganswers))
print(f"{randomelement} was the element.")
else:
print(random.choice(nicephrases), ", YOU GET IT!")
score = score + 1
if randomelement == "Magnesium" and not out_of_guesses:
print("Tip 1: It has the atomic number of 12.")
print("Tip 2: It's oxide can be extracted into free metal through electrolysis.")
print("Tip 3: It is a type of metal.")
procedure same as the first question. And so on with my questions.
However, it shows that my_timer variable is not defined. The process that I would want it to undergo is that it will countdown for 5 seconds for every questions, and when the timer reaches 0, it will print out of time and proceed to the next question.
|
[
"In the code you've shown, you haven't assigned a value to my_timer.\nmy_timer = 5\nBy assigning the global within countdown() you've merely allowed countdown to change the value of my_timer. You still need to assign a value.\n"
] |
[
0
] |
[] |
[] |
[
"countdowntimer",
"python"
] |
stackoverflow_0074497971_countdowntimer_python.txt
|
Q:
Webpage not loading while scrapping in Python
I have a dataset which contains URL of Just Dial website for which I am trying to extract few information like seller name. Below I have attached a sample data
dict_test = {"Id" : [1000, 1001, 1002],
"Online_url" : ['https://www.justdial.com/Mumbai/Sunrise-Info-Solutions-Pvt-Ltd-Near-Airtel-Gallery/022PXX22-XX22-220719102528-J5Q2_BZDET?xid=TXVtYmFpIE1vYmlsZSBEZWFsZXJz',
'https://www.justdial.com/Mumbai/Riddhi-Siddhi-Mobile-Gallery-Electronic-Opposite-Jain-Plaza-Ambernath/022PXX22-XX22-210519191020-K2U6_BZDET?xid=TXVtYmFpIE1vYmlsZSBEZWFsZXJz',
'https://www.justdial.com/Mumbai/Bharat-Communication-Opposite-Vibgyor-School-Goregaon-West/022PXX22-XX22-130103150323-S4V9_BZDET?xid=TXVtYmFpIE1vYmlsZSBEZWFsZXJz']}
df_test = pd.DataFrame(dict_test)
And below script is what I have used to extract Seller information
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ['enable-automation'])
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument("--disable-notifications")
options.add_argument( "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36")
options.add_argument("--remote-debugging-port=9222")
driver = webdriver.Chrome(executable_path=r'C:\Users\admin\Downloads\chromedriver_lates\chromedriver.exe', options = options)
driver.maximize_window()
driver.implicitly_wait(10)
driver.get('https://www.justdial.com/')
time.sleep(2)
def webpage_extract(min_count, max_count, df_test, folder, file_name):
for i in range(min_count,max_count):
try:
driver.set_page_load_timeout(5)
driver.switch_to.window(driver.window_handles[0])
driver.execute_script("window.open('');")
# Switch to the new window and open new URL
driver.switch_to.window(driver.window_handles[1])
driver.get(df_test['Online_url'].iloc[i])
time.sleep(5)
except TimeoutException as ex:
isrunning = 0
print("Exception has been thrown.")
try:
myElem = WebDriverWait(driver, 2).until(EC.presence_of_element_located((By.CLASS_NAME, 'fn')))
except TimeoutException:
print("Loading took too much time!")
### Below command is used to close the Pop-up
try:
driver.find_element("xpath", '//*[@id="best_deal_detail_div"]/section/span').click()
driver.find_element("xpath", '//*[@id="best_deal_detail_div"]/section/span').click()
except:
"Pop_Up"
try:
seller_info=driver.find_element("xpath", "/html/body/div[2]/div[1]/div/div[1]/div[2]/div/div/h1/span/span").text
print("Seller_Name: ", seller_info)
except:
seller_info="Extraction_Error"
print("Iteration {} : Information Extracted for Seller {}".format(i, seller_info))
driver.delete_all_cookies()
# Closing the tab
driver.close()
time.sleep(2)
return None
%time webpage_extract(0, len(df_test), df_test, folder, file_name)
The issue with above code is that for 1st URL data is extracting correct information however for 2nd URL the web-page is not loading and is showing about:blank URL. Is there any way to resolve this or to skip this URL and move on to next URL?
A:
you should not close the driver at the end of webpage_extract.
|
Webpage not loading while scrapping in Python
|
I have a dataset which contains URL of Just Dial website for which I am trying to extract few information like seller name. Below I have attached a sample data
dict_test = {"Id" : [1000, 1001, 1002],
"Online_url" : ['https://www.justdial.com/Mumbai/Sunrise-Info-Solutions-Pvt-Ltd-Near-Airtel-Gallery/022PXX22-XX22-220719102528-J5Q2_BZDET?xid=TXVtYmFpIE1vYmlsZSBEZWFsZXJz',
'https://www.justdial.com/Mumbai/Riddhi-Siddhi-Mobile-Gallery-Electronic-Opposite-Jain-Plaza-Ambernath/022PXX22-XX22-210519191020-K2U6_BZDET?xid=TXVtYmFpIE1vYmlsZSBEZWFsZXJz',
'https://www.justdial.com/Mumbai/Bharat-Communication-Opposite-Vibgyor-School-Goregaon-West/022PXX22-XX22-130103150323-S4V9_BZDET?xid=TXVtYmFpIE1vYmlsZSBEZWFsZXJz']}
df_test = pd.DataFrame(dict_test)
And below script is what I have used to extract Seller information
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ['enable-automation'])
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument("--disable-notifications")
options.add_argument( "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36")
options.add_argument("--remote-debugging-port=9222")
driver = webdriver.Chrome(executable_path=r'C:\Users\admin\Downloads\chromedriver_lates\chromedriver.exe', options = options)
driver.maximize_window()
driver.implicitly_wait(10)
driver.get('https://www.justdial.com/')
time.sleep(2)
def webpage_extract(min_count, max_count, df_test, folder, file_name):
for i in range(min_count,max_count):
try:
driver.set_page_load_timeout(5)
driver.switch_to.window(driver.window_handles[0])
driver.execute_script("window.open('');")
# Switch to the new window and open new URL
driver.switch_to.window(driver.window_handles[1])
driver.get(df_test['Online_url'].iloc[i])
time.sleep(5)
except TimeoutException as ex:
isrunning = 0
print("Exception has been thrown.")
try:
myElem = WebDriverWait(driver, 2).until(EC.presence_of_element_located((By.CLASS_NAME, 'fn')))
except TimeoutException:
print("Loading took too much time!")
### Below command is used to close the Pop-up
try:
driver.find_element("xpath", '//*[@id="best_deal_detail_div"]/section/span').click()
driver.find_element("xpath", '//*[@id="best_deal_detail_div"]/section/span').click()
except:
"Pop_Up"
try:
seller_info=driver.find_element("xpath", "/html/body/div[2]/div[1]/div/div[1]/div[2]/div/div/h1/span/span").text
print("Seller_Name: ", seller_info)
except:
seller_info="Extraction_Error"
print("Iteration {} : Information Extracted for Seller {}".format(i, seller_info))
driver.delete_all_cookies()
# Closing the tab
driver.close()
time.sleep(2)
return None
%time webpage_extract(0, len(df_test), df_test, folder, file_name)
The issue with above code is that for 1st URL data is extracting correct information however for 2nd URL the web-page is not loading and is showing about:blank URL. Is there any way to resolve this or to skip this URL and move on to next URL?
|
[
"you should not close the driver at the end of webpage_extract.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x",
"selenium"
] |
stackoverflow_0074492832_python_python_3.x_selenium.txt
|
Q:
How to plot 2 variables against each other using a bar chart in python?
In a pandas dataframe, I have three columns:
Column
Value
Educational level
Bachelors , Masters , PHD , ...
Education-num
1 , 2 , 3 , ...
salary
1 , 0
I want to plot a barchart with count on the y-axis. And on the x-axis, educational level with salary. How can I do so with matplotlib or seaborn?
I have tried:
df = pd.read_csv("ds.csv")
fig, ax = plt.subplots()
sns.barplot(ax = ax, data = df, x = 'EDUCATION-NUM', y = 'SALARY')
plt.show()
But it was not what I want.
A:
You need to do some manipulation to generate count that is in your chart. Is it from 'EDUCATION-NUM'?
Once generated:
x = 'Education level'
y = 'count'
to segment, you use hue = 'SALARY'
documentation is here: https://seaborn.pydata.org/generated/seaborn.barplot.html
|
How to plot 2 variables against each other using a bar chart in python?
|
In a pandas dataframe, I have three columns:
Column
Value
Educational level
Bachelors , Masters , PHD , ...
Education-num
1 , 2 , 3 , ...
salary
1 , 0
I want to plot a barchart with count on the y-axis. And on the x-axis, educational level with salary. How can I do so with matplotlib or seaborn?
I have tried:
df = pd.read_csv("ds.csv")
fig, ax = plt.subplots()
sns.barplot(ax = ax, data = df, x = 'EDUCATION-NUM', y = 'SALARY')
plt.show()
But it was not what I want.
|
[
"You need to do some manipulation to generate count that is in your chart. Is it from 'EDUCATION-NUM'?\nOnce generated:\nx = 'Education level'\ny = 'count'\nto segment, you use hue = 'SALARY'\ndocumentation is here: https://seaborn.pydata.org/generated/seaborn.barplot.html\n"
] |
[
0
] |
[] |
[] |
[
"bar_chart",
"matplotlib",
"plot",
"python",
"seaborn"
] |
stackoverflow_0074498254_bar_chart_matplotlib_plot_python_seaborn.txt
|
Q:
How can I restrict users to delete other's posts in django using class based views?
my views.py file:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin,
)
from .models import Post
# Create your views here.
class PostListView(ListView):
model = Post
template_name = "blog/index.html"
context_object_name = "posts"
ordering = ["-date_posted"]
class PostDetailView(DetailView):
model = Post
class PostCreateView(CreateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
fields = ['title', 'genere', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
success_url = "blog-home"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(DeleteView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
success_url = "/"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def about(request):
return render(request, 'blog/about.html')
My models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
genere = models.CharField(max_length=50, default='')
def __str__(self):
return f'{self.title} by {self.author}'
def get_absolute_url(self):
return reverse('blog-home')
my urls.py url:
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView
from . import views
urlpatterns = [
path("", PostListView.as_view(), name="blog-home"),
path("about", views.about, name="blog-about"),
path("post/<int:pk>", PostDetailView.as_view(), name="blog-detail"),
path("post/new", PostCreateView.as_view(), name="blog-create"),
path("post/<int:pk>/update", PostUpdateView.as_view(), name="blog-update"),
path("post/<int:pk>/delete", PostDeleteView.as_view(), name="blog-delete"),
]
index.html
{% extends "blog/base.html" %}
{% load static %}
{% block content %}
<div class="row tm-row">
{% for post in posts %}
<article class="col-12 col-md-6 tm-post">
<hr class="tm-hr-primary">
<a href="{% url 'blog-detail' post.id %}" class="effect-lily tm-post-link tm-pt-60">
<div class="tm-post-link-inner">
<img src="{% static 'img/img-01.jpg' %}" alt="Image" class="img-fluid">
</div>
<span class="position-absolute tm-new-badge">New</span>
<h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ post.title }}</h2>
</a>
<p class="tm-pt-30">
{{ post.content|safe|truncatewords:"30"|linebreaks }}
</p>
<div class="d-flex justify-content-between tm-pt-45">
<span class="tm-color-primary">{{ post.genere }}</span>
<span class="tm-color-primary">{{ post.date_posted|date:'N j,Y' }}</span>
</div>
<hr>
<div class="d-flex justify-content-between">
<span>36 comments</span>
<span>by {{ post.author }}</span>
</div>
</article>
{% endfor %}
</div>
{% endblock %}
post_detail.html:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div class="container">
<article class="col-12 col-md-6 tm-post">
<hr class="tm-hr-primary">
<a href="" class="effect-lily tm-post-link tm-pt-60">
<div class="tm-post-link-inner">
<img src="{% static 'img/img-01.jpg' %}" alt="Image" class="img-fluid">
</div>
<span class="position-absolute tm-new-badge">New</span>
<h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ object.title }}</h2>
{% if object.author == user %}
<a class="btn btn-outline-danger" href="{% url 'blog-delete' object.id %}">Delete</a>
<a class="btn btn-outline-secondary" href="{% url 'blog-update' object.id %}">Update</a>
{% endif %}
</a>
<p class="tm-pt-30">
{{ object.content }}
</p>
<div class="d-flex justify-content-between tm-pt-45">
<span class="tm-color-primary">{{ object.genere }}</span>
<span class="tm-color-primary">{{ object.date_posted|date:'N j,Y' }}</span>
</div>
<hr>
<div class="d-flex justify-content-between">
<span>36 comments</span>
<span>by {{ object.author }}</span>
</div>
</article>
</div>
{% endblock %}
post_confirm_delete.html:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<form method="POST">
{% csrf_token %}
<h2>Are You Sure You Want To Delete "{{ object.title }}"</h2>
<button class="btn btn-outline-danger">Yes, I'm Sure</button>
<a class="btn btn-outline-secondary" href="{% url 'blog-detail' object.id %}">Cancel</a>
</form>
</div>
{% endblock %}
So, what I'm getting is that suppose 2 person jeff and ram are users so ram cannot update the posts of jeff and vice versa.
And if jeff views the post of ram, so he does not get the update and delete, so he cannot edit the post of ram but if jeff goes to "127.0.0.1:8000/post/9/delete" from "127.0.0.1:800/post/9",
So he get the confirm delete page and he can even delete his post.
How can I fix this bug in my project??????
A:
you can use get_queryset() to restrict query in database
class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
success_url = "blog-home"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_queryset(self):
pk = self.kwargs.get(self.pk_url_kwarg)
return self.model.objects.filter(pk=pk,user=self.request.user)
|
How can I restrict users to delete other's posts in django using class based views?
|
my views.py file:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin,
)
from .models import Post
# Create your views here.
class PostListView(ListView):
model = Post
template_name = "blog/index.html"
context_object_name = "posts"
ordering = ["-date_posted"]
class PostDetailView(DetailView):
model = Post
class PostCreateView(CreateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
fields = ['title', 'genere', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
success_url = "blog-home"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(DeleteView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
success_url = "/"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def about(request):
return render(request, 'blog/about.html')
My models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
genere = models.CharField(max_length=50, default='')
def __str__(self):
return f'{self.title} by {self.author}'
def get_absolute_url(self):
return reverse('blog-home')
my urls.py url:
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView
from . import views
urlpatterns = [
path("", PostListView.as_view(), name="blog-home"),
path("about", views.about, name="blog-about"),
path("post/<int:pk>", PostDetailView.as_view(), name="blog-detail"),
path("post/new", PostCreateView.as_view(), name="blog-create"),
path("post/<int:pk>/update", PostUpdateView.as_view(), name="blog-update"),
path("post/<int:pk>/delete", PostDeleteView.as_view(), name="blog-delete"),
]
index.html
{% extends "blog/base.html" %}
{% load static %}
{% block content %}
<div class="row tm-row">
{% for post in posts %}
<article class="col-12 col-md-6 tm-post">
<hr class="tm-hr-primary">
<a href="{% url 'blog-detail' post.id %}" class="effect-lily tm-post-link tm-pt-60">
<div class="tm-post-link-inner">
<img src="{% static 'img/img-01.jpg' %}" alt="Image" class="img-fluid">
</div>
<span class="position-absolute tm-new-badge">New</span>
<h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ post.title }}</h2>
</a>
<p class="tm-pt-30">
{{ post.content|safe|truncatewords:"30"|linebreaks }}
</p>
<div class="d-flex justify-content-between tm-pt-45">
<span class="tm-color-primary">{{ post.genere }}</span>
<span class="tm-color-primary">{{ post.date_posted|date:'N j,Y' }}</span>
</div>
<hr>
<div class="d-flex justify-content-between">
<span>36 comments</span>
<span>by {{ post.author }}</span>
</div>
</article>
{% endfor %}
</div>
{% endblock %}
post_detail.html:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div class="container">
<article class="col-12 col-md-6 tm-post">
<hr class="tm-hr-primary">
<a href="" class="effect-lily tm-post-link tm-pt-60">
<div class="tm-post-link-inner">
<img src="{% static 'img/img-01.jpg' %}" alt="Image" class="img-fluid">
</div>
<span class="position-absolute tm-new-badge">New</span>
<h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ object.title }}</h2>
{% if object.author == user %}
<a class="btn btn-outline-danger" href="{% url 'blog-delete' object.id %}">Delete</a>
<a class="btn btn-outline-secondary" href="{% url 'blog-update' object.id %}">Update</a>
{% endif %}
</a>
<p class="tm-pt-30">
{{ object.content }}
</p>
<div class="d-flex justify-content-between tm-pt-45">
<span class="tm-color-primary">{{ object.genere }}</span>
<span class="tm-color-primary">{{ object.date_posted|date:'N j,Y' }}</span>
</div>
<hr>
<div class="d-flex justify-content-between">
<span>36 comments</span>
<span>by {{ object.author }}</span>
</div>
</article>
</div>
{% endblock %}
post_confirm_delete.html:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<form method="POST">
{% csrf_token %}
<h2>Are You Sure You Want To Delete "{{ object.title }}"</h2>
<button class="btn btn-outline-danger">Yes, I'm Sure</button>
<a class="btn btn-outline-secondary" href="{% url 'blog-detail' object.id %}">Cancel</a>
</form>
</div>
{% endblock %}
So, what I'm getting is that suppose 2 person jeff and ram are users so ram cannot update the posts of jeff and vice versa.
And if jeff views the post of ram, so he does not get the update and delete, so he cannot edit the post of ram but if jeff goes to "127.0.0.1:8000/post/9/delete" from "127.0.0.1:800/post/9",
So he get the confirm delete page and he can even delete his post.
How can I fix this bug in my project??????
|
[
"you can use get_queryset() to restrict query in database\nclass PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin):\n model = Post\n success_url = \"blog-home\"\n\n def form_valid(self, form):\n form.instance.author = self.request.user\n return super().form_valid(form)\n\n def get_queryset(self):\n pk = self.kwargs.get(self.pk_url_kwarg)\n return self.model.objects.filter(pk=pk,user=self.request.user)\n \n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0070692162_django_python.txt
|
Q:
AttributeError: module '__main__' has no attribute 'cleaner'
We are creating web-site with ai assistant. We trained our model in Google Colab and now we are trying to upload it to our project. But we get the following error:
AttributeError: module '__main__' has no attribute 'cleaner'
In our file views.py declared the class VoiceAssistant and the function cleaner for pipeline. The problem is hidden on the line:
talk_model = joblib.load(r'artifitial_assistant/model.pkl')
While training our model we used the following code:
Pipeline(steps=[('bow',
CountVectorizer(analyzer = cleaner)),
('tfidf', TfidfTransformer()),
('classifier', DecisionTreeClassifier())])
Views.py:
import string
import traceback
import webbrowser
import joblib
import pyttsx3
import speech_recognition
import wikipedia
from django.shortcut import render
def cleaner(x):
"""
cleaning function required for neural model
"""
return [a for a in (''.join([a for a in x if a not in string.punctuation])).lower().split()]
class VoiceAssistant:
"""
Settings of our voice assistant
"""
name = ""
sex = ""
speech_lang = ""
is_talking = False
recognition_lang = ""
# initializing speech recognition and input tools
recognizer = speech_recognition.Recognizer()
microphone = speech_recognition.Microphone()
# initialization of the speech synthesis tool
ttsEngine = pyttsx3.init()
def assistant_answer(self, voice):
"""
a function that loads user input into the neural model and predicts the response
"""
answer = self.talk_model.predict([voice])[0]
return answer
# loading a neural model from disk
talk_model = joblib.load(r'artifitial_assistant/model.pkl') # !!!<-Problem uppears here
...
from django.shortcuts import render
from django.http import HttpResponse
#initializing voice_assistant
voice_assistant = VoiceAssistant()
voice_assistant.sex = "female"
voice_assistant.speech_lang = "en"
voice_assistant.name = "blonde"
voice_assistant.setup_assistant_voice()
def first_view(request): #just want to get the simplest response from voice_assistant
return HttpResponse(voice_assistant.assistant_answer('Hi'))
A:
To solve this problem, I just added cleaner function to the manage.py, because there is the module main. It solved the problem.
A:
Just change the name of your module from "main" to anything else, and it should work
|
AttributeError: module '__main__' has no attribute 'cleaner'
|
We are creating web-site with ai assistant. We trained our model in Google Colab and now we are trying to upload it to our project. But we get the following error:
AttributeError: module '__main__' has no attribute 'cleaner'
In our file views.py declared the class VoiceAssistant and the function cleaner for pipeline. The problem is hidden on the line:
talk_model = joblib.load(r'artifitial_assistant/model.pkl')
While training our model we used the following code:
Pipeline(steps=[('bow',
CountVectorizer(analyzer = cleaner)),
('tfidf', TfidfTransformer()),
('classifier', DecisionTreeClassifier())])
Views.py:
import string
import traceback
import webbrowser
import joblib
import pyttsx3
import speech_recognition
import wikipedia
from django.shortcut import render
def cleaner(x):
"""
cleaning function required for neural model
"""
return [a for a in (''.join([a for a in x if a not in string.punctuation])).lower().split()]
class VoiceAssistant:
"""
Settings of our voice assistant
"""
name = ""
sex = ""
speech_lang = ""
is_talking = False
recognition_lang = ""
# initializing speech recognition and input tools
recognizer = speech_recognition.Recognizer()
microphone = speech_recognition.Microphone()
# initialization of the speech synthesis tool
ttsEngine = pyttsx3.init()
def assistant_answer(self, voice):
"""
a function that loads user input into the neural model and predicts the response
"""
answer = self.talk_model.predict([voice])[0]
return answer
# loading a neural model from disk
talk_model = joblib.load(r'artifitial_assistant/model.pkl') # !!!<-Problem uppears here
...
from django.shortcuts import render
from django.http import HttpResponse
#initializing voice_assistant
voice_assistant = VoiceAssistant()
voice_assistant.sex = "female"
voice_assistant.speech_lang = "en"
voice_assistant.name = "blonde"
voice_assistant.setup_assistant_voice()
def first_view(request): #just want to get the simplest response from voice_assistant
return HttpResponse(voice_assistant.assistant_answer('Hi'))
|
[
"To solve this problem, I just added cleaner function to the manage.py, because there is the module main. It solved the problem.\n",
"Just change the name of your module from \"main\" to anything else, and it should work\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"joblib",
"machine_learning",
"python",
"scikit_learn"
] |
stackoverflow_0073209533_django_joblib_machine_learning_python_scikit_learn.txt
|
Q:
Extract content from a page that renders it with javascript using Beautifulsoup
I started programming not long ago and came across this problem. I want to collect stock data from the website: https://statusinvest.com.br/acoes/petr4. But apparently they are rendered with javascript and BeautifulSoup does not collect, if you can help I appreciate it
My soup code
Example of information loaded with javascript
A:
Hoping that OP's next questions will contain a minimal, reproducible example, here is one way of getting some data from that page using Requests and BeautifulSoup:
from bs4 import BeautifulSoup as bs
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}
r = requests.get('https://statusinvest.com.br/acoes/petr4', headers=headers)
soup = bs(r.text, 'html.parser')
valor_atual = soup.select_one('h3:-soup-contains("Valor atual")').find_next('strong').text
min_52_semanas = soup.select_one('h3:-soup-contains("Min. 52 semanas")').find_next('strong').text
print('Valor atual:', valor_atual)
print('Min. 52 semanas:', min_52_semanas)
### and now some values hydrated in page by Javascript, from an API endpoint:
api_url = 'https://statusinvest.com.br/acao/payoutresult?code=petr4&companyid=408&type=0'
api_headers = {
'referer': 'https://statusinvest.com.br/acoes/petr4',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}
r = requests.get(api_url, headers=api_headers)
print(r.json())
Result in terminal:
Valor atual: 26,54
Min. 52 semanas: 15,85
{'actual': 124.12623323305537, 'avg': 83.32096287339556, 'avgDifference': 48.97359434223362, 'minValue': 26.353309862919502, 'minValueRank': 2019, 'maxValue': 144.51093035368598, 'maxValueRank': 2020, 'actual_F': '124,13%', 'avg_F': '83,32%', 'avgDifference_F': '48,97% acima da média', 'minValue_F': '26,35%', 'minValueRank_F': '2019', 'maxValue_F': '144,51%', 'maxValueRank_F': '2020', 'chart': {'categoryUnique': True, 'category': ['2018', '2019', '2020', '2021', '2022'], 'series': {'percentual': [{'value': 27.189302754606462, 'value_F': '27,19%'}, {'value': 26.353309862919502, 'value_F': '26,35%'}, {'value': 144.51093035368598, 'value_F': '144,51%'}, {'value': 94.42503816271046, 'value_F': '94,43%'}, {'value': 124.12623323305537, 'value_F': '124,13%'}], 'proventos': [{'value': 7009130357.11, 'value_F': 'R$ 7.009.130.357,11', 'valueSmall_F': '7,01 B'}, {'value': 10577427979.68, 'value_F': 'R$ 10.577.427.979,68', 'valueSmall_F': '10,58 B'}, {'value': 10271836929.54, 'value_F': 'R$ 10.271.836.929,54', 'valueSmall_F': '10,27 B'}, {'value': 100721299707.4, 'value_F': 'R$ 100.721.299.707,40', 'valueSmall_F': '100,72 B'}, {'value': 179966901777.61, 'value_F': 'R$ 179.966.901.777,61', 'valueSmall_F': '179,97 B'}], 'lucroLiquido': [{'value': 25779000000.0, 'value_F': 'R$ 25.779.000.000,00', 'valueSmall_F': '25,78 B'}, {'value': 40137000000.0, 'value_F': 'R$ 40.137.000.000,00', 'valueSmall_F': '40,14 B'}, {'value': 7108000000.0, 'value_F': 'R$ 7.108.000.000,00', 'valueSmall_F': '7,11 B'}, {'value': 106668000000.0, 'value_F': 'R$ 106.668.000.000,00', 'valueSmall_F': '106,67 B'}, {'value': 144987000000.0, 'value_F': 'R$ 144.987.000.000,00', 'valueSmall_F': '144,99 B'}]}}}
BeautifulSoup documentation can be found here: https://beautiful-soup-4.readthedocs.io/en/latest/
A:
This section not only requires js to load, it actually will not load until you scroll to it. You could try to figure out which request and/or bit of js was made to render that section and then attempt to replicate it with python, but I think it would be easier to use selenium. I even have this function for making it more convenient to automate some of the simpler/common interactions before scraping the html:
#### FIRST PASTE [or DOWNLOAD&IMPORT] FUNCTION DEF from https://pastebin.com/kEC9gPC8 ####
soup = linkToSoup_selenium(
'https://statusinvest.com.br/acoes/petr4',
clickFirst='//strong[@data-item="avg_F"]' # it actually just has to scroll, not click [but I haven't added an option for that yet],
ecx='//strong[@data-item="avg_F"][text()!="-"]' # waits till this loads
)
if soup is not None:
print({
t.find_previous_sibling().get_text(' ').strip(): t.get_text(' ').strip()
for t in soup.select('div#payout-section span.title + strong.value')
})
prints
{'MÉDIA': '83,32%', 'ATUAL': '124,13% \n ( 48,97% acima da média )', 'MENOR\xa0VALOR': '26,35% \n ( 2019 )', 'MAIOR\xa0VALOR': '144,51% \n \n( 2020 )'}
EDIT: I ended up noticing the API used for fetching the data after all (https://statusinvest.com.br/acao/payoutresult?code=petr4&companyid=408&type=0). You can actually reform it even with html available before the js-loading happens:
soup.select_one('#payout-section[data-company][data-code]').attrs
should return
{'id': 'payout-section', 'data-company': '408', 'data-code': 'petr4', 'data-category': '1'}
so then the url can be formed with
payout = soup.select_one('#payout-section[data-company][data-code]')
if payout:
compId, dCode = payout.get('data-company'), payout.get('data-code')
apiUrl = f'https://statusinvest.com.br/acao'
apiUrl = f'{apiUrl}/payoutresult?code={dCode}&companyid={compId}&type=0'
[I think the type param is for the time window - 0 for 5yrs, 1 for 10yrs, and 2 for max window.] requests.get(apiUrl, headers=headers).json() should return something like
{
"actual": 124.12623323305537,
"avg": 83.32096287339556,
"avgDifference": 48.97359434223362,
"minValue": 26.353309862919502,
"minValueRank": 2019,
"maxValue": 144.51093035368598,
"maxValueRank": 2020,
"actual_F": "124,13%",
"avg_F": "83,32%",
"avgDifference_F": "48,97% acima da m\u00e9dia",
"minValue_F": "26,35%",
"minValueRank_F": "2019",
"maxValue_F": "144,51%",
"maxValueRank_F": "2020",
"chart": {
"categoryUnique": true,
"category": [
"2018",
"2019",
"2020",
"2021",
"2022"
],
"series": {
"percentual": [
{
"value": 27.189302754606462,
"value_F": "27,19%"
},
{
"value": 26.353309862919502,
"value_F": "26,35%"
},
{
"value": 144.51093035368598,
"value_F": "144,51%"
},
{
"value": 94.42503816271046,
"value_F": "94,43%"
},
{
"value": 124.12623323305537,
"value_F": "124,13%"
}
],
"proventos": [
{
"value": 7009130357.11,
"value_F": "R$ 7.009.130.357,11",
"valueSmall_F": "7,01 B"
},
{
"value": 10577427979.68,
"value_F": "R$ 10.577.427.979,68",
"valueSmall_F": "10,58 B"
},
{
"value": 10271836929.54,
"value_F": "R$ 10.271.836.929,54",
"valueSmall_F": "10,27 B"
},
{
"value": 100721299707.4,
"value_F": "R$ 100.721.299.707,40",
"valueSmall_F": "100,72 B"
},
{
"value": 179966901777.61,
"value_F": "R$ 179.966.901.777,61",
"valueSmall_F": "179,97 B"
}
],
"lucroLiquido": [
{
"value": 25779000000.0,
"value_F": "R$ 25.779.000.000,00",
"valueSmall_F": "25,78 B"
},
{
"value": 40137000000.0,
"value_F": "R$ 40.137.000.000,00",
"valueSmall_F": "40,14 B"
},
{
"value": 7108000000.0,
"value_F": "R$ 7.108.000.000,00",
"valueSmall_F": "7,11 B"
},
{
"value": 106668000000.0,
"value_F": "R$ 106.668.000.000,00",
"valueSmall_F": "106,67 B"
},
{
"value": 144987000000.0,
"value_F": "R$ 144.987.000.000,00",
"valueSmall_F": "144,99 B"
}
]
}
}
}
and then you can get the values you want from there. (I think it includes the chart data as well.)
|
Extract content from a page that renders it with javascript using Beautifulsoup
|
I started programming not long ago and came across this problem. I want to collect stock data from the website: https://statusinvest.com.br/acoes/petr4. But apparently they are rendered with javascript and BeautifulSoup does not collect, if you can help I appreciate it
My soup code
Example of information loaded with javascript
|
[
"Hoping that OP's next questions will contain a minimal, reproducible example, here is one way of getting some data from that page using Requests and BeautifulSoup:\nfrom bs4 import BeautifulSoup as bs\nimport requests\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\n\nr = requests.get('https://statusinvest.com.br/acoes/petr4', headers=headers)\nsoup = bs(r.text, 'html.parser')\nvalor_atual = soup.select_one('h3:-soup-contains(\"Valor atual\")').find_next('strong').text\nmin_52_semanas = soup.select_one('h3:-soup-contains(\"Min. 52 semanas\")').find_next('strong').text\nprint('Valor atual:', valor_atual)\nprint('Min. 52 semanas:', min_52_semanas)\n\n### and now some values hydrated in page by Javascript, from an API endpoint:\n\napi_url = 'https://statusinvest.com.br/acao/payoutresult?code=petr4&companyid=408&type=0'\napi_headers = {\n 'referer': 'https://statusinvest.com.br/acoes/petr4',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\nr = requests.get(api_url, headers=api_headers)\nprint(r.json())\n\nResult in terminal:\nValor atual: 26,54\nMin. 52 semanas: 15,85\n{'actual': 124.12623323305537, 'avg': 83.32096287339556, 'avgDifference': 48.97359434223362, 'minValue': 26.353309862919502, 'minValueRank': 2019, 'maxValue': 144.51093035368598, 'maxValueRank': 2020, 'actual_F': '124,13%', 'avg_F': '83,32%', 'avgDifference_F': '48,97% acima da média', 'minValue_F': '26,35%', 'minValueRank_F': '2019', 'maxValue_F': '144,51%', 'maxValueRank_F': '2020', 'chart': {'categoryUnique': True, 'category': ['2018', '2019', '2020', '2021', '2022'], 'series': {'percentual': [{'value': 27.189302754606462, 'value_F': '27,19%'}, {'value': 26.353309862919502, 'value_F': '26,35%'}, {'value': 144.51093035368598, 'value_F': '144,51%'}, {'value': 94.42503816271046, 'value_F': '94,43%'}, {'value': 124.12623323305537, 'value_F': '124,13%'}], 'proventos': [{'value': 7009130357.11, 'value_F': 'R$ 7.009.130.357,11', 'valueSmall_F': '7,01 B'}, {'value': 10577427979.68, 'value_F': 'R$ 10.577.427.979,68', 'valueSmall_F': '10,58 B'}, {'value': 10271836929.54, 'value_F': 'R$ 10.271.836.929,54', 'valueSmall_F': '10,27 B'}, {'value': 100721299707.4, 'value_F': 'R$ 100.721.299.707,40', 'valueSmall_F': '100,72 B'}, {'value': 179966901777.61, 'value_F': 'R$ 179.966.901.777,61', 'valueSmall_F': '179,97 B'}], 'lucroLiquido': [{'value': 25779000000.0, 'value_F': 'R$ 25.779.000.000,00', 'valueSmall_F': '25,78 B'}, {'value': 40137000000.0, 'value_F': 'R$ 40.137.000.000,00', 'valueSmall_F': '40,14 B'}, {'value': 7108000000.0, 'value_F': 'R$ 7.108.000.000,00', 'valueSmall_F': '7,11 B'}, {'value': 106668000000.0, 'value_F': 'R$ 106.668.000.000,00', 'valueSmall_F': '106,67 B'}, {'value': 144987000000.0, 'value_F': 'R$ 144.987.000.000,00', 'valueSmall_F': '144,99 B'}]}}}\n\nBeautifulSoup documentation can be found here: https://beautiful-soup-4.readthedocs.io/en/latest/\n",
"This section not only requires js to load, it actually will not load until you scroll to it. You could try to figure out which request and/or bit of js was made to render that section and then attempt to replicate it with python, but I think it would be easier to use selenium. I even have this function for making it more convenient to automate some of the simpler/common interactions before scraping the html:\n#### FIRST PASTE [or DOWNLOAD&IMPORT] FUNCTION DEF from https://pastebin.com/kEC9gPC8 ####\nsoup = linkToSoup_selenium(\n 'https://statusinvest.com.br/acoes/petr4', \n clickFirst='//strong[@data-item=\"avg_F\"]' # it actually just has to scroll, not click [but I haven't added an option for that yet], \n ecx='//strong[@data-item=\"avg_F\"][text()!=\"-\"]' # waits till this loads\n)\nif soup is not None:\n print({\n t.find_previous_sibling().get_text(' ').strip(): t.get_text(' ').strip()\n for t in soup.select('div#payout-section span.title + strong.value')\n })\n\nprints\n{'MÉDIA': '83,32%', 'ATUAL': '124,13% \\n ( 48,97% acima da média )', 'MENOR\\xa0VALOR': '26,35% \\n ( 2019 )', 'MAIOR\\xa0VALOR': '144,51% \\n \\n( 2020 )'}\n\n\nEDIT: I ended up noticing the API used for fetching the data after all (https://statusinvest.com.br/acao/payoutresult?code=petr4&companyid=408&type=0). You can actually reform it even with html available before the js-loading happens:\nsoup.select_one('#payout-section[data-company][data-code]').attrs\n\nshould return\n{'id': 'payout-section', 'data-company': '408', 'data-code': 'petr4', 'data-category': '1'}\n\nso then the url can be formed with\npayout = soup.select_one('#payout-section[data-company][data-code]')\nif payout:\n compId, dCode = payout.get('data-company'), payout.get('data-code')\n apiUrl = f'https://statusinvest.com.br/acao'\n apiUrl = f'{apiUrl}/payoutresult?code={dCode}&companyid={compId}&type=0'\n\n[I think the type param is for the time window - 0 for 5yrs, 1 for 10yrs, and 2 for max window.] requests.get(apiUrl, headers=headers).json() should return something like\n{\n \"actual\": 124.12623323305537,\n \"avg\": 83.32096287339556,\n \"avgDifference\": 48.97359434223362,\n \"minValue\": 26.353309862919502,\n \"minValueRank\": 2019,\n \"maxValue\": 144.51093035368598,\n \"maxValueRank\": 2020,\n \"actual_F\": \"124,13%\",\n \"avg_F\": \"83,32%\",\n \"avgDifference_F\": \"48,97% acima da m\\u00e9dia\",\n \"minValue_F\": \"26,35%\",\n \"minValueRank_F\": \"2019\",\n \"maxValue_F\": \"144,51%\",\n \"maxValueRank_F\": \"2020\",\n \"chart\": {\n \"categoryUnique\": true,\n \"category\": [\n \"2018\",\n \"2019\",\n \"2020\",\n \"2021\",\n \"2022\"\n ],\n \"series\": {\n \"percentual\": [\n {\n \"value\": 27.189302754606462,\n \"value_F\": \"27,19%\"\n },\n {\n \"value\": 26.353309862919502,\n \"value_F\": \"26,35%\"\n },\n {\n \"value\": 144.51093035368598,\n \"value_F\": \"144,51%\"\n },\n {\n \"value\": 94.42503816271046,\n \"value_F\": \"94,43%\"\n },\n {\n \"value\": 124.12623323305537,\n \"value_F\": \"124,13%\"\n }\n ],\n \"proventos\": [\n {\n \"value\": 7009130357.11,\n \"value_F\": \"R$ 7.009.130.357,11\",\n \"valueSmall_F\": \"7,01 B\"\n },\n {\n \"value\": 10577427979.68,\n \"value_F\": \"R$ 10.577.427.979,68\",\n \"valueSmall_F\": \"10,58 B\"\n },\n {\n \"value\": 10271836929.54,\n \"value_F\": \"R$ 10.271.836.929,54\",\n \"valueSmall_F\": \"10,27 B\"\n },\n {\n \"value\": 100721299707.4,\n \"value_F\": \"R$ 100.721.299.707,40\",\n \"valueSmall_F\": \"100,72 B\"\n },\n {\n \"value\": 179966901777.61,\n \"value_F\": \"R$ 179.966.901.777,61\",\n \"valueSmall_F\": \"179,97 B\"\n }\n ],\n \"lucroLiquido\": [\n {\n \"value\": 25779000000.0,\n \"value_F\": \"R$ 25.779.000.000,00\",\n \"valueSmall_F\": \"25,78 B\"\n },\n {\n \"value\": 40137000000.0,\n \"value_F\": \"R$ 40.137.000.000,00\",\n \"valueSmall_F\": \"40,14 B\"\n },\n {\n \"value\": 7108000000.0,\n \"value_F\": \"R$ 7.108.000.000,00\",\n \"valueSmall_F\": \"7,11 B\"\n },\n {\n \"value\": 106668000000.0,\n \"value_F\": \"R$ 106.668.000.000,00\",\n \"valueSmall_F\": \"106,67 B\"\n },\n {\n \"value\": 144987000000.0,\n \"value_F\": \"R$ 144.987.000.000,00\",\n \"valueSmall_F\": \"144,99 B\"\n }\n ]\n }\n }\n}\n\nand then you can get the values you want from there. (I think it includes the chart data as well.)\n"
] |
[
0,
0
] |
[] |
[] |
[
"beautifulsoup",
"python",
"web_scraping"
] |
stackoverflow_0074497235_beautifulsoup_python_web_scraping.txt
|
Q:
how to avoid TO_TENSOR() clips values to 1
I have a black and white image that needs to be converted into tensor.
The shape of the image is (400, 600, 3).
Originally, the values of the image have max = 255; for example:
org_img[0]
# result:
array([[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]], dtype=uint8)
but after i convert into tensor using to_tensor(), it clips my value into 1.
torchvision.transforms.functional.to_tensor(org_img[0])
# result:
tensor([[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
...,
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]])
This makes my image all black, how can i avoid this problem?
Thank you.
A:
The images are not clipped but instead re-scaled from uint8 0..255 to float32 [0, 1] by ToTensor. Library such as matplotlib can naturally handle RGB images with single-precision pixel values within [0, 1] after re-scaling.
|
how to avoid TO_TENSOR() clips values to 1
|
I have a black and white image that needs to be converted into tensor.
The shape of the image is (400, 600, 3).
Originally, the values of the image have max = 255; for example:
org_img[0]
# result:
array([[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]], dtype=uint8)
but after i convert into tensor using to_tensor(), it clips my value into 1.
torchvision.transforms.functional.to_tensor(org_img[0])
# result:
tensor([[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
...,
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]])
This makes my image all black, how can i avoid this problem?
Thank you.
|
[
"The images are not clipped but instead re-scaled from uint8 0..255 to float32 [0, 1] by ToTensor. Library such as matplotlib can naturally handle RGB images with single-precision pixel values within [0, 1] after re-scaling.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"pytorch",
"tensor"
] |
stackoverflow_0074498111_python_pytorch_tensor.txt
|
Q:
Celery Tasks are not getting added to database
I am trying to run my django application using docker which involves celery. I am able to set everything on local and it works perfectly fine. However, when I run it docker, and my task gets executed, it throws me the following error:
myapp.models.mymodel.DoesNotExist: mymodel matching query does not exist.
I am particularly new to celery and docker so not sure what am I doing wrong.
Celery is set up correctly, I have made sure of that. Following are the broker_url and backend:
CELERY_BROKER_URL = 'redis://redis:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = 'django-db'
This is my docker-compose.yml file:
version: "3.8"
services:
redis:
image: redis:alpine
container_name: rz01
ports:
- "6379:6379"
networks:
- npm-nw
- braythonweb-network
braythonweb:
build: .
command: >
sh -c "python manage.py makemigrations &&
python manage.py migrate &&
gunicorn braython.wsgi:application -b 0.0.0.0:8000 --workers=1 --timeout 10000"
volumes:
- .:/code
ports:
- "8000:8000"
restart: unless-stopped
env_file: .env
networks:
- npm-nw
- braythonweb-network
celery:
build: .
restart: always
container_name: cl01
command: celery -A braython worker -l info
depends_on:
- redis
networks:
- npm-nw
- braythonweb-network
networks:
braythonweb-network:
npm-nw:
external: false
I have tried few things from different stackoverflow posts like apply_async. I have also made sure that my model existed.
Update On further investigating the issue, I have noticed that the celery task does not get created in the database in the first place. Don't know why, may be I have to the following with something else:
CELERY_RESULT_BACKEND = 'django-db'
A:
The exception is telling you that you are looking for an entry in your database, that does not exist (yet). Look for any function where you query the database and make sure you create the needed entry before looking for it. I'm assuming you have a table in your database for some configuration, that is read in a function, but the database is empty at the beginning.
A:
I had to add the following to the celery container too to provide access to it:
volumes:
- .:/code
|
Celery Tasks are not getting added to database
|
I am trying to run my django application using docker which involves celery. I am able to set everything on local and it works perfectly fine. However, when I run it docker, and my task gets executed, it throws me the following error:
myapp.models.mymodel.DoesNotExist: mymodel matching query does not exist.
I am particularly new to celery and docker so not sure what am I doing wrong.
Celery is set up correctly, I have made sure of that. Following are the broker_url and backend:
CELERY_BROKER_URL = 'redis://redis:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = 'django-db'
This is my docker-compose.yml file:
version: "3.8"
services:
redis:
image: redis:alpine
container_name: rz01
ports:
- "6379:6379"
networks:
- npm-nw
- braythonweb-network
braythonweb:
build: .
command: >
sh -c "python manage.py makemigrations &&
python manage.py migrate &&
gunicorn braython.wsgi:application -b 0.0.0.0:8000 --workers=1 --timeout 10000"
volumes:
- .:/code
ports:
- "8000:8000"
restart: unless-stopped
env_file: .env
networks:
- npm-nw
- braythonweb-network
celery:
build: .
restart: always
container_name: cl01
command: celery -A braython worker -l info
depends_on:
- redis
networks:
- npm-nw
- braythonweb-network
networks:
braythonweb-network:
npm-nw:
external: false
I have tried few things from different stackoverflow posts like apply_async. I have also made sure that my model existed.
Update On further investigating the issue, I have noticed that the celery task does not get created in the database in the first place. Don't know why, may be I have to the following with something else:
CELERY_RESULT_BACKEND = 'django-db'
|
[
"The exception is telling you that you are looking for an entry in your database, that does not exist (yet). Look for any function where you query the database and make sure you create the needed entry before looking for it. I'm assuming you have a table in your database for some configuration, that is read in a function, but the database is empty at the beginning.\n",
"I had to add the following to the celery container too to provide access to it:\nvolumes:\n - .:/code\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"celery",
"celery_task",
"django",
"docker",
"python"
] |
stackoverflow_0074475991_celery_celery_task_django_docker_python.txt
|
Q:
Getting much output from the number of user input in Javascript
In Python I use "for x in range(j)" and j is defined from user input, for example
j = int(input())
for x in range(j)
print(j)
if I input j as 3, the output will be
3
3
3
My question is, how do i do it with javascript?
I tried to do it with array, etc. Nothing seems to work, sorry im really new at coding and need to learn 2 programming language for my college
A:
You can do it with prompt function
const printData = () =>{
let num = prompt("Please input a number", "3") // second parameter is the default value
if(isNaN(num)){
console.error(`${num} is an invalid number`)
return
}
for(let i=0;i<num;i++){
console.log(num)
}
}
printData()
|
Getting much output from the number of user input in Javascript
|
In Python I use "for x in range(j)" and j is defined from user input, for example
j = int(input())
for x in range(j)
print(j)
if I input j as 3, the output will be
3
3
3
My question is, how do i do it with javascript?
I tried to do it with array, etc. Nothing seems to work, sorry im really new at coding and need to learn 2 programming language for my college
|
[
"You can do it with prompt function\n\n\nconst printData = () =>{\n\n let num = prompt(\"Please input a number\", \"3\") // second parameter is the default value\n if(isNaN(num)){\n console.error(`${num} is an invalid number`)\n return\n }\n\n for(let i=0;i<num;i++){\n console.log(num)\n }\n}\n\nprintData()\n\n\n\n"
] |
[
0
] |
[] |
[] |
[
"javascript",
"python"
] |
stackoverflow_0074498452_javascript_python.txt
|
Q:
Trying to create a filled dataframe from pandas crosstab
I've got a numpy array that looks like this, in general (it was created from a pd crosstable if that's of any significance)
Person
1to1 Person Attribute
Circumstance
Outcome A Count
Outcome B Count
ABC1
1
X
100
25
DEF2
2
X
1
2
Y
0
2
XYZ1
1
X
33
5
Y
5
10
that I'd like to turn into a pandas dataframe that looks like
Person
1to1 Person Attribute
Circumstance
Outcome A Count
Outcome B Count
ABC1
1
X
100
25
DEF2
2
X
1
2
DEF2
2
Y
0
2
XYZ1
1
X
33
5
XYZ1
1
Y
5
10
I've attempted some for loops to take any situation where there's a blank and replace it with the previously observed value, but I've hit such an array of errors I've decided I might be headed down the wrong path entirely.
Thank you, everybody
A:
pd.DataFrame(your ndarray).fillna(method = 'ffill')
|
Trying to create a filled dataframe from pandas crosstab
|
I've got a numpy array that looks like this, in general (it was created from a pd crosstable if that's of any significance)
Person
1to1 Person Attribute
Circumstance
Outcome A Count
Outcome B Count
ABC1
1
X
100
25
DEF2
2
X
1
2
Y
0
2
XYZ1
1
X
33
5
Y
5
10
that I'd like to turn into a pandas dataframe that looks like
Person
1to1 Person Attribute
Circumstance
Outcome A Count
Outcome B Count
ABC1
1
X
100
25
DEF2
2
X
1
2
DEF2
2
Y
0
2
XYZ1
1
X
33
5
XYZ1
1
Y
5
10
I've attempted some for loops to take any situation where there's a blank and replace it with the previously observed value, but I've hit such an array of errors I've decided I might be headed down the wrong path entirely.
Thank you, everybody
|
[
"pd.DataFrame(your ndarray).fillna(method = 'ffill')\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"numpy",
"pandas",
"pivot_table",
"python"
] |
stackoverflow_0074498391_dataframe_numpy_pandas_pivot_table_python.txt
|
Q:
Multiprocessing in python. Can a multiprocessed function call functions as multiprocesses?
Recently I have started using the multiprocessor pool executor in python to accelerate my processing.
So instead of doing a
list_of_res=[]
for n in range(a_number):
res=calculate_something(list_of sources[n])
list_of_res.append(res)
joint_results=pd.concat(list_of_res)
I do
with ProcessPoolExecutor(max_workers=8) as executor:
joint_results=pd.concat(executor.map(calculate_something,list_of_sources))
It works great.
However I've noticed that inside the calculate_something function I call the same function like 8 times, one after another, so I might as well apply a map to them instead of a loop
My question is, can I apply multiprocessing to a function that is already being called in multiprocess?
A:
yes you can have a worker process spawn another pool of workers, but it is not optimal.
each time you launch a new process it takes a few hundred milliseconds to a few seconds for this new process to initialize and start executing work (OS, disk and code dependent.)
launching a worker from a worker is just wasting the overhead of spawning the first child to begin with, and you are better off extracting the loop inside calculate_something and launching it directly within your initial executor.
a better approach is to launch your initial calculate_something using a ThreadPoolExecutor and have one shared ProcessPoolExecutor that all your thread workers will push work into, this way you can limit the number of newly created processes and avoid creating and deleting much more workers than you actually need, and it takes only a few microseconds to launch a threadpool.
this is an example of how to nest threadpool and process_pool.
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def process_worker(n):
print(n)
return n
def thread_worker(list_of_n,process_pool:ProcessPoolExecutor):
work_done = list(process_pool.map(process_worker,list_of_n))
return work_done
if __name__ == "__main__":
list_of_lists_of_n = [[1,2,3],[4,5,6]]
with ProcessPoolExecutor() as process_pool, ThreadPoolExecutor() as threadpool:
tasks = []
work_done = []
for item in list_of_lists_of_n:
tasks.append(threadpool.submit(thread_worker,item,process_pool))
for item in tasks:
work_done.append(item.result())
print(work_done)
|
Multiprocessing in python. Can a multiprocessed function call functions as multiprocesses?
|
Recently I have started using the multiprocessor pool executor in python to accelerate my processing.
So instead of doing a
list_of_res=[]
for n in range(a_number):
res=calculate_something(list_of sources[n])
list_of_res.append(res)
joint_results=pd.concat(list_of_res)
I do
with ProcessPoolExecutor(max_workers=8) as executor:
joint_results=pd.concat(executor.map(calculate_something,list_of_sources))
It works great.
However I've noticed that inside the calculate_something function I call the same function like 8 times, one after another, so I might as well apply a map to them instead of a loop
My question is, can I apply multiprocessing to a function that is already being called in multiprocess?
|
[
"yes you can have a worker process spawn another pool of workers, but it is not optimal.\neach time you launch a new process it takes a few hundred milliseconds to a few seconds for this new process to initialize and start executing work (OS, disk and code dependent.)\nlaunching a worker from a worker is just wasting the overhead of spawning the first child to begin with, and you are better off extracting the loop inside calculate_something and launching it directly within your initial executor.\na better approach is to launch your initial calculate_something using a ThreadPoolExecutor and have one shared ProcessPoolExecutor that all your thread workers will push work into, this way you can limit the number of newly created processes and avoid creating and deleting much more workers than you actually need, and it takes only a few microseconds to launch a threadpool.\nthis is an example of how to nest threadpool and process_pool.\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\n\ndef process_worker(n):\n print(n)\n return n\n\ndef thread_worker(list_of_n,process_pool:ProcessPoolExecutor):\n work_done = list(process_pool.map(process_worker,list_of_n))\n return work_done\n\nif __name__ == \"__main__\":\n list_of_lists_of_n = [[1,2,3],[4,5,6]]\n with ProcessPoolExecutor() as process_pool, ThreadPoolExecutor() as threadpool:\n tasks = []\n work_done = []\n for item in list_of_lists_of_n:\n tasks.append(threadpool.submit(thread_worker,item,process_pool))\n for item in tasks:\n work_done.append(item.result())\n print(work_done)\n\n"
] |
[
1
] |
[] |
[] |
[
"multiprocessing",
"python"
] |
stackoverflow_0074498451_multiprocessing_python.txt
|
Q:
textblob .detect_language() function not working
So I have been trying out coding and am currently finding some language detection packages and found out about textblob, but I am having some sort of proble.
This is my code:
# - *- coding: utf- 8 - *-
from textblob import TextBlob
blob = TextBlob("Comment vas-tu?")
print(blob.detect_language())
print(blob.translate(to='es'))
print(blob.translate(to='en'))
print(blob.translate(to='zh'))
and this error shows:
Traceback (most recent call last):
File "C:\Users\*****\PycharmProjects\pythonProject\main.py", line 6, in <module>
print(blob.detect_language())
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\site-packages\textblob\blob.py", line 568, in detect_language
return self.translator.detect(self.raw)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\site-packages\textblob\translate.py", line 72, in detect
response = self._request(url, host=host, type_=type_, data=data)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\site-packages\textblob\translate.py", line 92, in _request
resp = request.urlopen(req)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
response = meth(req, response)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
response = self.parent.error(
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
return self._call_chain(*args)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
result = func(*args)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found
Process finished with exit code 1
I am still a little bit of a beginner in programming... Can I ask what I can do to solve this?
A:
You can make it working by doing some changes in your translate.py file as mentioned below:
Original:
url = "http://translate.google.com/translate_a/t?client=webapp&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&ssel=0&tsel=0&kc=1"
Change above code to:
url = "http://translate.google.com/translate_a/t?client=te&format=html&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&ssel=0&tsel=0&kc=1"
For further details visit this link: "HTTPError: HTTP Error 404: Not Found" while using translation function in TextBlob
A:
Since you only need to do language detection, I see that langdetect library is a good fit:
https://pypi.org/project/langdetect/
Here is a demo on how to use it:
>>> from langdetect import detect
>>> detect('هيا بنا نلعب')
'ar'
>>>
|
textblob .detect_language() function not working
|
So I have been trying out coding and am currently finding some language detection packages and found out about textblob, but I am having some sort of proble.
This is my code:
# - *- coding: utf- 8 - *-
from textblob import TextBlob
blob = TextBlob("Comment vas-tu?")
print(blob.detect_language())
print(blob.translate(to='es'))
print(blob.translate(to='en'))
print(blob.translate(to='zh'))
and this error shows:
Traceback (most recent call last):
File "C:\Users\*****\PycharmProjects\pythonProject\main.py", line 6, in <module>
print(blob.detect_language())
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\site-packages\textblob\blob.py", line 568, in detect_language
return self.translator.detect(self.raw)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\site-packages\textblob\translate.py", line 72, in detect
response = self._request(url, host=host, type_=type_, data=data)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\site-packages\textblob\translate.py", line 92, in _request
resp = request.urlopen(req)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
response = meth(req, response)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
response = self.parent.error(
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
return self._call_chain(*args)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
result = func(*args)
File "C:\Users\*****\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found
Process finished with exit code 1
I am still a little bit of a beginner in programming... Can I ask what I can do to solve this?
|
[
"You can make it working by doing some changes in your translate.py file as mentioned below:\nOriginal:\nurl = \"http://translate.google.com/translate_a/t?client=webapp&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&ssel=0&tsel=0&kc=1\"\n\nChange above code to:\nurl = \"http://translate.google.com/translate_a/t?client=te&format=html&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&ssel=0&tsel=0&kc=1\"\n\nFor further details visit this link: \"HTTPError: HTTP Error 404: Not Found\" while using translation function in TextBlob\n",
"Since you only need to do language detection, I see that langdetect library is a good fit:\nhttps://pypi.org/project/langdetect/\nHere is a demo on how to use it:\n>>> from langdetect import detect\n>>> detect('هيا بنا نلعب')\n'ar'\n>>>\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"language_detection",
"python",
"textblob"
] |
stackoverflow_0069207838_language_detection_python_textblob.txt
|
Q:
Python - Mandatory 3 decimal places
I'm stuck on a subject.
I have a float number with a value of 0.150. Except that in my program in python, my value displays 0.15.
I want to force the display of 0.150 without converting the number into a character string.
Do you know a function, a library that could help me?
Thanks for your help !
EDIT :
Here my field Odoo declare :
posX = fields.Float(digits=(4, 3), string="Position X", required=True)
It works fine for the xml field. I have 0.150.
However, when I use a Python value dictionary, the result displayed is 0.15. This poses a problem in my program. I need 0.150 in float and not in string
Code to use my value :
values += [{
'name': element.name,
'posX': element.posX,
'posY': element.posY,
'width': element.width,
'height': element.height,
}]
Here the resut it's 0.15. Why ?
A:
Float 0,15 or 0,150 are exactly the same number for python. You can only show the extra 0 in Odoo nieuws and on pdf reports but not store it in the python variable.
For the views and pdf you can use this code:
<t t-esc="'{0:,.3f}'.format(int(values.posX))" />
|
Python - Mandatory 3 decimal places
|
I'm stuck on a subject.
I have a float number with a value of 0.150. Except that in my program in python, my value displays 0.15.
I want to force the display of 0.150 without converting the number into a character string.
Do you know a function, a library that could help me?
Thanks for your help !
EDIT :
Here my field Odoo declare :
posX = fields.Float(digits=(4, 3), string="Position X", required=True)
It works fine for the xml field. I have 0.150.
However, when I use a Python value dictionary, the result displayed is 0.15. This poses a problem in my program. I need 0.150 in float and not in string
Code to use my value :
values += [{
'name': element.name,
'posX': element.posX,
'posY': element.posY,
'width': element.width,
'height': element.height,
}]
Here the resut it's 0.15. Why ?
|
[
"Float 0,15 or 0,150 are exactly the same number for python. You can only show the extra 0 in Odoo nieuws and on pdf reports but not store it in the python variable.\nFor the views and pdf you can use this code:\n <t t-esc=\"'{0:,.3f}'.format(int(values.posX))\" />\n\n"
] |
[
0
] |
[] |
[] |
[
"odoo",
"python",
"python_3.x"
] |
stackoverflow_0074478265_odoo_python_python_3.x.txt
|
Q:
python function: how to unset a default argument value
if i have
def (a=10, b=2): ...
how do I unset a=1? I was told I need to not set 'a' but I can't find how to do that on google, it just sets itself to the default value if I don't have it, and I need to completely unset it
the library is madmom and the instruction was "If look_ahead is not set, a constant tempo throughout the whole piece is assumed. If look_ahead is set, the local tempo (in a range +/- look_ahead seconds around the actual position) is estimated and then the next beat is tracked accordingly. This procedure is repeated from the new position to the end of the piece.". https://madmom.readthedocs.io/en/v0.16/modules/features/beats.html
A:
Simply pass new values to your function on call:
def func(a=10, b=2)
print(a, b)
Call with default arguments:
func()
Call with non-default arguments:
func(20, 3)
A:
answer is that I had to set it to None and it worked
|
python function: how to unset a default argument value
|
if i have
def (a=10, b=2): ...
how do I unset a=1? I was told I need to not set 'a' but I can't find how to do that on google, it just sets itself to the default value if I don't have it, and I need to completely unset it
the library is madmom and the instruction was "If look_ahead is not set, a constant tempo throughout the whole piece is assumed. If look_ahead is set, the local tempo (in a range +/- look_ahead seconds around the actual position) is estimated and then the next beat is tracked accordingly. This procedure is repeated from the new position to the end of the piece.". https://madmom.readthedocs.io/en/v0.16/modules/features/beats.html
|
[
"Simply pass new values to your function on call:\ndef func(a=10, b=2)\n print(a, b)\n\nCall with default arguments:\nfunc()\n\nCall with non-default arguments:\nfunc(20, 3)\n\n",
"answer is that I had to set it to None and it worked\n"
] |
[
0,
-1
] |
[] |
[] |
[
"default",
"function",
"python"
] |
stackoverflow_0074498204_default_function_python.txt
|
Q:
I am getting an error of: not enough values to unpack (Expected 2, got 1) im following a tutorial but it just wont work
This is the code I have used from a tutorial
def view():
with open('My coding stuff\\passwords.txt', 'r') as f:
for line in f.readlines():
data = line.rstrip()
user, passw = data.split("|")
print("User:",user, ", password:", passw)
I have no idea what is wrong with the code
I was trying to make a password manager by following a tutorial and i am just confused
A:
Please save data in password.txt in below format
User|pwd
A:
The problem in your code that you are assigning one value in tuple user, passw instead of 2 values which is returned by data.split("|").
I think that the file you are reading doesn't contain data in the format user | pass (each record seperated by | ) so it gives you this exception Error.
I suggest to check the format of data in your file then edit your code according to it.
|
I am getting an error of: not enough values to unpack (Expected 2, got 1) im following a tutorial but it just wont work
|
This is the code I have used from a tutorial
def view():
with open('My coding stuff\\passwords.txt', 'r') as f:
for line in f.readlines():
data = line.rstrip()
user, passw = data.split("|")
print("User:",user, ", password:", passw)
I have no idea what is wrong with the code
I was trying to make a password manager by following a tutorial and i am just confused
|
[
"Please save data in password.txt in below format\nUser|pwd\n",
"The problem in your code that you are assigning one value in tuple user, passw instead of 2 values which is returned by data.split(\"|\").\nI think that the file you are reading doesn't contain data in the format user | pass (each record seperated by | ) so it gives you this exception Error.\nI suggest to check the format of data in your file then edit your code according to it.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"syntax"
] |
stackoverflow_0074498485_python_syntax.txt
|
Q:
Pandas - convert integer to bytestring and update single fields
Problem: I receive from a machine errorcodes as integer (every minute). This errorcode represents a bytestring and every bit stands for a specific error. For analytics I need this bits
inside pandas as separate columns. I'm struggling doing this.
def converttobinary(num, length=3):
binary_string_list = list(format(num, '0{}b'.format(length)))
return [int(digit) for digit in binary_string_list]
df = pd.DataFrame({'errorcode': [1,2,3],
'errorcodelist': ['', '', ''],
'errorcode01': ['', '', ''],
'errorcode02': ['', '', ''],
'errorcode03': ['', '', ''],})
df['errorcodelist'] = df.apply(lambda row : converttobinary(row['errorcode']), axis = 1)
print(df)
Result (by now):
errorcode errorcodelist errorcode01 errorcode02 errorcode03
1 [0, 0, 1]
2 [0, 1, 0]
3 [0, 1, 1]
Expected Result:
errorcode errorcodelist errorcode01 errorcode02 errorcode03
1 [0, 0, 1] 1 0 0
2 [0, 1, 0] 0 1 0
3 [0, 1, 1] 0 1 1
Has anyone an idea, how to get the expected result?
A:
You can use another apply call to extract the element of the list:
df['errorcode01'] = df.apply(lambda row : row['errorcodelist'][2], axis = 1)
df['errorcode02'] = df.apply(lambda row : row['errorcodelist'][1], axis = 1)
df['errorcode03'] = df.apply(lambda row : row['errorcodelist'][0], axis = 1)
Or you could fill the other columns during dataframe creation:
from collections import defaultdict
errorcodes = [1,2,3]
# create dataframe
obj = defaultdict(list)
bit_length = 3
for code in errorcodes:
obj["errorcode"].append(code)
binary_list = converttobinary(code, length=bit_length)
obj["errorcodelist"].append(binary_list)
# add the bits to the corresponding list
for i, bit in enumerate(reversed(binary_list)):
obj[f"bit{i+1:02d}"].append(bit)
df = pd.DataFrame(obj)
|
Pandas - convert integer to bytestring and update single fields
|
Problem: I receive from a machine errorcodes as integer (every minute). This errorcode represents a bytestring and every bit stands for a specific error. For analytics I need this bits
inside pandas as separate columns. I'm struggling doing this.
def converttobinary(num, length=3):
binary_string_list = list(format(num, '0{}b'.format(length)))
return [int(digit) for digit in binary_string_list]
df = pd.DataFrame({'errorcode': [1,2,3],
'errorcodelist': ['', '', ''],
'errorcode01': ['', '', ''],
'errorcode02': ['', '', ''],
'errorcode03': ['', '', ''],})
df['errorcodelist'] = df.apply(lambda row : converttobinary(row['errorcode']), axis = 1)
print(df)
Result (by now):
errorcode errorcodelist errorcode01 errorcode02 errorcode03
1 [0, 0, 1]
2 [0, 1, 0]
3 [0, 1, 1]
Expected Result:
errorcode errorcodelist errorcode01 errorcode02 errorcode03
1 [0, 0, 1] 1 0 0
2 [0, 1, 0] 0 1 0
3 [0, 1, 1] 0 1 1
Has anyone an idea, how to get the expected result?
|
[
"You can use another apply call to extract the element of the list:\ndf['errorcode01'] = df.apply(lambda row : row['errorcodelist'][2], axis = 1)\ndf['errorcode02'] = df.apply(lambda row : row['errorcodelist'][1], axis = 1)\ndf['errorcode03'] = df.apply(lambda row : row['errorcodelist'][0], axis = 1)\n\nOr you could fill the other columns during dataframe creation:\nfrom collections import defaultdict\nerrorcodes = [1,2,3]\n\n# create dataframe\nobj = defaultdict(list)\nbit_length = 3\nfor code in errorcodes:\n obj[\"errorcode\"].append(code)\n\n binary_list = converttobinary(code, length=bit_length)\n obj[\"errorcodelist\"].append(binary_list)\n \n # add the bits to the corresponding list\n for i, bit in enumerate(reversed(binary_list)):\n obj[f\"bit{i+1:02d}\"].append(bit)\n\ndf = pd.DataFrame(obj)\n\n"
] |
[
1
] |
[] |
[] |
[
"arrays",
"pandas",
"python"
] |
stackoverflow_0074498555_arrays_pandas_python.txt
|
Q:
Pythonic approach to keeping track of cached variable/function dependencies
I have a system with a library which includes many functions/methods that are slow, for example SQL queries or computational expensive algorithms. Therefore, I have identified those that can benefit from caching and use the lru_cache or cache decorators from functools. I additionally use cache_clear() to clear caches when a function's/method's dependent data/parameters have changed.
This is simple when the number of dependent data or parameters are small, for example when testing, however, when this approach is scaled to include data dependent on data from other cached function/methods, keeping track of these dependent data/parameters' changes and appropriately clearing cache(s) is tricky. See code example 1, which includes some scenarios of when dependent data are changed and the clearing of caches. In this case I must manually keep track and place cache_clear() on the appropriate functions/methods.
In an attempt to have a more systematic approach to tracking data dependencies and clearing caches I have a simple class to manage this. See code example 2 for this updated approach. I have split the problem in to two halves, 1) declaring data dependencies, and 2) notifying the manager when a variable is changed. The manager then clears any caches for functions/methods that depend on the changed variable.
This approach relies on using string descriptions of data. Ideally, so that I do not need to remember/use the exact same string descriptions, actual references to data would be used, for example with id(), however when data are updated the reference can change. See code example 3. The reference stored when declaring the dependency is different after the change to b.Y so the manager can't find which caches need to be cleared.
Is there a common (more 'pythonic') solution for this problem? or
Is there a way to replace the string descriptions with object references that change when objects change?
Example 1:
from functools import lru_cache, cache
class A():
def __init__(self):
self._X = 0
self.Y = (1, 2, 3)
@classmethod
def set_up(cls, z):
cls.Z = z
@property
@cache
def X(self):
return self._X
@X.setter
def X(self, new_X):
self._X = new_X
# A.X.fget.cache_clear()
@cache
def N(self):
return len(str(self.X))
@lru_cache(maxsize=None, typed=True)
def bar(self, y):
return self.Y * y
@cache
def foobar(self):
return self.bar(self.X) * self.N()
@lru_cache(maxsize=10, typed=True)
def func(ans):
ans *= A.Z
return ans
a = A()
a.set_up(3)
# Case 1
# X is changed, so both X and N() need to be cleared
assert a.X == 0
assert a.N() == 1
a.X = 20
assert a.X == 0
assert a.N() == 1
A.X.fget.cache_clear() # could put this in the property setter
a.N.cache_clear()
assert a.X == 20
assert a.N() == 2
# Case 2
# Y is changed so bar() needs to be cleared
assert a.bar(4) == (1, 2, 3) * 4
a.Y = (1, 2, 3, 4, 5, 6)
assert a.bar(4) == (1, 2, 3) * 4
a.bar.cache_clear()
assert a.bar(4) == (1, 2, 3, 4, 5, 6) * 4
# Case 3
# if either a.X or a.Y changes, one or more of X, N(), bar() and foobar()
# need to be cleared (I can simplify to all - commented lines)
assert a.foobar() == (1, 2, 3, 4, 5, 6) * 20 * 2
a.X = 500
a.Y = (7, 8, 9)
assert a.foobar() == (1, 2, 3, 4, 5, 6) * 20 * 2
A.X.fget.cache_clear()
a.N.cache_clear()
a.bar.cache_clear()
a.foobar.cache_clear()
assert a.foobar() == (7, 8, 9) * 500 * 3
# Case 4
# if A.Z changes, func() needs to be cleared
assert func(a.foobar()) == ((7, 8, 9) * 500 * 3) * 3
a.set_up(4)
assert func(a.foobar()) == ((7, 8, 9) * 500 * 3) * 3
func.cache_clear()
assert func(a.foobar()) == ((7, 8, 9) * 500 * 3) * 4
Example 2:
from collections import defaultdict
class CacheManager():
def __init__(self):
self._caches = defaultdict(list)
def add_dependency(self, dependent, dependee):
# dependent: that which relies on another for support
# dependee: that which the dependent relies on
self._caches[dependee].append(dependent)
def changed(self, dependee):
for d in dependee:
for f in self._caches[d]:
f.cache_clear()
cache_manager= CacheManager()
cache_manager.add_dependency(func, "A.Z")
class B(A):
def __init__(self, cashe_manager ):
super().__init__()
self._cache_manager = cache_manager
self._cache_manager.add_dependency(B.X.fget, "b.X")
self._cache_manager.add_dependency(self.N, "b.X")
self._cache_manager.add_dependency(self.bar, "b.Y")
self._cache_manager.add_dependency(self.foobar, "b.X")
self._cache_manager.add_dependency(self.foobar, "b.N")
b = B(cache_manager )
# Case 1
# X is changed, so both X and N() need to be cleared
assert b.X == 0
assert b.N() == 1
b.X = 20
assert b.X == 0
assert b.N() == 1
cache_manager.changed(("b.X",))
assert b.X == 20
assert b.N() == 2
# Case 2
# Y is changed so bar() needs to be cleared
assert b.bar(4) == (1, 2, 3) * 4
b.Y = (1, 2, 3, 4, 5, 6)
assert b.bar(4) == (1, 2, 3) * 4
cache_manager.changed(("b.Y",))
assert b.bar(4) == (1, 2, 3, 4, 5, 6) * 4
# Case 3
# if either a.X or a.Y changes, one or more of X, N(), bar() and foobar()
# need to be cleared (I can simplify to all - commented lines)
assert b.foobar() == (1, 2, 3, 4, 5, 6) * 20 * 2
b.X = 500
b.Y = (7, 8, 9)
assert b.foobar() == (1, 2, 3, 4, 5, 6) * 20 * 2
cache_manager.changed(("b.X", "b.Y"))
assert b.foobar() == (7, 8, 9) * 500 * 3
# Case 4
# a new instance of A is instantiated so func() needs to be cleared
assert func(b.foobar()) == ((7, 8, 9) * 500 * 3) * 4
a = A()
a.set_up(2)
assert func(b.foobar()) == ((7, 8, 9) * 500 * 3) * 4
cache_manager.changed(("A.Z",))
assert func(b.foobar()) == ((7, 8, 9) * 500 * 3) * 2
Example 3:
class CacheManager():
def __init__(self):
self._caches = defaultdict(list)
def add_dependency(self, dependent, dependee):
# dependent: that which relies on another for support
# dependee: that which the dependent relies on
print(f"Adding {dependee} with id {id(dependee)}")
self._caches[id(dependee)].append(dependent)
def changed(self, dependee):
print(f"{dependee} changed")
for d in dependee:
print(f"for dependee {d}, {self._caches[id(d)]} caches ... ")
for f in self._caches[id(d)]:
print(f"... clearing cache of {d} with id {id(d)}")
f.cache_clear()
cache_manager = CacheManager()
cache_manager.add_dependency(func, A.Z)
class B(A):
def __init__(self, cache_manager):
super().__init__()
self._cache_manager= cache_manager
self._cache_manager.add_dependency(B.X.fget, self.X)
self._cache_manager.add_dependency(self.N, self.X)
self._cache_manager.add_dependency(self.bar, self.Y)
self._cache_manager.add_dependency(self.foobar, self.X)
self._cache_manager.add_dependency(self.foobar, self.N)
b = B(cache_manager)
# Case 1
# X is changed, so both X and N() need to be cleared
assert b.X == 0
assert b.N() == 1
b.X = 20
assert b.X == 0
assert b.N() == 1
cache_manager.changed((b.X,))
assert b.X == 20
assert b.N() == 2
# Case 2
# Y is changed so bar() needs to be cleared
assert b.bar(4) == (1, 2, 3) * 4
b.Y = (1, 2, 3, 4, 5, 6)
assert b.bar(4) == (1, 2, 3) * 4
cache_manager.changed((b.Y,))
assert b.bar(4) == (1, 2, 3, 4, 5, 6) * 4 # <---- Fails
A:
I think the idea of using the cache decorators on non-idempotent functions is a bit of an abuse of the API. The idea is generally that you can cache the values on the objects because there are no side-effects which would require the outputs to change on subsequent calls.
In the example for class A you provide a method for getting the cached result of property X, which relies on a mutable state of attribute A._X. In this case, rather than caching on the property, a better alternative might be to have that property call to an idempotent function which takes A._X as an argument, which would lead to mutations of A._X causing a cache miss and a recalculation of the value:
from functools import cache
@cache
def _calculate_x(a_x):
return a_x
class A():
def __init__(self):
self._X = 0
@property
def X(self):
return _calculate_x(self._X)
a = A()
assert a.X == 0
a._X = 20
assert a.X == 20
If the usecase is simply for testing and clearing the cache, I would probably opt for a simpler approach where on each test-case you can easily clear all caches regardless of what dependencies are changed. This ensures that each test run with a blank slate.
One way to do this could be to create wrapper around creating cache objects which stores them in a global list before returning them to the caller. e.g.
from functools import cache
_caches = []
def application_cache(func):
cached_func = cache(func)
_caches.append(cached_func)
return cached_func
def cache_clear():
for func_cache in _caches:
func_cache.cache_clear()
...
class A:
def __init__(self):
self._X = 0
@property
@application_cache
def X(self):
return self._X
a = A()
assert a.X == 0
a._X = 20
assert a.X == 0
cache_clear()
assert a.X == 20
This would however result in memory leaks for short lived object instances that create caches, as they are never cleared from the _caches. A reference to the wrapped method from _caches would lead to the associated instance never being GC'd. If that is a concern, then in the real production code, you could have:
from functools import cache
def application_cache(func):
return cache(func)
In your test setup you would patch the application_cache function to use the previous implementation with the global _caches list. This would allow you to use the real cache methods in production, but provide the cache_clear method that globally clears all cached data from within your tests.
|
Pythonic approach to keeping track of cached variable/function dependencies
|
I have a system with a library which includes many functions/methods that are slow, for example SQL queries or computational expensive algorithms. Therefore, I have identified those that can benefit from caching and use the lru_cache or cache decorators from functools. I additionally use cache_clear() to clear caches when a function's/method's dependent data/parameters have changed.
This is simple when the number of dependent data or parameters are small, for example when testing, however, when this approach is scaled to include data dependent on data from other cached function/methods, keeping track of these dependent data/parameters' changes and appropriately clearing cache(s) is tricky. See code example 1, which includes some scenarios of when dependent data are changed and the clearing of caches. In this case I must manually keep track and place cache_clear() on the appropriate functions/methods.
In an attempt to have a more systematic approach to tracking data dependencies and clearing caches I have a simple class to manage this. See code example 2 for this updated approach. I have split the problem in to two halves, 1) declaring data dependencies, and 2) notifying the manager when a variable is changed. The manager then clears any caches for functions/methods that depend on the changed variable.
This approach relies on using string descriptions of data. Ideally, so that I do not need to remember/use the exact same string descriptions, actual references to data would be used, for example with id(), however when data are updated the reference can change. See code example 3. The reference stored when declaring the dependency is different after the change to b.Y so the manager can't find which caches need to be cleared.
Is there a common (more 'pythonic') solution for this problem? or
Is there a way to replace the string descriptions with object references that change when objects change?
Example 1:
from functools import lru_cache, cache
class A():
def __init__(self):
self._X = 0
self.Y = (1, 2, 3)
@classmethod
def set_up(cls, z):
cls.Z = z
@property
@cache
def X(self):
return self._X
@X.setter
def X(self, new_X):
self._X = new_X
# A.X.fget.cache_clear()
@cache
def N(self):
return len(str(self.X))
@lru_cache(maxsize=None, typed=True)
def bar(self, y):
return self.Y * y
@cache
def foobar(self):
return self.bar(self.X) * self.N()
@lru_cache(maxsize=10, typed=True)
def func(ans):
ans *= A.Z
return ans
a = A()
a.set_up(3)
# Case 1
# X is changed, so both X and N() need to be cleared
assert a.X == 0
assert a.N() == 1
a.X = 20
assert a.X == 0
assert a.N() == 1
A.X.fget.cache_clear() # could put this in the property setter
a.N.cache_clear()
assert a.X == 20
assert a.N() == 2
# Case 2
# Y is changed so bar() needs to be cleared
assert a.bar(4) == (1, 2, 3) * 4
a.Y = (1, 2, 3, 4, 5, 6)
assert a.bar(4) == (1, 2, 3) * 4
a.bar.cache_clear()
assert a.bar(4) == (1, 2, 3, 4, 5, 6) * 4
# Case 3
# if either a.X or a.Y changes, one or more of X, N(), bar() and foobar()
# need to be cleared (I can simplify to all - commented lines)
assert a.foobar() == (1, 2, 3, 4, 5, 6) * 20 * 2
a.X = 500
a.Y = (7, 8, 9)
assert a.foobar() == (1, 2, 3, 4, 5, 6) * 20 * 2
A.X.fget.cache_clear()
a.N.cache_clear()
a.bar.cache_clear()
a.foobar.cache_clear()
assert a.foobar() == (7, 8, 9) * 500 * 3
# Case 4
# if A.Z changes, func() needs to be cleared
assert func(a.foobar()) == ((7, 8, 9) * 500 * 3) * 3
a.set_up(4)
assert func(a.foobar()) == ((7, 8, 9) * 500 * 3) * 3
func.cache_clear()
assert func(a.foobar()) == ((7, 8, 9) * 500 * 3) * 4
Example 2:
from collections import defaultdict
class CacheManager():
def __init__(self):
self._caches = defaultdict(list)
def add_dependency(self, dependent, dependee):
# dependent: that which relies on another for support
# dependee: that which the dependent relies on
self._caches[dependee].append(dependent)
def changed(self, dependee):
for d in dependee:
for f in self._caches[d]:
f.cache_clear()
cache_manager= CacheManager()
cache_manager.add_dependency(func, "A.Z")
class B(A):
def __init__(self, cashe_manager ):
super().__init__()
self._cache_manager = cache_manager
self._cache_manager.add_dependency(B.X.fget, "b.X")
self._cache_manager.add_dependency(self.N, "b.X")
self._cache_manager.add_dependency(self.bar, "b.Y")
self._cache_manager.add_dependency(self.foobar, "b.X")
self._cache_manager.add_dependency(self.foobar, "b.N")
b = B(cache_manager )
# Case 1
# X is changed, so both X and N() need to be cleared
assert b.X == 0
assert b.N() == 1
b.X = 20
assert b.X == 0
assert b.N() == 1
cache_manager.changed(("b.X",))
assert b.X == 20
assert b.N() == 2
# Case 2
# Y is changed so bar() needs to be cleared
assert b.bar(4) == (1, 2, 3) * 4
b.Y = (1, 2, 3, 4, 5, 6)
assert b.bar(4) == (1, 2, 3) * 4
cache_manager.changed(("b.Y",))
assert b.bar(4) == (1, 2, 3, 4, 5, 6) * 4
# Case 3
# if either a.X or a.Y changes, one or more of X, N(), bar() and foobar()
# need to be cleared (I can simplify to all - commented lines)
assert b.foobar() == (1, 2, 3, 4, 5, 6) * 20 * 2
b.X = 500
b.Y = (7, 8, 9)
assert b.foobar() == (1, 2, 3, 4, 5, 6) * 20 * 2
cache_manager.changed(("b.X", "b.Y"))
assert b.foobar() == (7, 8, 9) * 500 * 3
# Case 4
# a new instance of A is instantiated so func() needs to be cleared
assert func(b.foobar()) == ((7, 8, 9) * 500 * 3) * 4
a = A()
a.set_up(2)
assert func(b.foobar()) == ((7, 8, 9) * 500 * 3) * 4
cache_manager.changed(("A.Z",))
assert func(b.foobar()) == ((7, 8, 9) * 500 * 3) * 2
Example 3:
class CacheManager():
def __init__(self):
self._caches = defaultdict(list)
def add_dependency(self, dependent, dependee):
# dependent: that which relies on another for support
# dependee: that which the dependent relies on
print(f"Adding {dependee} with id {id(dependee)}")
self._caches[id(dependee)].append(dependent)
def changed(self, dependee):
print(f"{dependee} changed")
for d in dependee:
print(f"for dependee {d}, {self._caches[id(d)]} caches ... ")
for f in self._caches[id(d)]:
print(f"... clearing cache of {d} with id {id(d)}")
f.cache_clear()
cache_manager = CacheManager()
cache_manager.add_dependency(func, A.Z)
class B(A):
def __init__(self, cache_manager):
super().__init__()
self._cache_manager= cache_manager
self._cache_manager.add_dependency(B.X.fget, self.X)
self._cache_manager.add_dependency(self.N, self.X)
self._cache_manager.add_dependency(self.bar, self.Y)
self._cache_manager.add_dependency(self.foobar, self.X)
self._cache_manager.add_dependency(self.foobar, self.N)
b = B(cache_manager)
# Case 1
# X is changed, so both X and N() need to be cleared
assert b.X == 0
assert b.N() == 1
b.X = 20
assert b.X == 0
assert b.N() == 1
cache_manager.changed((b.X,))
assert b.X == 20
assert b.N() == 2
# Case 2
# Y is changed so bar() needs to be cleared
assert b.bar(4) == (1, 2, 3) * 4
b.Y = (1, 2, 3, 4, 5, 6)
assert b.bar(4) == (1, 2, 3) * 4
cache_manager.changed((b.Y,))
assert b.bar(4) == (1, 2, 3, 4, 5, 6) * 4 # <---- Fails
|
[
"I think the idea of using the cache decorators on non-idempotent functions is a bit of an abuse of the API. The idea is generally that you can cache the values on the objects because there are no side-effects which would require the outputs to change on subsequent calls.\nIn the example for class A you provide a method for getting the cached result of property X, which relies on a mutable state of attribute A._X. In this case, rather than caching on the property, a better alternative might be to have that property call to an idempotent function which takes A._X as an argument, which would lead to mutations of A._X causing a cache miss and a recalculation of the value:\nfrom functools import cache\n\n@cache\ndef _calculate_x(a_x):\n return a_x\n\n\nclass A():\n def __init__(self):\n self._X = 0\n\n @property\n def X(self):\n return _calculate_x(self._X)\n\n\na = A()\n\nassert a.X == 0\na._X = 20\nassert a.X == 20\n\nIf the usecase is simply for testing and clearing the cache, I would probably opt for a simpler approach where on each test-case you can easily clear all caches regardless of what dependencies are changed. This ensures that each test run with a blank slate.\nOne way to do this could be to create wrapper around creating cache objects which stores them in a global list before returning them to the caller. e.g.\nfrom functools import cache\n\n_caches = []\n\ndef application_cache(func):\n cached_func = cache(func)\n _caches.append(cached_func)\n return cached_func\n\ndef cache_clear():\n for func_cache in _caches:\n func_cache.cache_clear()\n\n...\n\nclass A:\n def __init__(self):\n self._X = 0\n\n @property\n @application_cache\n def X(self):\n return self._X\n\n\na = A()\n\nassert a.X == 0\na._X = 20\nassert a.X == 0\n\ncache_clear()\nassert a.X == 20\n\nThis would however result in memory leaks for short lived object instances that create caches, as they are never cleared from the _caches. A reference to the wrapped method from _caches would lead to the associated instance never being GC'd. If that is a concern, then in the real production code, you could have:\nfrom functools import cache\n\ndef application_cache(func):\n return cache(func)\n\nIn your test setup you would patch the application_cache function to use the previous implementation with the global _caches list. This would allow you to use the real cache methods in production, but provide the cache_clear method that globally clears all cached data from within your tests.\n"
] |
[
3
] |
[] |
[] |
[
"caching",
"dependencies",
"dependency_management",
"lru",
"python"
] |
stackoverflow_0074386469_caching_dependencies_dependency_management_lru_python.txt
|
Q:
How to method-chain `ffill(axis=1)` in a dataframe
I would like to fill column b of a dataframe with values from a in case b is nan, and I would like to do it in a method chain, but I cannot figure out how to do this.
The following works
import numpy as np
import pandas as pd
df = pd.DataFrame(
{"a": [1, 2, 3, 4], "b": [10, np.nan, np.nan, 40], "c": ["a", "b", "c", "d"]}
)
df["b"] = df[["a", "b"]].ffill(axis=1)["b"]
print(df.to_markdown())
| | a | b | c |
|---:|----:|----:|:----|
| 0 | 1 | 10 | a |
| 1 | 2 | 2 | b |
| 2 | 3 | 3 | c |
| 3 | 4 | 40 | d |
but is not method-chained. Thanks a lot for the help!
A:
df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [10, np.nan, np.nan, 40], "c": ["a", "b", "c", "d"]})
df['b'] = df.b.fillna(df.a)
| | a | b | c |
|---:|----:|----:|:----|
| 0 | 1 | 10 | a |
| 1 | 2 | 2 | b |
| 2 | 3 | 3 | c |
| 3 | 4 | 40 | d |
A:
One solution I have found is by using the pyjanitor library:
import pandas as pd
import pyjanitor
df = pd.DataFrame(
{"a": [1, 2, 3, 4], "b": [10, np.nan, np.nan, 40], "c": ["a", "b", "c", "d"]}
)
df.case_when(
lambda x: x["b"].isna(), lambda x: x["a"], lambda x: x["b"], column_name="b"
)
Here, the case_when(...) can be integrated into a chain of manipulations and we still keep the whole dataframe in the chain.
I wonder how this could be accomplished without pyjanitor.
|
How to method-chain `ffill(axis=1)` in a dataframe
|
I would like to fill column b of a dataframe with values from a in case b is nan, and I would like to do it in a method chain, but I cannot figure out how to do this.
The following works
import numpy as np
import pandas as pd
df = pd.DataFrame(
{"a": [1, 2, 3, 4], "b": [10, np.nan, np.nan, 40], "c": ["a", "b", "c", "d"]}
)
df["b"] = df[["a", "b"]].ffill(axis=1)["b"]
print(df.to_markdown())
| | a | b | c |
|---:|----:|----:|:----|
| 0 | 1 | 10 | a |
| 1 | 2 | 2 | b |
| 2 | 3 | 3 | c |
| 3 | 4 | 40 | d |
but is not method-chained. Thanks a lot for the help!
|
[
"df = pd.DataFrame({\"a\": [1, 2, 3, 4], \"b\": [10, np.nan, np.nan, 40], \"c\": [\"a\", \"b\", \"c\", \"d\"]})\ndf['b'] = df.b.fillna(df.a)\n \n| | a | b | c |\n|---:|----:|----:|:----|\n| 0 | 1 | 10 | a |\n| 1 | 2 | 2 | b |\n| 2 | 3 | 3 | c |\n| 3 | 4 | 40 | d |\n\n",
"One solution I have found is by using the pyjanitor library:\nimport pandas as pd\nimport pyjanitor \n\ndf = pd.DataFrame(\n {\"a\": [1, 2, 3, 4], \"b\": [10, np.nan, np.nan, 40], \"c\": [\"a\", \"b\", \"c\", \"d\"]}\n)\ndf.case_when(\n lambda x: x[\"b\"].isna(), lambda x: x[\"a\"], lambda x: x[\"b\"], column_name=\"b\"\n)\n\nHere, the case_when(...) can be integrated into a chain of manipulations and we still keep the whole dataframe in the chain.\nI wonder how this could be accomplished without pyjanitor.\n"
] |
[
0,
0
] |
[] |
[] |
[
"method_chaining",
"pandas",
"python"
] |
stackoverflow_0074493618_method_chaining_pandas_python.txt
|
Q:
python Scrapy amazon fails to return all reviews
I want to scrape the amazon review from amazon, the return result is always none,however,there are product review can correctly returned. what is the problem?
import scrapy
from scrapy import Selector, Request
from test1.items import Test1Item
class hiSpider(scrapy.Spider):
name = 'hello'
def start_requests(self):
urls = ['https://www.amazon.com/s?k=t-shirts+for+men&page=2&crid=2GLXHBOKVG093&qid=1668745933&sprefix=t-shirts+for+men%2Caps%2C280&ref=sr_pg_1']
def parse(self, response):
sel = Selector(response)
items = sel.css('span[data-component-type="s-search-results"]>div>div[data-component-type="s-search-result"]')
for item in items:
help = Test1Item()
detail_url = item.css('a[class="a-link-normal s-no-outline"]::attr(href)').get()
url = response.urljoin(detail_url)
yield Request(url=url,
callback=self.parse_detail,
cb_kwargs={'item': help}
)
def parse_detail(self,response,**kwargs):
help = kwargs['item']
sel = Selector(response)
comment_url = response.request.url
product_id = comment_url.split("dp/")[1].split("/")[0]
print(product_id)
nexturl = f'https://www.amazon.com/product-reviews/{product_id}/ref=cm_cr_arp_d_viewopt_srt?sortBy=recent&pageNumber=1'
yield Request(url=nexturl,
callback=self.parse_detail1,
cb_kwargs={'item': help}
)
def parse_detail1(self, response, **kwargs):
help = kwargs['item']
sel = Selector(response)
help["name"] = sel.css('a[data-hook="review-title"]>span::text').get()
yield help
I want to return all the reviews, how can I do that
A:
Test this code.
import scrapy
from scrapy import Request
from test1.items import Test1Item
class hiSpider(scrapy.Spider):
name = 'hello'
# if you use ( statr_urls ) you don't need start_request() function
def start_requests(self):
url = 'https://www.amazon.com/s?k=t-shirts+for+men&page=2&crid=2GLXHBOKVG093&qid=1668745933&sprefix=t-shirts+for+men%2Caps%2C280&ref=sr_pg_1'
yield scrapy.Request(
url=url,
callback=self.parse
)
def parse(self, response):
# you dont need Selector here because response is a selector object
items = response.css('your css selector')
help = Test1Item()
for item in items:
detail_url = item.css('your css selector').get()
url = response.urljoin(detail_url)
yield Request(url=url,
callback=self.parse_detail,
cb_kwargs={'item': help}
)
def parse_detail(self,response,**kwargs):
help = response.cb_kwargs['item'] # response.cb_kwargs['item'] not kwargs['item']
comment_url = response.request.url
product_id = comment_url.split("dp/")[1].split("/")[0]
print(product_id)
nexturl = f'https://www.amazon.com/product-reviews/{product_id}/ref=cm_cr_arp_d_viewopt_srt?sortBy=recent&pageNumber=1'
yield Request(url=nexturl,
callback=self.parse_detail1,
cb_kwargs={'item': help}
)
def parse_detail1(self, response, **kwargs):
help = response.cb_kwargs['item']
help["name"] = response.css('your css selector').get()
yield help
|
python Scrapy amazon fails to return all reviews
|
I want to scrape the amazon review from amazon, the return result is always none,however,there are product review can correctly returned. what is the problem?
import scrapy
from scrapy import Selector, Request
from test1.items import Test1Item
class hiSpider(scrapy.Spider):
name = 'hello'
def start_requests(self):
urls = ['https://www.amazon.com/s?k=t-shirts+for+men&page=2&crid=2GLXHBOKVG093&qid=1668745933&sprefix=t-shirts+for+men%2Caps%2C280&ref=sr_pg_1']
def parse(self, response):
sel = Selector(response)
items = sel.css('span[data-component-type="s-search-results"]>div>div[data-component-type="s-search-result"]')
for item in items:
help = Test1Item()
detail_url = item.css('a[class="a-link-normal s-no-outline"]::attr(href)').get()
url = response.urljoin(detail_url)
yield Request(url=url,
callback=self.parse_detail,
cb_kwargs={'item': help}
)
def parse_detail(self,response,**kwargs):
help = kwargs['item']
sel = Selector(response)
comment_url = response.request.url
product_id = comment_url.split("dp/")[1].split("/")[0]
print(product_id)
nexturl = f'https://www.amazon.com/product-reviews/{product_id}/ref=cm_cr_arp_d_viewopt_srt?sortBy=recent&pageNumber=1'
yield Request(url=nexturl,
callback=self.parse_detail1,
cb_kwargs={'item': help}
)
def parse_detail1(self, response, **kwargs):
help = kwargs['item']
sel = Selector(response)
help["name"] = sel.css('a[data-hook="review-title"]>span::text').get()
yield help
I want to return all the reviews, how can I do that
|
[
"Test this code.\nimport scrapy\nfrom scrapy import Request\nfrom test1.items import Test1Item\n\nclass hiSpider(scrapy.Spider):\n\n\n name = 'hello'\n\n # if you use ( statr_urls ) you don't need start_request() function \n\n def start_requests(self):\n url = 'https://www.amazon.com/s?k=t-shirts+for+men&page=2&crid=2GLXHBOKVG093&qid=1668745933&sprefix=t-shirts+for+men%2Caps%2C280&ref=sr_pg_1'\n yield scrapy.Request(\n url=url,\n callback=self.parse\n )\n \n def parse(self, response):\n # you dont need Selector here because response is a selector object \n\n items = response.css('your css selector')\n help = Test1Item()\n\n for item in items:\n detail_url = item.css('your css selector').get()\n url = response.urljoin(detail_url)\n yield Request(url=url,\n callback=self.parse_detail,\n cb_kwargs={'item': help}\n\n )\n\n\n def parse_detail(self,response,**kwargs):\n help = response.cb_kwargs['item'] # response.cb_kwargs['item'] not kwargs['item']\n\n comment_url = response.request.url\n product_id = comment_url.split(\"dp/\")[1].split(\"/\")[0]\n\n print(product_id)\n\n nexturl = f'https://www.amazon.com/product-reviews/{product_id}/ref=cm_cr_arp_d_viewopt_srt?sortBy=recent&pageNumber=1'\n\n yield Request(url=nexturl,\n callback=self.parse_detail1,\n cb_kwargs={'item': help}\n )\n\n\n def parse_detail1(self, response, **kwargs):\n help = response.cb_kwargs['item']\n help[\"name\"] = response.css('your css selector').get()\n yield help\n\n"
] |
[
0
] |
[] |
[] |
[
"amazon",
"python",
"scrapy",
"web_crawler"
] |
stackoverflow_0074486673_amazon_python_scrapy_web_crawler.txt
|
Q:
check if a string has any other character than '*'
I'd like to check whether a certain string contains any character other than '*'. for example:
str1 = "aaa*bbb" will return false
str2= "***" will return true
how can I do that?
this is what I tried and it didn't work
A:
You can use all() to perform the check:
def check(s, char="*"):
return all(ch == char for ch in s)
print(check("aaa*bbb"))
print(check("***"))
Prints:
False
True
|
check if a string has any other character than '*'
|
I'd like to check whether a certain string contains any character other than '*'. for example:
str1 = "aaa*bbb" will return false
str2= "***" will return true
how can I do that?
this is what I tried and it didn't work
|
[
"You can use all() to perform the check:\ndef check(s, char=\"*\"):\n return all(ch == char for ch in s)\n\n\nprint(check(\"aaa*bbb\"))\nprint(check(\"***\"))\n\nPrints:\nFalse\nTrue\n\n"
] |
[
2
] |
[] |
[] |
[
"function",
"python",
"string"
] |
stackoverflow_0074498625_function_python_string.txt
|
Q:
How to define multiple API endpoints in FastAPI with different paths but the same path parameter?
I'm working on a project which uses FastAPI. My router file looks like the following:
# GET API Endpoint 1
@router.get("/project/{project_id}/{employee_id}")
async def method_one(
project_id: str, organization_id: str, session: AsyncSession = Depends(get_db)
):
try:
return await CustomController.method_one(
session, project_id, employee_id
)
except Exception as e:
return custom_exception_handler(e)
# GET API Endpoint 2
@router.get("/project/details/{project_id}")
async def method_two(
project_id: str, session: AsyncSession = Depends(get_db)
):
try:
return await CustomController.method_two(
session=session, project_id=project_id
)
except Exception as e:
return custom_exception_handler(e)
# GET API Endpoint 3
@router.get("/project/metadata/{project_id}")
async def method_three(
project_id: str, session: AsyncSession = Depends(get_db)
):
try:
return await CustomController.method_three(
session=session, project_id=project_id
)
except Exception as e:
return custom_exception_handler(e)
The obvious expectation of workflow here is: when each of these API endpoints are triggered with their required path parameters, the controller method is executed, as defined in their body.
However, for some strange reason, when API endpoints 2 and 3 are triggered, they are executing the controller method in endpoint 1, i.e., CustomController.method_one().
Upon adding some print() statements in the method method_one() of the router, I've observed that method_one() is being called when API endpoint 2 is called, while it is actually supposed to call method_two() in the router. Same is the case with API endpoint 3.
I'm unable to understand why the method body of method_one() is getting executed, when API endpoints 2 and 3 are triggered. Am I missing out something on configuration, or something - can someone please correct me? Thanks!
A:
In FastAPI, as described in this answer, because endpoints are evaluated in order (see order matters), it makes sure that the endpoint you defined first in your app—in this case, that is, /project/{project_id}/...—will be evaluated first. Hence, every time you call one of the other two endpoints, i.e., /project/details/... and /project/metadata/..., the first endpoint is triggered, using details or metadata as the project_id parameter.
Solution
Thus, you need to make sure that the other two endpoints are declared before the one for /project/{project_id}/.... For example:
# GET API Endpoint 1
@router.get("/project/details/{project_id}")
# ...
# GET API Endpoint 2
@router.get("/project/metadata/{project_id}")
# ...
# GET API Endpoint 3
@router.get("/project/{project_id}/{employee_id}")
# ...
|
How to define multiple API endpoints in FastAPI with different paths but the same path parameter?
|
I'm working on a project which uses FastAPI. My router file looks like the following:
# GET API Endpoint 1
@router.get("/project/{project_id}/{employee_id}")
async def method_one(
project_id: str, organization_id: str, session: AsyncSession = Depends(get_db)
):
try:
return await CustomController.method_one(
session, project_id, employee_id
)
except Exception as e:
return custom_exception_handler(e)
# GET API Endpoint 2
@router.get("/project/details/{project_id}")
async def method_two(
project_id: str, session: AsyncSession = Depends(get_db)
):
try:
return await CustomController.method_two(
session=session, project_id=project_id
)
except Exception as e:
return custom_exception_handler(e)
# GET API Endpoint 3
@router.get("/project/metadata/{project_id}")
async def method_three(
project_id: str, session: AsyncSession = Depends(get_db)
):
try:
return await CustomController.method_three(
session=session, project_id=project_id
)
except Exception as e:
return custom_exception_handler(e)
The obvious expectation of workflow here is: when each of these API endpoints are triggered with their required path parameters, the controller method is executed, as defined in their body.
However, for some strange reason, when API endpoints 2 and 3 are triggered, they are executing the controller method in endpoint 1, i.e., CustomController.method_one().
Upon adding some print() statements in the method method_one() of the router, I've observed that method_one() is being called when API endpoint 2 is called, while it is actually supposed to call method_two() in the router. Same is the case with API endpoint 3.
I'm unable to understand why the method body of method_one() is getting executed, when API endpoints 2 and 3 are triggered. Am I missing out something on configuration, or something - can someone please correct me? Thanks!
|
[
"In FastAPI, as described in this answer, because endpoints are evaluated in order (see order matters), it makes sure that the endpoint you defined first in your app—in this case, that is, /project/{project_id}/...—will be evaluated first. Hence, every time you call one of the other two endpoints, i.e., /project/details/... and /project/metadata/..., the first endpoint is triggered, using details or metadata as the project_id parameter.\nSolution\nThus, you need to make sure that the other two endpoints are declared before the one for /project/{project_id}/.... For example:\n# GET API Endpoint 1\n@router.get(\"/project/details/{project_id}\")\n # ...\n\n# GET API Endpoint 2\n@router.get(\"/project/metadata/{project_id}\")\n # ...\n\n# GET API Endpoint 3\n@router.get(\"/project/{project_id}/{employee_id}\")\n # ...\n\n"
] |
[
1
] |
[] |
[] |
[
"fastapi",
"fastapi_crudrouter",
"fastapiusers",
"python",
"rest"
] |
stackoverflow_0074498191_fastapi_fastapi_crudrouter_fastapiusers_python_rest.txt
|
Q:
How to run Oracle PL/SQL in python
I'm using Jupyter notebook to run a PL/SQL script but I get an error. The code block in the notebook is as follows:
%%sql
DECLARE BEGIN
FOR record_item IN (
SELECT
*
FROM
duplicated_records
) LOOP
EXECUTE IMMEDIATE 'UPDATE table_name SET record_id ='|| record_item.original_record_id || ' WHERE record_id =' || record_item.duplicated_record_id;
EXECUTE IMMEDIATE 'DELETE FROM records WHERE id ='|| record_item.duplicated_record_id;
END LOOP;
END
The error is
(cx_Oracle.DatabaseError) ORA-06550: line 8, column 165:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
Non-PL/SQL code, such as select, and update statements, seems to work.
It works perfectly fine with other SQL clients like SQL developer. I've tried adding/removing the; at the end but it still doesn't work.
A:
I don't know Python so I can't assist about that, but - as far as Oracle is concerned - you don't need DECLARE (as you didn't declare anything), and you certainly don't need dynamic SQL (EXECUTE IMMEDIATE) as there's nothing dynamic there.
Rewritten:
BEGIN
FOR record_item IN (SELECT * FROM duplicated_records) LOOP
UPDATE table_name
SET record_id = record_item.original_record_id
WHERE record_id = record_item.duplicated_record_id;
DELETE FROM records
WHERE id = record_item.duplicated_record_id;
END LOOP;
END;
On the other hand, row-by-row processing is slow-by-slow. Consider using two separate statements: one which will update existing rows, and another which will delete rows (from a different table, apparently):
merge into table_name a
using duplicated_records b
on (a.record_id = b.duplicate_record_id)
when matched then update set
a.record_id = b.original_record_id;
delete from records a
where a.id in (select b.duplicated_record_id from duplicated_records b);
If tables are properly indexed (on ID columns), that should behave better (faster).
A:
The direct implementation of your code in Python would be like:
import oracledb
import traceback
import os
import sys
#if sys.platform.startswith('darwin'):
# oracledb.init_oracle_client(lib_dir=os.environ.get('HOME')+'/Downloads/instantclient_19_8')
un = os.environ.get('PYTHON_USERNAME')
pw = os.environ.get('PYTHON_PASSWORD')
cs = os.environ.get('PYTHON_CONNECTSTRING')
try:
connection = oracledb.connect(user=un, password=pw, dsn=cs)
with connection.cursor() as cursor:
plsql = """BEGIN
FOR RECORD_ITEM IN (
SELECT
*
FROM
DUPLICATED_RECORDS
) LOOP
EXECUTE IMMEDIATE 'UPDATE table_name SET record_id ='
|| RECORD_ITEM.ORIGINAL_RECORD_ID
|| ' WHERE record_id ='
|| RECORD_ITEM.DUPLICATED_RECORD_ID;
EXECUTE IMMEDIATE 'DELETE FROM records WHERE id ='
|| RECORD_ITEM.DUPLICATED_RECORD_ID;
END LOOP;
END;"""
cursor.execute(plsql)
except oracledb.Error as e:
error, = e.args
traceback.print_tb(e.__traceback__)
print(error.message)
For this you need to install the oracledb module, which is the renamed, latest version of the cx_Oracle module. It will work with cx_Oracle by changing the import to import cx_Oracle as oracledb.
However, before blindly copying this, check @littlefoot's answer for more about the PL/SQL code.
|
How to run Oracle PL/SQL in python
|
I'm using Jupyter notebook to run a PL/SQL script but I get an error. The code block in the notebook is as follows:
%%sql
DECLARE BEGIN
FOR record_item IN (
SELECT
*
FROM
duplicated_records
) LOOP
EXECUTE IMMEDIATE 'UPDATE table_name SET record_id ='|| record_item.original_record_id || ' WHERE record_id =' || record_item.duplicated_record_id;
EXECUTE IMMEDIATE 'DELETE FROM records WHERE id ='|| record_item.duplicated_record_id;
END LOOP;
END
The error is
(cx_Oracle.DatabaseError) ORA-06550: line 8, column 165:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
Non-PL/SQL code, such as select, and update statements, seems to work.
It works perfectly fine with other SQL clients like SQL developer. I've tried adding/removing the; at the end but it still doesn't work.
|
[
"I don't know Python so I can't assist about that, but - as far as Oracle is concerned - you don't need DECLARE (as you didn't declare anything), and you certainly don't need dynamic SQL (EXECUTE IMMEDIATE) as there's nothing dynamic there.\nRewritten:\nBEGIN\n FOR record_item IN (SELECT * FROM duplicated_records) LOOP\n UPDATE table_name\n SET record_id = record_item.original_record_id\n WHERE record_id = record_item.duplicated_record_id;\n\n DELETE FROM records\n WHERE id = record_item.duplicated_record_id;\n END LOOP;\nEND;\n\n\nOn the other hand, row-by-row processing is slow-by-slow. Consider using two separate statements: one which will update existing rows, and another which will delete rows (from a different table, apparently):\nmerge into table_name a\n using duplicated_records b\n on (a.record_id = b.duplicate_record_id) \n when matched then update set\n a.record_id = b.original_record_id;\n\ndelete from records a\n where a.id in (select b.duplicated_record_id from duplicated_records b);\n\nIf tables are properly indexed (on ID columns), that should behave better (faster).\n",
"The direct implementation of your code in Python would be like:\nimport oracledb\nimport traceback\nimport os\nimport sys\n\n#if sys.platform.startswith('darwin'):\n# oracledb.init_oracle_client(lib_dir=os.environ.get('HOME')+'/Downloads/instantclient_19_8')\n\nun = os.environ.get('PYTHON_USERNAME')\npw = os.environ.get('PYTHON_PASSWORD')\ncs = os.environ.get('PYTHON_CONNECTSTRING')\n\ntry:\n connection = oracledb.connect(user=un, password=pw, dsn=cs)\n\n with connection.cursor() as cursor:\n plsql = \"\"\"BEGIN\n FOR RECORD_ITEM IN (\n SELECT\n *\n FROM\n DUPLICATED_RECORDS\n ) LOOP\n EXECUTE IMMEDIATE 'UPDATE table_name SET record_id ='\n || RECORD_ITEM.ORIGINAL_RECORD_ID\n || ' WHERE record_id ='\n || RECORD_ITEM.DUPLICATED_RECORD_ID;\n EXECUTE IMMEDIATE 'DELETE FROM records WHERE id ='\n || RECORD_ITEM.DUPLICATED_RECORD_ID;\n END LOOP;\n END;\"\"\"\n\n cursor.execute(plsql)\n\nexcept oracledb.Error as e:\n error, = e.args\n traceback.print_tb(e.__traceback__)\n print(error.message)\n\nFor this you need to install the oracledb module, which is the renamed, latest version of the cx_Oracle module. It will work with cx_Oracle by changing the import to import cx_Oracle as oracledb.\nHowever, before blindly copying this, check @littlefoot's answer for more about the PL/SQL code.\n"
] |
[
2,
1
] |
[] |
[] |
[
"jupyter_notebook",
"oracle",
"plsql",
"python"
] |
stackoverflow_0074498105_jupyter_notebook_oracle_plsql_python.txt
|
Q:
What does "splitter" attribute in sklearn's DecisionTreeClassifier do?
The sklearn DecisionTreeClassifier has a attribute called "splitter" , it is set to "best" by default, what does setting it to "best" or "random" do? I couldn't find enough information from the official documentation.
A:
There is 2 things to consider, the criterion and the splitter. During all the explaination, I'll use the wine dataset example:
Criterion:
It is used to evaluate the feature importance. The default one is gini but you can also use entropy. Based on this, the model will define the importance of each feature for the classification.
Example:
The wine dataset using a "gini" criterion has a feature importance of:
alcohol -> 0.04727507393151268
malic_acid -> 0.0
ash -> 0.0
alcalinity_of_ash -> 0.0
magnesium -> 0.0329784450464887
total_phenols -> 0.0
flavanoids -> 0.1414466773122087
nonflavanoid_phenols -> 0.0
proanthocyanins -> 0.0
color_intensity -> 0.0
hue -> 0.08378677906228588
od280/od315_of_diluted_wines -> 0.3120425747831769
proline -> 0.38247044986432716
The wine dataset using a "entropy" criterion has a feature importance of:
alcohol -> 0.014123729330936566
malic_acid -> 0.0
ash -> 0.0
alcalinity_of_ash -> 0.02525179137252771
magnesium -> 0.0
total_phenols -> 0.0
flavanoids -> 0.4128453371544815
nonflavanoid_phenols -> 0.0
proanthocyanins -> 0.0
color_intensity -> 0.22278576133186542
hue -> 0.011635633063349873
od280/od315_of_diluted_wines -> 0.0
proline -> 0.31335774774683883
Results varies with the random_state so I think that only a subset of the dataset is used to compute it.
Splitter:
The splitter is used to decide which feature and which threshold is used.
Using best, the model if taking the feature with the highest importance
Using random, the model if taking the feature randomly but with the same distribution (in gini, proline have an importance of 38% so it will be taken in 38% of cases)
Example:
After training 1000 DecisionTreeClassifier with criterion="gini", splitter="best" and here is the distribution of the "feature number" used at the first split and the 'threshold'
It always choses the feature 12 (=proline) with a threshold of 755. This is the head of one of the model trained:
By doing the same with splitter= "random", the result is:
The threshold is more variant due to the use of different features, here is the result by filtering model having the feature 12 as first split:
We can see that the model is also taking randomply the thresholdto split. By looking at the distribution of the feature 12 in regards of classes, we have:
The red line being the threshold used when splitter="best".
Now, using random, the model will randomly select a threshold value (I think normally distributed with a mean/stdev of the feature but I'm not sure) leading the a distribution centered in the green light and with min max in blue (done with 1353 randomly trained model wtarting with feature 12 for the split)
Code to reproduce:
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier, plot_tree, _tree
import numpy as np
import matplotlib.pyplot as plt
wine = datasets.load_wine()
# Feature importance
clf = DecisionTreeClassifier(criterion="gini", splitter='best', random_state=42)
clf = clf.fit(wine.data, wine.target)
for name, val in zip(wine.feature_names, clf.feature_importances_):
print(f"{name:>40} -> {val}")
print("")
clf = DecisionTreeClassifier(criterion="entropy", splitter='best', random_state=42)
clf = clf.fit(wine.data, wine.target)
for name, val in zip(wine.feature_names, clf.feature_importances_):
print(f"{name:>40} -> {val}")
# Feature selected first and threshold
features = []
tresholds = []
for random in range(1000):
clf = DecisionTreeClassifier(criterion="gini", splitter='best', random_state=random)
clf = clf.fit(wine.data, wine.target)
features.append(clf.tree_.feature[0])
tresholds.append(clf.tree_.threshold[0])
# plot distribution
fig, (ax, ax2) = plt.subplots(1, 2, figsize=(20, 5))
ax.hist(features, bins=np.arange(14)-0.5)
ax2.hist(tresholds)
ax.set_title("Number of the first used for split")
ax2.set_title("Value of the threshold")
plt.show()
# plot model
plt.figure(figsize=(20, 12))
plot_tree(clf)
plt.show()
# plot filtered result
threshold_filtered = [val for feat, val in zip(features, tresholds) if feat==12]
fig, ax = plt.subplots(1, 1, figsize=(20, 10))
ax.hist(threshold_filtered)
ax.set_title("Number of the first used for split")
plt.show()
feature_number = 12
X1, X2, X3 = wine.data[wine.target==0][:, feature_number], wine.data[wine.target==1][:, feature_number], wine.data[wine.target==2][:, feature_number]
fig, ax = plt.subplots()
ax.set_title(f'feature {feature_number} - distribution')
ax.boxplot([X1, X2, X3])
ax.hlines(755, 0.5, 3.5, colors="r", linestyles="dashed")
ax.hlines(min(threshold_filtered), 0.5, 3.5, colors="b", linestyles="dashed")
ax.hlines(max(threshold_filtered), 0.5, 3.5, colors="b", linestyles="dashed")
ax.hlines(sum(threshold_filtered)/len(threshold_filtered), 0.5, 3.5, colors="g", linestyles="dashed")
plt.xlabel("Class")
plt.show()
A:
The "Random" setting selects a feature at random, then splits it at random and calculates the gini. It repeats this a number of times, comparing all the splits and then takes the best one.
This has a few advantages:
It's less computation intensive than calculating the optimal split of every feature at every leaf.
It should be less prone to overfitting.
The additional randomness is useful if your decision tree is a component of an ensemble method.
A:
Short ans:
RandomSplitter initiates a **random split on each chosen feature**, whereas BestSplitter goes through **all possible splits on each chosen feature**.
Longer explanation:
This is clear when you go thru _splitter.pyx.
RandomSplitter calculates improvement only on threshold that is randomly initiated (ref. lines 761 and 801). BestSplitter goes through all possible splits in a while loop (ref. lines 436 (which is where loop starts) and 462). [Note: Lines are in relation to version 0.21.2.]
As opposed to earlier responses from 15 Oct 2017 and 1 Feb 2018, RandomSplitter and BestSplitter both loop through all relevant features. This is also evident in _splitter.pyx.
A:
In fact, the "random" parameter is used for implementing the extra randomized tree in sklearn. In a nutshell, this parameter means that the splitting algorithm will traverse all features but only randomly choose the splitting point between the maximum feature value and the minimum feature value. If you are interested in the algorithm's details, you can refer to this paper [1]. Moreover, if you are interested in the detailed implementation of this algorithm, you can refer to this page.
[1]. P. Geurts, D. Ernst., and L. Wehenkel, “Extremely randomized trees”, Machine Learning, 63(1), 3-42, 2006.
A:
In my opinion,
JSong's explanation (https://stackoverflow.com/a/56999837) is correct,
Nicolas M.'s experiment (https://stackoverflow.com/a/46759065) verifies JSong's explanation.
My Reason:
If the algorithm randomly selects a point to split for all features, and then chooses the feature with the best performance. Those features that are more important have a greater probability of being selected (The proline's importance is 38%, even with random selection of the split point, it still has a 38% chance of being the best feature).
Conclusion:
If using "best", for all features, the algorithm selects the "best" point to split, then choose the best feature as the final decision.
If using "random", for all features, the algorithm "randomly" selects a point to split, then choose the best feature as the final decision.
|
What does "splitter" attribute in sklearn's DecisionTreeClassifier do?
|
The sklearn DecisionTreeClassifier has a attribute called "splitter" , it is set to "best" by default, what does setting it to "best" or "random" do? I couldn't find enough information from the official documentation.
|
[
"There is 2 things to consider, the criterion and the splitter. During all the explaination, I'll use the wine dataset example:\nCriterion:\nIt is used to evaluate the feature importance. The default one is gini but you can also use entropy. Based on this, the model will define the importance of each feature for the classification.\nExample:\nThe wine dataset using a \"gini\" criterion has a feature importance of:\n alcohol -> 0.04727507393151268\n malic_acid -> 0.0\n ash -> 0.0\n alcalinity_of_ash -> 0.0\n magnesium -> 0.0329784450464887\n total_phenols -> 0.0\n flavanoids -> 0.1414466773122087\n nonflavanoid_phenols -> 0.0\n proanthocyanins -> 0.0\n color_intensity -> 0.0\n hue -> 0.08378677906228588\n od280/od315_of_diluted_wines -> 0.3120425747831769\n proline -> 0.38247044986432716\n\nThe wine dataset using a \"entropy\" criterion has a feature importance of:\n alcohol -> 0.014123729330936566\n malic_acid -> 0.0\n ash -> 0.0\n alcalinity_of_ash -> 0.02525179137252771\n magnesium -> 0.0\n total_phenols -> 0.0\n flavanoids -> 0.4128453371544815\n nonflavanoid_phenols -> 0.0\n proanthocyanins -> 0.0\n color_intensity -> 0.22278576133186542\n hue -> 0.011635633063349873\n od280/od315_of_diluted_wines -> 0.0\n proline -> 0.31335774774683883\n\nResults varies with the random_state so I think that only a subset of the dataset is used to compute it.\nSplitter:\nThe splitter is used to decide which feature and which threshold is used.\n\nUsing best, the model if taking the feature with the highest importance\nUsing random, the model if taking the feature randomly but with the same distribution (in gini, proline have an importance of 38% so it will be taken in 38% of cases)\n\nExample:\nAfter training 1000 DecisionTreeClassifier with criterion=\"gini\", splitter=\"best\" and here is the distribution of the \"feature number\" used at the first split and the 'threshold'\n\nIt always choses the feature 12 (=proline) with a threshold of 755. This is the head of one of the model trained:\n\nBy doing the same with splitter= \"random\", the result is:\n\nThe threshold is more variant due to the use of different features, here is the result by filtering model having the feature 12 as first split:\n\nWe can see that the model is also taking randomply the thresholdto split. By looking at the distribution of the feature 12 in regards of classes, we have:\n\nThe red line being the threshold used when splitter=\"best\".\nNow, using random, the model will randomly select a threshold value (I think normally distributed with a mean/stdev of the feature but I'm not sure) leading the a distribution centered in the green light and with min max in blue (done with 1353 randomly trained model wtarting with feature 12 for the split)\n\nCode to reproduce:\nfrom sklearn import datasets\nfrom sklearn.tree import DecisionTreeClassifier, plot_tree, _tree\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nwine = datasets.load_wine()\n\n# Feature importance\n\nclf = DecisionTreeClassifier(criterion=\"gini\", splitter='best', random_state=42)\nclf = clf.fit(wine.data, wine.target)\n\nfor name, val in zip(wine.feature_names, clf.feature_importances_):\n print(f\"{name:>40} -> {val}\")\n\nprint(\"\")\nclf = DecisionTreeClassifier(criterion=\"entropy\", splitter='best', random_state=42)\nclf = clf.fit(wine.data, wine.target)\n\nfor name, val in zip(wine.feature_names, clf.feature_importances_):\n print(f\"{name:>40} -> {val}\")\n\n# Feature selected first and threshold\n\nfeatures = []\ntresholds = []\nfor random in range(1000):\n clf = DecisionTreeClassifier(criterion=\"gini\", splitter='best', random_state=random)\n clf = clf.fit(wine.data, wine.target)\n features.append(clf.tree_.feature[0])\n tresholds.append(clf.tree_.threshold[0])\n\n# plot distribution\nfig, (ax, ax2) = plt.subplots(1, 2, figsize=(20, 5))\nax.hist(features, bins=np.arange(14)-0.5)\nax2.hist(tresholds)\nax.set_title(\"Number of the first used for split\")\nax2.set_title(\"Value of the threshold\")\nplt.show()\n\n# plot model\nplt.figure(figsize=(20, 12))\nplot_tree(clf) \nplt.show()\n\n# plot filtered result\nthreshold_filtered = [val for feat, val in zip(features, tresholds) if feat==12]\nfig, ax = plt.subplots(1, 1, figsize=(20, 10))\nax.hist(threshold_filtered)\nax.set_title(\"Number of the first used for split\")\nplt.show()\n\nfeature_number = 12\nX1, X2, X3 = wine.data[wine.target==0][:, feature_number], wine.data[wine.target==1][:, feature_number], wine.data[wine.target==2][:, feature_number]\n\nfig, ax = plt.subplots()\nax.set_title(f'feature {feature_number} - distribution')\nax.boxplot([X1, X2, X3])\nax.hlines(755, 0.5, 3.5, colors=\"r\", linestyles=\"dashed\")\nax.hlines(min(threshold_filtered), 0.5, 3.5, colors=\"b\", linestyles=\"dashed\")\nax.hlines(max(threshold_filtered), 0.5, 3.5, colors=\"b\", linestyles=\"dashed\")\nax.hlines(sum(threshold_filtered)/len(threshold_filtered), 0.5, 3.5, colors=\"g\", linestyles=\"dashed\")\nplt.xlabel(\"Class\")\nplt.show()\n\n",
"The \"Random\" setting selects a feature at random, then splits it at random and calculates the gini. It repeats this a number of times, comparing all the splits and then takes the best one. \nThis has a few advantages: \n\nIt's less computation intensive than calculating the optimal split of every feature at every leaf. \nIt should be less prone to overfitting. \nThe additional randomness is useful if your decision tree is a component of an ensemble method.\n\n",
"Short ans:\nRandomSplitter initiates a **random split on each chosen feature**, whereas BestSplitter goes through **all possible splits on each chosen feature**.\n\nLonger explanation: \nThis is clear when you go thru _splitter.pyx.\nRandomSplitter calculates improvement only on threshold that is randomly initiated (ref. lines 761 and 801). BestSplitter goes through all possible splits in a while loop (ref. lines 436 (which is where loop starts) and 462). [Note: Lines are in relation to version 0.21.2.]\nAs opposed to earlier responses from 15 Oct 2017 and 1 Feb 2018, RandomSplitter and BestSplitter both loop through all relevant features. This is also evident in _splitter.pyx.\n",
"In fact, the \"random\" parameter is used for implementing the extra randomized tree in sklearn. In a nutshell, this parameter means that the splitting algorithm will traverse all features but only randomly choose the splitting point between the maximum feature value and the minimum feature value. If you are interested in the algorithm's details, you can refer to this paper [1]. Moreover, if you are interested in the detailed implementation of this algorithm, you can refer to this page.\n[1]. P. Geurts, D. Ernst., and L. Wehenkel, “Extremely randomized trees”, Machine Learning, 63(1), 3-42, 2006.\n",
"In my opinion,\n\nJSong's explanation (https://stackoverflow.com/a/56999837) is correct,\n\nNicolas M.'s experiment (https://stackoverflow.com/a/46759065) verifies JSong's explanation.\n\n\nMy Reason:\nIf the algorithm randomly selects a point to split for all features, and then chooses the feature with the best performance. Those features that are more important have a greater probability of being selected (The proline's importance is 38%, even with random selection of the split point, it still has a 38% chance of being the best feature).\nConclusion:\n\nIf using \"best\", for all features, the algorithm selects the \"best\" point to split, then choose the best feature as the final decision.\nIf using \"random\", for all features, the algorithm \"randomly\" selects a point to split, then choose the best feature as the final decision.\n\n"
] |
[
11,
3,
3,
2,
0
] |
[] |
[] |
[
"machine_learning",
"python",
"python_3.x",
"scikit_learn"
] |
stackoverflow_0046756606_machine_learning_python_python_3.x_scikit_learn.txt
|
Q:
convert string response to array of json objects
I am receiving a response that I need to save as CSV file. So I would like to convert the response string as an array of json objects then access all the objects and convert each to json and push to another array to write to a csv with csv.writerow(). Probably this is too much steps and can be reduced. But I am currently searching for a way to convert the response to an array. Here is the response sample along with code of trial:
import json
null = -1
response_object = """[{
"a" : "1",
"b" : "2",
"c" : "null"
}, {
"d" : "3",
"e" : "4",
"f" : "null"
}]
"""
jess_dict = json.dumps(response_object)
jeson_converted = json.loads(jess_dict)
print(jeson_converted)
since the response object is not a valid json, I am not sure what I should do to convert it. Please suggest.
A:
json.dumps is for getting string dump from a json. Here You have a string already, so you don't need to dump it.
If You just use loads, It will give You a list of dicts:
...
jeson_converted = json.loads(response_object)
print(jeson_converted)
Output:
[{'a': '1', 'b': '2', 'c': 'null'}, {'d': '3', 'e': '4', 'f': 'null'}]
A:
This approach worked for me using literal_eval method from ast package to parse string representation of list, check if it's useful in your case:
import ast
parsed_response_object = ast.literal_eval(response_object)
for json_obj in parsed_response_object:
print(json_obj)
Output:
{'a': '1', 'b': '2', 'c': 'null'}
{'d': '3', 'e': '4', 'f': 'null'}
|
convert string response to array of json objects
|
I am receiving a response that I need to save as CSV file. So I would like to convert the response string as an array of json objects then access all the objects and convert each to json and push to another array to write to a csv with csv.writerow(). Probably this is too much steps and can be reduced. But I am currently searching for a way to convert the response to an array. Here is the response sample along with code of trial:
import json
null = -1
response_object = """[{
"a" : "1",
"b" : "2",
"c" : "null"
}, {
"d" : "3",
"e" : "4",
"f" : "null"
}]
"""
jess_dict = json.dumps(response_object)
jeson_converted = json.loads(jess_dict)
print(jeson_converted)
since the response object is not a valid json, I am not sure what I should do to convert it. Please suggest.
|
[
"json.dumps is for getting string dump from a json. Here You have a string already, so you don't need to dump it.\nIf You just use loads, It will give You a list of dicts:\n...\njeson_converted = json.loads(response_object)\nprint(jeson_converted)\n\nOutput:\n[{'a': '1', 'b': '2', 'c': 'null'}, {'d': '3', 'e': '4', 'f': 'null'}]\n\n",
"This approach worked for me using literal_eval method from ast package to parse string representation of list, check if it's useful in your case:\nimport ast\nparsed_response_object = ast.literal_eval(response_object)\nfor json_obj in parsed_response_object:\n print(json_obj)\n\nOutput:\n{'a': '1', 'b': '2', 'c': 'null'}\n{'d': '3', 'e': '4', 'f': 'null'}\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"json",
"python"
] |
stackoverflow_0074498690_json_python.txt
|
Q:
Forbidden (403) CSRF verification failed. Request aborted-Real time chat application with Django Channels
I'm doing a course from YouTube "Python Django Realtime Chat Project - Full Course" and I'm new to django.My problem is, When I try to send message in room chat (submit form) I get this error Forbidden (403) CSRF verification failed. We don't have CSRFtoken in our form in room.html but The instructor fixed the error by adding
e.preventDefault();
and
return false;
in submit querySelector block in room.html. I still get the error.
when submitting the form message should add to div with chat-messages id.
room.html:
{% extends 'core/base.html' %}
{% block title %}
{{room.name}}
{% endblock %}
{% block content %}
<div class="p-10 lg:p-20 text-center">
<h1 class="text-3xl lg:text-6xl text-white">{{room.name}}</h1>
</div>
<div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl">
<div class="chat-messages space-y-3" id="chat-messages">
<div class="p-4 bg-gray-200 rounded-xl">
<p class="font-semibold">Username</p>
<p>Message.</p>
</div>
</div>
</div>
<div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl">
<form method='POST' action='.' class='flex'>
<input type="text" name="content" class="flex-1 mr-3" placeholder="Your message..." id="chat-message-input">
<button class="px-5 py-3 rounded-xl text-white bg-teal-600 hover:bg-teal-700" id="chat-message-submit">
send
</button>
</form>
</div>
{% endblock %}
{% block script %}
{{room.slug|json_script:"json-roomname"}}
{{request.user.username|json_script:"json-username"}}
<script>
const roomName = JSON.parse(document.getElementById('json-roomname').textContent);
const userName = JSON.parse(document.getElementById('json-username').textContent);
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e) {
console.log('onmessage')
const data = JSON.parse(e.data);
if (data.message){
let html = '<div class="p-4 bg-gray-200 rounded-xl">';
html += '<p class="font-semibold">'+ data.username +'</p>';
html += '<p>'+ data.message +'</p></div>';
document.querySelector('#chat-messages').innerHTML += html;
}else {
alert('Type something!')
}
}
chatSocket.onclose = function(e) {
console.log('onclose')
}
document.querySelector('#chat-message-submit').onclick = function(e){
e.preventDefault();
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message,
'username': userName,
'room': roomName,
}));
messageInputDom.value = '';
return false;
}
</script>
{% endblock %}
consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name,
)
async def receive(self, text_data):
data = json.loads(text_data)
message = data['message']
username = data['username']
room = data['room']
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
'username': username,
'room': room,
}
)
async def chat_message(self, event):
message = event['message']
username = event['username']
room = event['room']
await self.send(text_data=json.dumps({
'message': message,
'username': username,
'room': room,
}))
routing.py
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()),
]
views
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Room
# Create your views here.
@login_required
def rooms(request):
rooms = Room.objects.all()
return render(request, 'room/rooms.html', {'rooms': rooms})
@login_required
def room(request, slug):
room = Room.objects.get(slug=slug)
return render(request, 'room/room.html', {'room': room})
url
from django.urls import path
from . import views
urlpatterns = [
path('', views.rooms, name='rooms'),
path('<slug:slug>/', views.room, name="room"),
]
error
when I add the token, I don't get the error but the message also does not add to html. It's like nothing happens.
structure
A:
Simply you can add csrf_token inside form tag of template.
In template:
<form>
{% csrf_token %}
</form>
And that error will solve.
|
Forbidden (403) CSRF verification failed. Request aborted-Real time chat application with Django Channels
|
I'm doing a course from YouTube "Python Django Realtime Chat Project - Full Course" and I'm new to django.My problem is, When I try to send message in room chat (submit form) I get this error Forbidden (403) CSRF verification failed. We don't have CSRFtoken in our form in room.html but The instructor fixed the error by adding
e.preventDefault();
and
return false;
in submit querySelector block in room.html. I still get the error.
when submitting the form message should add to div with chat-messages id.
room.html:
{% extends 'core/base.html' %}
{% block title %}
{{room.name}}
{% endblock %}
{% block content %}
<div class="p-10 lg:p-20 text-center">
<h1 class="text-3xl lg:text-6xl text-white">{{room.name}}</h1>
</div>
<div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl">
<div class="chat-messages space-y-3" id="chat-messages">
<div class="p-4 bg-gray-200 rounded-xl">
<p class="font-semibold">Username</p>
<p>Message.</p>
</div>
</div>
</div>
<div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl">
<form method='POST' action='.' class='flex'>
<input type="text" name="content" class="flex-1 mr-3" placeholder="Your message..." id="chat-message-input">
<button class="px-5 py-3 rounded-xl text-white bg-teal-600 hover:bg-teal-700" id="chat-message-submit">
send
</button>
</form>
</div>
{% endblock %}
{% block script %}
{{room.slug|json_script:"json-roomname"}}
{{request.user.username|json_script:"json-username"}}
<script>
const roomName = JSON.parse(document.getElementById('json-roomname').textContent);
const userName = JSON.parse(document.getElementById('json-username').textContent);
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e) {
console.log('onmessage')
const data = JSON.parse(e.data);
if (data.message){
let html = '<div class="p-4 bg-gray-200 rounded-xl">';
html += '<p class="font-semibold">'+ data.username +'</p>';
html += '<p>'+ data.message +'</p></div>';
document.querySelector('#chat-messages').innerHTML += html;
}else {
alert('Type something!')
}
}
chatSocket.onclose = function(e) {
console.log('onclose')
}
document.querySelector('#chat-message-submit').onclick = function(e){
e.preventDefault();
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message,
'username': userName,
'room': roomName,
}));
messageInputDom.value = '';
return false;
}
</script>
{% endblock %}
consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name,
)
async def receive(self, text_data):
data = json.loads(text_data)
message = data['message']
username = data['username']
room = data['room']
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
'username': username,
'room': room,
}
)
async def chat_message(self, event):
message = event['message']
username = event['username']
room = event['room']
await self.send(text_data=json.dumps({
'message': message,
'username': username,
'room': room,
}))
routing.py
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()),
]
views
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Room
# Create your views here.
@login_required
def rooms(request):
rooms = Room.objects.all()
return render(request, 'room/rooms.html', {'rooms': rooms})
@login_required
def room(request, slug):
room = Room.objects.get(slug=slug)
return render(request, 'room/room.html', {'room': room})
url
from django.urls import path
from . import views
urlpatterns = [
path('', views.rooms, name='rooms'),
path('<slug:slug>/', views.room, name="room"),
]
error
when I add the token, I don't get the error but the message also does not add to html. It's like nothing happens.
structure
|
[
"Simply you can add csrf_token inside form tag of template.\nIn template:\n<form>\n {% csrf_token %} \n</form>\n\nAnd that error will solve.\n"
] |
[
1
] |
[] |
[] |
[
"channels",
"django",
"django_channels",
"python",
"websocket"
] |
stackoverflow_0074498749_channels_django_django_channels_python_websocket.txt
|
Q:
Is there a ready-made function for http_wait in telethon?
I need to use http_wait link with telethon, are there already made functions in the library to use that specific method?
I need to receive messages as soon as they occur is large broadcast channels, now the updates come 5-20 seconds late
A:
Clients using the Telegram API, such as Telethon, connect to the Telegram servers directly via a TCP socket. While connected, Telegram decides when and where to deliver the updates. Telegram's API doesn't really offer a way to "poll" for these updates.
If Telegram is delivering them slowly, it's probably to reduce load, or because the channel is too large, or because the client is not being actively used. In essence, it's not something the library can "fix".
|
Is there a ready-made function for http_wait in telethon?
|
I need to use http_wait link with telethon, are there already made functions in the library to use that specific method?
I need to receive messages as soon as they occur is large broadcast channels, now the updates come 5-20 seconds late
|
[
"Clients using the Telegram API, such as Telethon, connect to the Telegram servers directly via a TCP socket. While connected, Telegram decides when and where to deliver the updates. Telegram's API doesn't really offer a way to \"poll\" for these updates.\nIf Telegram is delivering them slowly, it's probably to reduce load, or because the channel is too large, or because the client is not being actively used. In essence, it's not something the library can \"fix\".\n"
] |
[
0
] |
[] |
[] |
[
"python",
"telethon"
] |
stackoverflow_0074463994_python_telethon.txt
|
Q:
ufunc 'sqrt' not supported for the input types
Im trying to plot a scatter with values from my array, everything is working till im trying to scale the size of the dots with an value of my array.
For example my array looks like this:
['50', ' 50', ' 0.6352952']
First value is x, second y and the third one is which i want to scale with
My plots currently looks like that:
for i in range(0, len(convertedResults)):
if convertedResults[i][0] and convertedResults[i][1]:
plt.scatter(convertedResults[i][0], convertedResults[i][1], s=1*convertedResults[i][2])
plt.show()
I can easy plot without convertedResults[i][2], but if im trying to set the size of each dot, the following error appears:
TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
I also tried to set the s size manually to s=0.653123123 (for Example) and it worked. So it seems like there is a problem with my array. I don´t know if its necessary but my array is build like this:
[['50', ' 50', ' 0.6352952'], ['60', ' 50', ' 2.8389171199999996'], ['70', ' 50', ' 2.8389171199999996'], ['50', ' 60', ' 0.6352952']]
A:
The data in convertedResults is of type string, so you are trying to pass a string into s. Even when you multiply convertedResults[i][2] by 1, the result is also a string according to the Python standard. You need to use s = float(convertedResults[i][2]) in the scatter call
|
ufunc 'sqrt' not supported for the input types
|
Im trying to plot a scatter with values from my array, everything is working till im trying to scale the size of the dots with an value of my array.
For example my array looks like this:
['50', ' 50', ' 0.6352952']
First value is x, second y and the third one is which i want to scale with
My plots currently looks like that:
for i in range(0, len(convertedResults)):
if convertedResults[i][0] and convertedResults[i][1]:
plt.scatter(convertedResults[i][0], convertedResults[i][1], s=1*convertedResults[i][2])
plt.show()
I can easy plot without convertedResults[i][2], but if im trying to set the size of each dot, the following error appears:
TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
I also tried to set the s size manually to s=0.653123123 (for Example) and it worked. So it seems like there is a problem with my array. I don´t know if its necessary but my array is build like this:
[['50', ' 50', ' 0.6352952'], ['60', ' 50', ' 2.8389171199999996'], ['70', ' 50', ' 2.8389171199999996'], ['50', ' 60', ' 0.6352952']]
|
[
"The data in convertedResults is of type string, so you are trying to pass a string into s. Even when you multiply convertedResults[i][2] by 1, the result is also a string according to the Python standard. You need to use s = float(convertedResults[i][2]) in the scatter call\n"
] |
[
1
] |
[] |
[] |
[
"matplotlib",
"plot",
"python",
"scatter_plot"
] |
stackoverflow_0074498600_matplotlib_plot_python_scatter_plot.txt
|
Q:
How do I make a turtle disapear if touched by another turtle?
Me and my buddy are making a sorta zombie shooting game on Python, we've gotten almost the basic gameplay done except with one issue, we can't find a way to make one turtle disappear after being touched by a different turtle. We have 3 turtles, one for our player model, one for a bullet, and one for a zombie, we're trying to make it so when the bullet turtle touches or is within a close area of the zombie turtle the zombie turtle disappears or at the very least moves location. No matter what we've tried nothing works, if anybody can help it would be greatly appreciated.
import turtle as trtl
wn = trtl.Screen()
p= trtl.Turtle()
g= trtl.Turtle()
z= trtl.Turtle()
b = trtl.Turtle()
counter=trtl.Turtle()
font_setup = ("Arial", 20, "normal")
p.penup()
b.penup()
b.hideturtle()
pSpeed = 30
bSpeed = 30
trtl.register_shape("appleleft.gif")
trtl.register_shape("appleright.gif")
trtl.register_shape("mario.gif")
trtl.register_shape("mario2.gif")
trtl.register_shape("bullet.gif")
trtl.register_shape("bulletleft.gif")
trtl.register_shape("bosszombie.gif")
p.shape("mario.gif")
b.shape("bullet.gif")
z.shape("bosszombie.gif")
z.goto(200,0)
zx = z.xcor()
zy = z.ycor()
bx = b.xcor()
by = b.ycor()
wn.bgpic("mars.gif")
def shoot():
b.goto(p.position())
b.showturtle()
b.forward(400)
b.hideturtle()
b.goto(p.position())
if b.xcor() == z.xcor():
z.clear()
def move_left():
x = p.xcor() - pSpeed
if x < -280:
x= -280
p.setx(x)
p.shape("mario2.gif")
b.shape("bulletleft.gif")
b.setheading(180)
def move_up():
y = p.ycor() + pSpeed
if y > 280:
y=280
p.sety(y)
def move_down():
y = p.ycor() - pSpeed
if y < -280:
y= -280
p.sety(y)
def move_right():
x = p.xcor() + pSpeed
if x > 280:
x=280
p.setx(x)
p.shape("mario.gif")
b.shape("bullet.gif")
b.setheading(0)
wn.onkeypress(move_left, "a")
wn.onkeypress(move_up, "w")
wn.onkeypress(move_down, "s")
wn.onkeypress(move_right, "d")
wn.onkeypress(shoot, "l")
wn.listen()
wn.mainloop()
We put a clear command for the zombie turtle when the bullet turtle touches it but it doesn't work, we even tried to make it go to random locations and nothing is working.
A:
That code is not working because the code that detects if a turtle touches turtle cannot only use it's own position, because for example if every frame the bullet moves 10 pixels so when it is at the point it needs to hit the zombie the zombie x is 5 and the bullet x is 0 at the next game it is going to 10, so it will not touch the 5. to make a code that detects if they really touches each other you should create a hitbox, this code is a little bit higher level (still beginners level)
for example lets make a square and circle the square moves and the game has to detect when they are touching and stop the square:
import turtle as t
wn = t.Screen()
wn.setup(0.7, 0.7)
s = t.Turtle()
s.pu() # you can use it instead of pen up
s.shape('square')
s.shapesize(3, 3)
s.setx(-100)
c = t.Turtle()
c.pu()
c.shape('circle')
c.shapesize(2, 2)
c.setx(100)
# now create the function that detects if they touch each other:
def StouchingC():
if s.xcor() + 3 * 20.1 / 2 > c.xcor() - 2 * 20.1 / 2: # thats because the scale between turtle size to one pixel is 20.1 means that one turtle size = 20.1 pixels
return (True)
while not StouchingC():
s.setx(s.xcor() + 5)
wn.update()
print('You see!')
wn.mainloop()
|
How do I make a turtle disapear if touched by another turtle?
|
Me and my buddy are making a sorta zombie shooting game on Python, we've gotten almost the basic gameplay done except with one issue, we can't find a way to make one turtle disappear after being touched by a different turtle. We have 3 turtles, one for our player model, one for a bullet, and one for a zombie, we're trying to make it so when the bullet turtle touches or is within a close area of the zombie turtle the zombie turtle disappears or at the very least moves location. No matter what we've tried nothing works, if anybody can help it would be greatly appreciated.
import turtle as trtl
wn = trtl.Screen()
p= trtl.Turtle()
g= trtl.Turtle()
z= trtl.Turtle()
b = trtl.Turtle()
counter=trtl.Turtle()
font_setup = ("Arial", 20, "normal")
p.penup()
b.penup()
b.hideturtle()
pSpeed = 30
bSpeed = 30
trtl.register_shape("appleleft.gif")
trtl.register_shape("appleright.gif")
trtl.register_shape("mario.gif")
trtl.register_shape("mario2.gif")
trtl.register_shape("bullet.gif")
trtl.register_shape("bulletleft.gif")
trtl.register_shape("bosszombie.gif")
p.shape("mario.gif")
b.shape("bullet.gif")
z.shape("bosszombie.gif")
z.goto(200,0)
zx = z.xcor()
zy = z.ycor()
bx = b.xcor()
by = b.ycor()
wn.bgpic("mars.gif")
def shoot():
b.goto(p.position())
b.showturtle()
b.forward(400)
b.hideturtle()
b.goto(p.position())
if b.xcor() == z.xcor():
z.clear()
def move_left():
x = p.xcor() - pSpeed
if x < -280:
x= -280
p.setx(x)
p.shape("mario2.gif")
b.shape("bulletleft.gif")
b.setheading(180)
def move_up():
y = p.ycor() + pSpeed
if y > 280:
y=280
p.sety(y)
def move_down():
y = p.ycor() - pSpeed
if y < -280:
y= -280
p.sety(y)
def move_right():
x = p.xcor() + pSpeed
if x > 280:
x=280
p.setx(x)
p.shape("mario.gif")
b.shape("bullet.gif")
b.setheading(0)
wn.onkeypress(move_left, "a")
wn.onkeypress(move_up, "w")
wn.onkeypress(move_down, "s")
wn.onkeypress(move_right, "d")
wn.onkeypress(shoot, "l")
wn.listen()
wn.mainloop()
We put a clear command for the zombie turtle when the bullet turtle touches it but it doesn't work, we even tried to make it go to random locations and nothing is working.
|
[
"That code is not working because the code that detects if a turtle touches turtle cannot only use it's own position, because for example if every frame the bullet moves 10 pixels so when it is at the point it needs to hit the zombie the zombie x is 5 and the bullet x is 0 at the next game it is going to 10, so it will not touch the 5. to make a code that detects if they really touches each other you should create a hitbox, this code is a little bit higher level (still beginners level)\nfor example lets make a square and circle the square moves and the game has to detect when they are touching and stop the square:\nimport turtle as t\nwn = t.Screen()\nwn.setup(0.7, 0.7)\n\ns = t.Turtle()\ns.pu() # you can use it instead of pen up\ns.shape('square')\ns.shapesize(3, 3)\ns.setx(-100)\n\nc = t.Turtle()\nc.pu()\nc.shape('circle')\nc.shapesize(2, 2)\nc.setx(100)\n\n# now create the function that detects if they touch each other:\ndef StouchingC():\n if s.xcor() + 3 * 20.1 / 2 > c.xcor() - 2 * 20.1 / 2: # thats because the scale between turtle size to one pixel is 20.1 means that one turtle size = 20.1 pixels\n return (True)\n\nwhile not StouchingC():\n s.setx(s.xcor() + 5)\n wn.update()\n\nprint('You see!')\nwn.mainloop()\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074380930_python.txt
|
Q:
How to generate a normally distributed variable in Python?
I have a list of 10 values:
variable=[2.1, 5.3, 4.1, 6.7, 2, 6.6, 1.9, 4.51, 4, 7.15]
Its length:
>>> len(variable)
10
Its average:
>>> mean(variable)
4.436
Its standard deviation:
>>> np.std(variable)
1.8987269419271429
From it I want to generate a new_variable having len(new_variable)==100 and normally distributed where mean==4.436 and np.std==1.898.
A:
You can use the random.gauss function:
1 sample:
import random
x = random.gauss(4.436, 1.898)
or 100 samples:
import random
x = [random.gauss(4.436, 1.898) for _ in range(100)]
This is standard library, you don't need to install anything. You may also be interested in the statistics library.
A:
This function achieves exactly what you asked for by transforming a randomly generated distribution.
from statistics import NormalDist, mean, stdev
def get_target_dist(target_mean, target_std, size):
dist = NormalDist(target_mean, target_std).samples(size)
dist_mean, dist_std = mean(dist), stdev(dist)
dist_standard = [(val - dist_mean) / dist_std for val in dist]
dist_scaled = [val * target_std + target_mean for val in dist_standard]
return dist_scaled
dist = get_target_dist(4.436, 1.898, 100)
print("len:", len(dist))
print("mean:", mean(dist))
print("std:", stdev(dist))
# len: 100
# mean: 4.436
# std: 1.898
|
How to generate a normally distributed variable in Python?
|
I have a list of 10 values:
variable=[2.1, 5.3, 4.1, 6.7, 2, 6.6, 1.9, 4.51, 4, 7.15]
Its length:
>>> len(variable)
10
Its average:
>>> mean(variable)
4.436
Its standard deviation:
>>> np.std(variable)
1.8987269419271429
From it I want to generate a new_variable having len(new_variable)==100 and normally distributed where mean==4.436 and np.std==1.898.
|
[
"You can use the random.gauss function:\n1 sample:\nimport random\nx = random.gauss(4.436, 1.898)\n\nor 100 samples:\nimport random\nx = [random.gauss(4.436, 1.898) for _ in range(100)]\n\nThis is standard library, you don't need to install anything. You may also be interested in the statistics library.\n",
"This function achieves exactly what you asked for by transforming a randomly generated distribution.\nfrom statistics import NormalDist, mean, stdev\n\ndef get_target_dist(target_mean, target_std, size):\n dist = NormalDist(target_mean, target_std).samples(size)\n dist_mean, dist_std = mean(dist), stdev(dist)\n dist_standard = [(val - dist_mean) / dist_std for val in dist]\n dist_scaled = [val * target_std + target_mean for val in dist_standard]\n return dist_scaled\n\ndist = get_target_dist(4.436, 1.898, 100)\n\nprint(\"len:\", len(dist))\nprint(\"mean:\", mean(dist))\nprint(\"std:\", stdev(dist))\n\n# len: 100\n# mean: 4.436\n# std: 1.898\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074498546_python.txt
|
Q:
discord.py dming/pinging random members in a server as a chat revive system
Is there a way I can dm or ping random members in a server to revive chat? I don't know if dming random people in a server will flag the bot but just in case perhaps I can ping in a channel? If so, How can I make it pick a certain amount of random members in a server? For example 5 random members in a server.
@client.hybrid_command(name="Chat Revive",with_app_command=True,descriptrion="Revive Chat",aliases=["revive", "dead chat"])
@commands.guild_only()
@commands.is_owner()
@app_commands.guilds(discord.Object(id = 1009907559391567912))
async def Chat Revive(ctx):
dm = True
while True:
for members in ctx.guild.members:
member = random.choice(members)
await member.send("Chat Revive! Talk in <#1009907560624685148> and gain perks and levels in the server!")
I have this so far and and the only error I get is object of type 'Member' has no len()
Please help
A:
Change these lines:
for members in ctx.guild.members:
member = random.choice(members)
to the following:
member = random.choice(ctx.guild.members)
Also remember to import random
|
discord.py dming/pinging random members in a server as a chat revive system
|
Is there a way I can dm or ping random members in a server to revive chat? I don't know if dming random people in a server will flag the bot but just in case perhaps I can ping in a channel? If so, How can I make it pick a certain amount of random members in a server? For example 5 random members in a server.
@client.hybrid_command(name="Chat Revive",with_app_command=True,descriptrion="Revive Chat",aliases=["revive", "dead chat"])
@commands.guild_only()
@commands.is_owner()
@app_commands.guilds(discord.Object(id = 1009907559391567912))
async def Chat Revive(ctx):
dm = True
while True:
for members in ctx.guild.members:
member = random.choice(members)
await member.send("Chat Revive! Talk in <#1009907560624685148> and gain perks and levels in the server!")
I have this so far and and the only error I get is object of type 'Member' has no len()
Please help
|
[
"Change these lines:\nfor members in ctx.guild.members:\n member = random.choice(members)\n\nto the following:\nmember = random.choice(ctx.guild.members)\n\nAlso remember to import random\n"
] |
[
1
] |
[] |
[] |
[
"discord",
"discord.py",
"python"
] |
stackoverflow_0074496462_discord_discord.py_python.txt
|
Q:
Elegant way to concat all dict values together with a string carrier as a single string in Python
The objective is to concat all values in a dict into a single str.
Additionally, the \r\n also will be appended.
The code below demonstrates the end result.
However, I am looking for a more elegant alternative than the proposed code below.
d=dict(idx='1',sat='so',sox=[['x1: y3'],['x2: y1'],['x3: y3']],mul_sol='my love so')
s=''
for x in d:
if x=='sox':
for kk in d[x]:
s=s +kk[0] +'\r\n'
else:
s=s +d[x]+'\r\n'
print(s)
A:
following code have more control over what might have in the dictionary:
def conca(li):
ret=''
for ele in li:
if isinstance(ele,str):
ret += ele + '\r\n'
else:
ret += conca(ele)
return ret
print(conca([d[e] for e in list(d)]))
or if want a more versatile solution:
def conca(li):
ret = ''
for ele in li:
if isinstance(ele, str):
ret += ele + '\r\n'
elif isinstance(ele, list):
ret += conca(ele)
elif isinstance(ele, dict):
ret += conca(ele.values())
# you can add any other customized conversions here...
else:
raise Exception(
"value of dictionary can only be str, list or dict~")
return ret
print(conca([d[e] for e in list(d)]))
A:
Make a separate function that transforms the values, and then apply that using map.
d = {
'idx': '1',
'sat': 'so',
'sox': [['x1: y3'],['x2: y1'],['x3: y3']],
'mul_sol': 'my love so'
}
crlf = '\r\n'
import operator
def transform_sox(item):
(key, val) = item
if key == 'sox':
return crlf.join(map(operator.itemgetter(0), val))
else:
return val
print(crlf.join(map(transform_sox, d.items())), crlf)
Not necessarily shorter, but clearer and more maintainable in my opinion.
Alternatively, if we can rely on the value type to determine the transformation, rather than the key:
def transform_sox(value):
return value if isinstance(value, str) \
else crlf.join(map(operator.itemgetter(0), value))
print(crlf.join(map(transform_sox, d.values())), crlf)
In the other direction, perhaps you need custom formatters for a few elements in the dictionary. In which case, look up the formatter for each element:
formatters = collections.defaultdict(lambda: lambda x: x)
formatters['sox'] = lambda x: crlf.join(map(operator.itemgetter(0), x))
def transform_sox(item):
return formatters[item[0]](item[1])
print(crlf.join(map(transform_sox, d.items())), crlf)
A:
Use two generators, one for d['sox'] and another for everything else, and then use join() to concatenate strings.
s = ''.join(kk[0] for kk in d['sox']) + '\r\n'
s += '\r\n'.join(val for key, val in d.items() if key != 'sox')
|
Elegant way to concat all dict values together with a string carrier as a single string in Python
|
The objective is to concat all values in a dict into a single str.
Additionally, the \r\n also will be appended.
The code below demonstrates the end result.
However, I am looking for a more elegant alternative than the proposed code below.
d=dict(idx='1',sat='so',sox=[['x1: y3'],['x2: y1'],['x3: y3']],mul_sol='my love so')
s=''
for x in d:
if x=='sox':
for kk in d[x]:
s=s +kk[0] +'\r\n'
else:
s=s +d[x]+'\r\n'
print(s)
|
[
"following code have more control over what might have in the dictionary:\ndef conca(li):\n ret=''\n for ele in li:\n if isinstance(ele,str):\n ret += ele + '\\r\\n'\n else:\n ret += conca(ele) \n return ret\n\nprint(conca([d[e] for e in list(d)]))\n\nor if want a more versatile solution:\ndef conca(li):\n ret = ''\n for ele in li:\n if isinstance(ele, str):\n ret += ele + '\\r\\n'\n elif isinstance(ele, list):\n ret += conca(ele)\n elif isinstance(ele, dict):\n ret += conca(ele.values())\n # you can add any other customized conversions here...\n else:\n raise Exception(\n \"value of dictionary can only be str, list or dict~\")\n return ret\nprint(conca([d[e] for e in list(d)]))\n\n",
"Make a separate function that transforms the values, and then apply that using map.\nd = {\n 'idx': '1',\n 'sat': 'so',\n 'sox': [['x1: y3'],['x2: y1'],['x3: y3']],\n 'mul_sol': 'my love so'\n}\n\ncrlf = '\\r\\n'\n\nimport operator\n\ndef transform_sox(item):\n (key, val) = item\n if key == 'sox':\n return crlf.join(map(operator.itemgetter(0), val))\n else:\n return val\n\nprint(crlf.join(map(transform_sox, d.items())), crlf)\n\nNot necessarily shorter, but clearer and more maintainable in my opinion.\n\nAlternatively, if we can rely on the value type to determine the transformation, rather than the key:\ndef transform_sox(value):\n return value if isinstance(value, str) \\\n else crlf.join(map(operator.itemgetter(0), value))\n\nprint(crlf.join(map(transform_sox, d.values())), crlf)\n\n\nIn the other direction, perhaps you need custom formatters for a few elements in the dictionary. In which case, look up the formatter for each element:\nformatters = collections.defaultdict(lambda: lambda x: x)\nformatters['sox'] = lambda x: crlf.join(map(operator.itemgetter(0), x))\n\ndef transform_sox(item):\n return formatters[item[0]](item[1])\n\nprint(crlf.join(map(transform_sox, d.items())), crlf)\n\n",
"Use two generators, one for d['sox'] and another for everything else, and then use join() to concatenate strings.\ns = ''.join(kk[0] for kk in d['sox']) + '\\r\\n'\ns += '\\r\\n'.join(val for key, val in d.items() if key != 'sox')\n\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0074498573_dictionary_python.txt
|
Q:
Create a date column and assign value from a condition based on an existing date column in pandas
I have the following:
import pandas as pd
file = pd.DataFrame()
file['CASH RECIEVED DATE'] = ['2018-07-23', '2019-09-26', '2017-05-02']
and I need to create a column called Cash Received Date
file['Cash Received Date']
such as if [CASH_RECIEVED_DATE] is not null && [CASH RECIEVED_DATE] <= 2022-09-01 then [Cash Received Date] will be 2019-09-01, otherwise it will be the value of [CASH_RECIEVED_DATE], so the output would be:
file['Cash Received Date'] = ['2019-09-01', '2019-09-26', '2019-09-01']
How do I achieve this by creating a function?
Many thanks,
Rafa
A:
def compare_date(x):
if pd.to_datetime(x) > pd.to_datetime('2019-09-01'):
return pd.to_datetime(x)
else:
return pd.to_datetime('2019-09-01')
file['Cash Received Date'] = file['CASH RECIEVED DATE'].apply(lambda x: compare_date(x))
gives file as :
CASH RECIEVED DATE Cash Received Date
0 2018-07-23 2019-09-01
1 2019-09-26 2019-09-26
2 2017-05-02 2019-09-01
P.S. It's best practice to give columns and dataframes more distinct names so as to prevent confusion with very similar or vague variable/column names.
A:
using .mask
first step is to ensure your values are datetime values.
df['Cash Received Date'] = pd.to_datetime(df['Cash Received Date'])
df['new_date'] = df['Cash Received Date'].mask(
df['Cash Received Date'].dropna().le('2019-09-01'),'2019-01-01')
Cash Received Date new_date
0 2019-09-01 2019-01-01
1 2019-09-26 2019-09-26
2 2019-09-01 2019-01-01
|
Create a date column and assign value from a condition based on an existing date column in pandas
|
I have the following:
import pandas as pd
file = pd.DataFrame()
file['CASH RECIEVED DATE'] = ['2018-07-23', '2019-09-26', '2017-05-02']
and I need to create a column called Cash Received Date
file['Cash Received Date']
such as if [CASH_RECIEVED_DATE] is not null && [CASH RECIEVED_DATE] <= 2022-09-01 then [Cash Received Date] will be 2019-09-01, otherwise it will be the value of [CASH_RECIEVED_DATE], so the output would be:
file['Cash Received Date'] = ['2019-09-01', '2019-09-26', '2019-09-01']
How do I achieve this by creating a function?
Many thanks,
Rafa
|
[
"def compare_date(x):\n if pd.to_datetime(x) > pd.to_datetime('2019-09-01'):\n return pd.to_datetime(x)\n else:\n return pd.to_datetime('2019-09-01')\n\nfile['Cash Received Date'] = file['CASH RECIEVED DATE'].apply(lambda x: compare_date(x))\n\ngives file as :\n CASH RECIEVED DATE Cash Received Date\n0 2018-07-23 2019-09-01\n1 2019-09-26 2019-09-26\n2 2017-05-02 2019-09-01\n\nP.S. It's best practice to give columns and dataframes more distinct names so as to prevent confusion with very similar or vague variable/column names.\n",
"using .mask\nfirst step is to ensure your values are datetime values.\ndf['Cash Received Date'] = pd.to_datetime(df['Cash Received Date'])\n\ndf['new_date'] = df['Cash Received Date'].mask(\n df['Cash Received Date'].dropna().le('2019-09-01'),'2019-01-01')\n\n Cash Received Date new_date\n0 2019-09-01 2019-01-01\n1 2019-09-26 2019-09-26\n2 2019-09-01 2019-01-01\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"dataframe",
"jupyter",
"jupyter_notebook",
"pandas",
"python"
] |
stackoverflow_0074494806_dataframe_jupyter_jupyter_notebook_pandas_python.txt
|
Q:
bot event has stopped all my commands from working
this is the code which is stopping all my bot commands:
@client.event
async def on_message(message):
if message.author == client.user:
return
phrases = open("D:/code/code/DIscord bot/myFile.txt").readlines()
phrases = list(map(lambda item: item.strip(), phrases))
if message.content in phrases:
msg = 'REAL!'
await message.reply(msg)
i think its in the line
phrases = list(map(lambda item: item.strip(), phrases))
which is stopping the bot. This part of the code basically just has a text file of phrases and when one of those phrases is said, the bot will then reply with "REAL!". However, when trying to fix how the bot searches the list i think its messed up the code... please help.
and im also wondering how i can make the bot find these phrases in sentences, for example:
find "i love coding" in "man i gotta say i love coding"
but i mainly just want my code to work.
This part of the code basically just has a text file of phrases and when one of those phrases is said, the bot will then reply with "REAL!". However, when trying to fix how the bot searches the list i think its messed up the code... please help.
A:
Take a look at the discord.py FAQ:
You need to change your @client.event to @client.listen('on_message') and that should fix your issue
|
bot event has stopped all my commands from working
|
this is the code which is stopping all my bot commands:
@client.event
async def on_message(message):
if message.author == client.user:
return
phrases = open("D:/code/code/DIscord bot/myFile.txt").readlines()
phrases = list(map(lambda item: item.strip(), phrases))
if message.content in phrases:
msg = 'REAL!'
await message.reply(msg)
i think its in the line
phrases = list(map(lambda item: item.strip(), phrases))
which is stopping the bot. This part of the code basically just has a text file of phrases and when one of those phrases is said, the bot will then reply with "REAL!". However, when trying to fix how the bot searches the list i think its messed up the code... please help.
and im also wondering how i can make the bot find these phrases in sentences, for example:
find "i love coding" in "man i gotta say i love coding"
but i mainly just want my code to work.
This part of the code basically just has a text file of phrases and when one of those phrases is said, the bot will then reply with "REAL!". However, when trying to fix how the bot searches the list i think its messed up the code... please help.
|
[
"Take a look at the discord.py FAQ:\nYou need to change your @client.event to @client.listen('on_message') and that should fix your issue\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"nextcord",
"python"
] |
stackoverflow_0074496371_discord_nextcord_python.txt
|
Q:
TypeError: 'generator' object is not callable when using pandas' date_range
I'm using pandas' date_range to generate datetime arrays:
time_array = pd.date_range(start='2020-6-1 00:00:00', end='2021-10-31 00:00:00', freq='H')
And when I start to debug my code, my IDE tells me this error:
past_predict_single.py::test_gen_line_model FAILED
past_predict_single.py:83 (test_gen_line_model)
def test_gen_line_model():
back_hours = 72
> time_array = pd.date_range(start='2020-6-1 00:00:00', end='2021-10-31 00:00:00', freq='H')
E TypeError: 'generator' object is not callable
But when I run my code, this error diappears.
And another interesting thing: after the error appeared on the 1st computer, I chose the 2nd computer to debug my code, but after running my code for several times, the 2nd computer also appeared this problem.
How to solve it?
A:
I cut my code to another python file and the problem disappeared.
|
TypeError: 'generator' object is not callable when using pandas' date_range
|
I'm using pandas' date_range to generate datetime arrays:
time_array = pd.date_range(start='2020-6-1 00:00:00', end='2021-10-31 00:00:00', freq='H')
And when I start to debug my code, my IDE tells me this error:
past_predict_single.py::test_gen_line_model FAILED
past_predict_single.py:83 (test_gen_line_model)
def test_gen_line_model():
back_hours = 72
> time_array = pd.date_range(start='2020-6-1 00:00:00', end='2021-10-31 00:00:00', freq='H')
E TypeError: 'generator' object is not callable
But when I run my code, this error diappears.
And another interesting thing: after the error appeared on the 1st computer, I chose the 2nd computer to debug my code, but after running my code for several times, the 2nd computer also appeared this problem.
How to solve it?
|
[
"I cut my code to another python file and the problem disappeared.\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"datetime",
"pandas",
"python",
"python_3.x"
] |
stackoverflow_0074486778_dataframe_datetime_pandas_python_python_3.x.txt
|
Q:
My discord.py bot is not responding to commands or events
import discord
from discord.ext import commands
from discord import Embed
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
#Prints bot is online to console
@bot.event
async def on_ready():
print("PythonBot is online")
#Replies Hey! if a user says Hello
@bot.event
async def on_message(message):
if message.content == 'Hello'.lower():
await message.channel.send("Hey!")
#Ping Command
@bot.command()
async def ping(ctx):
await ctx.send("Pong!")
bot.run("TOKEN_HERE")
I have made this simple program with discord.py that has an Event, the bot says Hey! when a user says Hello and a Command, that has the bot reply Pong! when a user uses the !ping command. My issue is that the bot does not respond when either of these actions happen and there are no errors raised in the terminal. I get confirmation from the API that my bot has connected to my application's token and I receive "PythonBot is online" in the terminal when I run my program but nothing else in my program seems to work.
A:
Take a look at the discord.py FAQ:
You need to change your following 2 lines
@bot.event
async def on_message(message):
to
@bot.listen('on_message')
async def on_message(message):
and that should fix your issue
|
My discord.py bot is not responding to commands or events
|
import discord
from discord.ext import commands
from discord import Embed
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
#Prints bot is online to console
@bot.event
async def on_ready():
print("PythonBot is online")
#Replies Hey! if a user says Hello
@bot.event
async def on_message(message):
if message.content == 'Hello'.lower():
await message.channel.send("Hey!")
#Ping Command
@bot.command()
async def ping(ctx):
await ctx.send("Pong!")
bot.run("TOKEN_HERE")
I have made this simple program with discord.py that has an Event, the bot says Hey! when a user says Hello and a Command, that has the bot reply Pong! when a user uses the !ping command. My issue is that the bot does not respond when either of these actions happen and there are no errors raised in the terminal. I get confirmation from the API that my bot has connected to my application's token and I receive "PythonBot is online" in the terminal when I run my program but nothing else in my program seems to work.
|
[
"Take a look at the discord.py FAQ:\nYou need to change your following 2 lines\n@bot.event\nasync def on_message(message):\n\nto\n@bot.listen('on_message')\nasync def on_message(message):\n\nand that should fix your issue\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.py",
"python"
] |
stackoverflow_0074495400_discord_discord.py_python.txt
|
Q:
Unable to process large amount of data using for loop
I am downloading 2 years worth of OHLC for 10k symbols and writing it to database. When I try to pull the entire list it crashes (but doesn't if I download 20%):
import config
from alpaca_trade_api.rest import REST, TimeFrame
import sqlite3
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
start_date = (datetime.datetime.now() - relativedelta(years=2)).date()
start_date = pd.Timestamp(start_date, tz='America/New_York').isoformat()
end_date = pd.Timestamp(datetime.datetime.now(), tz='America/New_York').isoformat()
conn = sqlite3.connect('allStockData.db')
api = REST(config.api_key_id, config.api_secret, base_url=config.base_url)
origin_symbols = pd.read_sql_query("SELECT symbol, name from stock", conn)
df = origin_symbols
df_dict = df.to_dict('records')
startTime = datetime.datetime.now()
api = REST(config.api_key_id, config.api_secret, base_url=config.base_url)
temp_data = []
for key in df_dict:
symbol = key['symbol']
print(f"downloading ${symbol}")
# stock_id = key['id']
barsets = api.get_bars_iter(symbol, TimeFrame.Day, start_date, end_date)
barsets = list(barsets)
for index, bar in enumerate(barsets):
bars = pd.DataFrame({'date': bar.t.date(), 'symbol': symbol, 'open': bar.o, 'high': bar.h, 'low': bar.l, 'close': bar.c, 'volume': bar.v, 'vwap': bar.vw}, index=[0])
temp_data.append(bars)
print("loop complete")
data = pd.concat(temp_data)
# write df back to sql, replacing the previous table
data.to_sql('daily_ohlc_init', if_exists='replace', con=conn, index=True)
endTime = datetime.datetime.now()
print(f'time elapsed to pull data was {endTime - startTime}')
To make it work I add this line after df_dict to limit symbols downloaded:
df_dict = df_dict[0:2000]
This will allow me to write to database but I need the entire dictionary (about 10k symbols). How do I write to the database without it crashing?
A:
Since you mentioned that you are able to make it work for 2000 records of df_dict at a time, a possible simple approach could be:
api = REST(config.api_key_id, config.api_secret, base_url=config.base_url)
num_records = len(df_dict)
chunk_size = 2000
num_passes = num_records // chunk_size + int(num_records % chunk_size != 0)
for i in range(num_passes):
start = i * chunk_size
end = min((i + 1) * chunk_size, num_records)
df_chunk = df_dict[start: end]
temp_data = []
for key in df_chunk:
symbol = key['symbol']
print(f"downloading ${symbol}")
barsets = api.get_bars_iter(symbol, TimeFrame.Day, start_date, end_date)
barsets = list(barsets)
for index, bar in enumerate(barsets):
bars = [bar.t.date(), symbol, bar.o, bar.h, bar.l, bar.c, bar.v, bar.vw]
temp_data.append(bars)
# should be a bit more efficient to create a dataframe just once
columns = ['date', 'symbol', 'open', 'high', 'low', 'close', 'volume', 'vwap']
data = pd.DataFrame(temp_data, columns=columns)
# should delete previous table when writing first chunk, then start appending from next passes through df_dict
data.to_sql('daily_ohlc_init', if_exists='replace' if i == 0 else 'append', con=conn, index=True)
print(f"Internal loop finished processing records {start} to {end} out of {num_records}.")
endTime = datetime.datetime.now()
print(f'time elapsed to pull data was {endTime - startTime}')
|
Unable to process large amount of data using for loop
|
I am downloading 2 years worth of OHLC for 10k symbols and writing it to database. When I try to pull the entire list it crashes (but doesn't if I download 20%):
import config
from alpaca_trade_api.rest import REST, TimeFrame
import sqlite3
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
start_date = (datetime.datetime.now() - relativedelta(years=2)).date()
start_date = pd.Timestamp(start_date, tz='America/New_York').isoformat()
end_date = pd.Timestamp(datetime.datetime.now(), tz='America/New_York').isoformat()
conn = sqlite3.connect('allStockData.db')
api = REST(config.api_key_id, config.api_secret, base_url=config.base_url)
origin_symbols = pd.read_sql_query("SELECT symbol, name from stock", conn)
df = origin_symbols
df_dict = df.to_dict('records')
startTime = datetime.datetime.now()
api = REST(config.api_key_id, config.api_secret, base_url=config.base_url)
temp_data = []
for key in df_dict:
symbol = key['symbol']
print(f"downloading ${symbol}")
# stock_id = key['id']
barsets = api.get_bars_iter(symbol, TimeFrame.Day, start_date, end_date)
barsets = list(barsets)
for index, bar in enumerate(barsets):
bars = pd.DataFrame({'date': bar.t.date(), 'symbol': symbol, 'open': bar.o, 'high': bar.h, 'low': bar.l, 'close': bar.c, 'volume': bar.v, 'vwap': bar.vw}, index=[0])
temp_data.append(bars)
print("loop complete")
data = pd.concat(temp_data)
# write df back to sql, replacing the previous table
data.to_sql('daily_ohlc_init', if_exists='replace', con=conn, index=True)
endTime = datetime.datetime.now()
print(f'time elapsed to pull data was {endTime - startTime}')
To make it work I add this line after df_dict to limit symbols downloaded:
df_dict = df_dict[0:2000]
This will allow me to write to database but I need the entire dictionary (about 10k symbols). How do I write to the database without it crashing?
|
[
"Since you mentioned that you are able to make it work for 2000 records of df_dict at a time, a possible simple approach could be:\napi = REST(config.api_key_id, config.api_secret, base_url=config.base_url)\n\nnum_records = len(df_dict)\nchunk_size = 2000\nnum_passes = num_records // chunk_size + int(num_records % chunk_size != 0)\n\nfor i in range(num_passes):\n start = i * chunk_size\n end = min((i + 1) * chunk_size, num_records)\n df_chunk = df_dict[start: end]\n\n temp_data = []\n for key in df_chunk:\n symbol = key['symbol']\n print(f\"downloading ${symbol}\")\n barsets = api.get_bars_iter(symbol, TimeFrame.Day, start_date, end_date)\n barsets = list(barsets)\n\n for index, bar in enumerate(barsets):\n bars = [bar.t.date(), symbol, bar.o, bar.h, bar.l, bar.c, bar.v, bar.vw]\n temp_data.append(bars)\n \n # should be a bit more efficient to create a dataframe just once\n columns = ['date', 'symbol', 'open', 'high', 'low', 'close', 'volume', 'vwap']\n data = pd.DataFrame(temp_data, columns=columns)\n\n # should delete previous table when writing first chunk, then start appending from next passes through df_dict\n data.to_sql('daily_ohlc_init', if_exists='replace' if i == 0 else 'append', con=conn, index=True)\n\n print(f\"Internal loop finished processing records {start} to {end} out of {num_records}.\")\n\nendTime = datetime.datetime.now()\nprint(f'time elapsed to pull data was {endTime - startTime}')\n\n"
] |
[
2
] |
[] |
[] |
[
"numpy",
"pandas",
"python",
"sqlite"
] |
stackoverflow_0074498448_numpy_pandas_python_sqlite.txt
|
Q:
Can not install pykd using pip
I get an error when I want to install pykd using pip.
The error says:
ERROR: Could not find a version that satisfies the requirement pykd (from versions: none)
ERROR: No matching distribution found for pykd
When I try to download the .whl file of pykd and install it with pip, I get this error:
ERROR: pykd-0.3.4.15-cp39-none-win_amd64.whl is not a supported wheel on this platform.
I'm running python 3.11.0 on a Windows 11 64-Bit machine with pip 22.3.1. I tried older versions of pykd but same error.
Can anybody help so I am able to run pykd?
A:
pykd-0.3.4.15-cp39-none-win_amd64.whl
it is not surprising what this wheel built special for python 3.9, so it can installed only for python 3.9
pykd build for 3.10 or 3.11 does not exsist. And there is no unversal pykd build. Sorry.
I recommend you use 3.8 python with pykd.
|
Can not install pykd using pip
|
I get an error when I want to install pykd using pip.
The error says:
ERROR: Could not find a version that satisfies the requirement pykd (from versions: none)
ERROR: No matching distribution found for pykd
When I try to download the .whl file of pykd and install it with pip, I get this error:
ERROR: pykd-0.3.4.15-cp39-none-win_amd64.whl is not a supported wheel on this platform.
I'm running python 3.11.0 on a Windows 11 64-Bit machine with pip 22.3.1. I tried older versions of pykd but same error.
Can anybody help so I am able to run pykd?
|
[
"pykd-0.3.4.15-cp39-none-win_amd64.whl\nit is not surprising what this wheel built special for python 3.9, so it can installed only for python 3.9\npykd build for 3.10 or 3.11 does not exsist. And there is no unversal pykd build. Sorry.\nI recommend you use 3.8 python with pykd.\n"
] |
[
0
] |
[] |
[] |
[
"pip",
"pykd",
"python"
] |
stackoverflow_0074494461_pip_pykd_python.txt
|
Q:
Trying to create an function which allows users to go back to a previous question
so I'm making a text-based game in python and I'm trying to create an option which allows the user to return to the question if their answer was incorrect. It works like this:
There are three options to a question, 1,2,3. 1 and 3 are the incorrect option which will fail the user, then they will have the option to go back to the question. If a user picks 2 the first time then their answer is correct and they'll be allowed to proceed.
The problem is trying to create that option which allows them to go back.
I've tried using while loops and if statements. But none of those have worked. with the while loop, i expected that it would print the incorrect answers over and over again until the user picked the correct answer, but it printed the same answer even if the user picked something different.
and with if statements, I tried to create a variable which stored the user's input, and then used that variable in an if statement which made it so that when the user pressed "q" the question would print again.
I had hoped that when the question would print again, when the user picked a different option it would print the different answer assigned to it, but it instead printed nothing. When I type the incorrect answer, it prints the answer assigned to it, and gives me the option to press q, everything worked accordingly until that point, but when I typed the correct answer, it printed nothing, even though it should've printed a option.
Here's the code so you can a better understanding:
question_1 = input("You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n ")
if question_1 == "1":
quit = input("You manage to break the window, but the glass cuts your hand and your face, you scream in pain and as the glass cuts through your face, and eventually die from the wounds. Press q to go back ")
if quit == "q":
second = input("You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n ")
if question_1 == "2":
print("You find an array of supplies in your basement, everything from hammers, tools, weapons and food and water. You then safely break the window and jump out.")
That's the problem I'm facing, I'm not sure what's going on or what the fix is, so hope you all can help me.
Note: Also, it prints nothing IF only the incorrect option is chosen first, then the quit option. If I originally chose 2, then it prints the answer assigned to it with no problem.
A:
this maybe overkill but if it was me I would probably implement a scene graph... something like what follows
class Scene:
graph_map = {}
def __init__(self,id,message,options):
self.message = message
self.opts = options
self.id = id or len(Scene.graph)
Scene.graph_map[id]=self
def prompt(self):
if self.opts:
while True:
resp = input(self.message)
if resp in self.opts:
return Scene.graph_map[self.opts[resp]]
print("ERROR Invalid input... try again")
else:
print(self.message)
return None
def play(self):
target = self
while True:
target = target.prompt()
if target and not isinstance(target,Scene):
print("Error unknown scene...")
return None
# make some scenes
welcome = Scene("welcome",message="""You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n """, options={"1":"window","2":"search","3":"help")
window = Scene("window",message="""You manage to break the window, but the glass cuts your hand and your face, you scream in pain and as the glass cuts through your face, and eventually die from the wounds. Press q to go back""", options={"q":"welcome"}
search = Scene("search",message="""You find an array of supplies in your basement, everything from hammers, tools, weapons and food and water. You then safely break the window and jump out.""",options=None)
#start the game
welcome.play()
A:
question_1=0
while question_1!="2":
question_1 = input("You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n ")
quit=0
if question_1 == "1":
while quit!= "q":
quit = input("You manage to break the window, but the glass cuts your hand and your face, you scream in pain and as the glass cuts through your face, and eventually die from the wounds. Press q to go back ")
if question_1 == "2":
print("You find an array of supplies in your basement, everything from hammers, tools, weapons and food and water. You then safely break the window and jump out.")
while question_1 is not 2, it keeps asking question 1.
If answer is 1, it keeps asking to quit until 'q' is pressed.
If answer is 2, question_1!="2" is now false so the while loop stops
|
Trying to create an function which allows users to go back to a previous question
|
so I'm making a text-based game in python and I'm trying to create an option which allows the user to return to the question if their answer was incorrect. It works like this:
There are three options to a question, 1,2,3. 1 and 3 are the incorrect option which will fail the user, then they will have the option to go back to the question. If a user picks 2 the first time then their answer is correct and they'll be allowed to proceed.
The problem is trying to create that option which allows them to go back.
I've tried using while loops and if statements. But none of those have worked. with the while loop, i expected that it would print the incorrect answers over and over again until the user picked the correct answer, but it printed the same answer even if the user picked something different.
and with if statements, I tried to create a variable which stored the user's input, and then used that variable in an if statement which made it so that when the user pressed "q" the question would print again.
I had hoped that when the question would print again, when the user picked a different option it would print the different answer assigned to it, but it instead printed nothing. When I type the incorrect answer, it prints the answer assigned to it, and gives me the option to press q, everything worked accordingly until that point, but when I typed the correct answer, it printed nothing, even though it should've printed a option.
Here's the code so you can a better understanding:
question_1 = input("You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n ")
if question_1 == "1":
quit = input("You manage to break the window, but the glass cuts your hand and your face, you scream in pain and as the glass cuts through your face, and eventually die from the wounds. Press q to go back ")
if quit == "q":
second = input("You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n ")
if question_1 == "2":
print("You find an array of supplies in your basement, everything from hammers, tools, weapons and food and water. You then safely break the window and jump out.")
That's the problem I'm facing, I'm not sure what's going on or what the fix is, so hope you all can help me.
Note: Also, it prints nothing IF only the incorrect option is chosen first, then the quit option. If I originally chose 2, then it prints the answer assigned to it with no problem.
|
[
"this maybe overkill but if it was me I would probably implement a scene graph... something like what follows\nclass Scene:\n graph_map = {}\n def __init__(self,id,message,options):\n self.message = message \n self.opts = options\n self.id = id or len(Scene.graph)\n Scene.graph_map[id]=self\n\n def prompt(self):\n if self.opts:\n while True:\n resp = input(self.message)\n if resp in self.opts:\n return Scene.graph_map[self.opts[resp]]\n print(\"ERROR Invalid input... try again\")\n else:\n print(self.message)\n return None\n\n def play(self):\n target = self\n while True:\n target = target.prompt()\n if target and not isinstance(target,Scene):\n print(\"Error unknown scene...\")\n return None\n\n# make some scenes\nwelcome = Scene(\"welcome\",message=\"\"\"You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\\n \"\"\", options={\"1\":\"window\",\"2\":\"search\",\"3\":\"help\")\nwindow = Scene(\"window\",message=\"\"\"You manage to break the window, but the glass cuts your hand and your face, you scream in pain and as the glass cuts through your face, and eventually die from the wounds. Press q to go back\"\"\", options={\"q\":\"welcome\"}\nsearch = Scene(\"search\",message=\"\"\"You find an array of supplies in your basement, everything from hammers, tools, weapons and food and water. You then safely break the window and jump out.\"\"\",options=None)\n\n#start the game\nwelcome.play()\n\n",
"question_1=0\n\nwhile question_1!=\"2\":\n question_1 = input(\"You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\\n \")\n\n quit=0\n if question_1 == \"1\":\n\n while quit!= \"q\":\n quit = input(\"You manage to break the window, but the glass cuts your hand and your face, you scream in pain and as the glass cuts through your face, and eventually die from the wounds. Press q to go back \")\n\nif question_1 == \"2\":\n print(\"You find an array of supplies in your basement, everything from hammers, tools, weapons and food and water. You then safely break the window and jump out.\")\n\n\nwhile question_1 is not 2, it keeps asking question 1.\nIf answer is 1, it keeps asking to quit until 'q' is pressed.\nIf answer is 2, question_1!=\"2\" is now false so the while loop stops\n"
] |
[
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074497867_python.txt
|
Q:
PyCharm auto suggestion doesn't appear
No Suggestion Appears:
My Setting:
Suddenly PyCharm auto suggestion doesn't appear.
For instance, to make a class, when I type just 'init', PyCharm used to suggest __init__(self).
I am begginer of Python and have little knowledge about pycharm interpreter.
Is this problem happening because of interpreter?
A:
Had the same in Visual studio code. Removed Pylance extention and got it back.
|
PyCharm auto suggestion doesn't appear
|
No Suggestion Appears:
My Setting:
Suddenly PyCharm auto suggestion doesn't appear.
For instance, to make a class, when I type just 'init', PyCharm used to suggest __init__(self).
I am begginer of Python and have little knowledge about pycharm interpreter.
Is this problem happening because of interpreter?
|
[
"Had the same in Visual studio code. Removed Pylance extention and got it back.\n"
] |
[
0
] |
[] |
[] |
[
"pycharm",
"python"
] |
stackoverflow_0070631204_pycharm_python.txt
|
Q:
Issues plotting a histogram of a csv file on google colab
I am new to google colab and I am trying to plot a histogram of a csv file using matplotlib, but getting error.
This code is able to read and show my data
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import pylab as pl
df = pd.read_csv('tree_result.csv')
df
but when I try to plot a histogram with two fields from the data, I get an error
fig, ax = plt.subplots(figsize = (50,10))
x = df['spc_common']
y = df['count']
plt.bar(x, height=y,align = 'center', width = 0.8)
plt.xlabel('Name of Trees (common name)', size = 10)
plt.ylabel('Number of Trees', size = 10)
pl.xticks(rotation = 90)
plt.show()
error message
TypeError: 'value' must be an instance of str or bytes, not a float
A:
To solve this I changed the datatype to string. That fixed it issue
fig, ax = plt.subplots(figsize = (50,10))
x = df['spc_common'].astype(str)
y = df['count']
plt.bar(x, height=y,align = 'center', width = 0.8)
plt.xlabel('Name of Trees (common name)', size = 10)
plt.ylabel('Number of Trees', size = 10)
pl.xticks(rotation = 90)
plt.show()
|
Issues plotting a histogram of a csv file on google colab
|
I am new to google colab and I am trying to plot a histogram of a csv file using matplotlib, but getting error.
This code is able to read and show my data
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import pylab as pl
df = pd.read_csv('tree_result.csv')
df
but when I try to plot a histogram with two fields from the data, I get an error
fig, ax = plt.subplots(figsize = (50,10))
x = df['spc_common']
y = df['count']
plt.bar(x, height=y,align = 'center', width = 0.8)
plt.xlabel('Name of Trees (common name)', size = 10)
plt.ylabel('Number of Trees', size = 10)
pl.xticks(rotation = 90)
plt.show()
error message
TypeError: 'value' must be an instance of str or bytes, not a float
|
[
"To solve this I changed the datatype to string. That fixed it issue\nfig, ax = plt.subplots(figsize = (50,10))\nx = df['spc_common'].astype(str)\ny = df['count']\nplt.bar(x, height=y,align = 'center', width = 0.8)\nplt.xlabel('Name of Trees (common name)', size = 10)\nplt.ylabel('Number of Trees', size = 10)\npl.xticks(rotation = 90)\nplt.show()\n\n"
] |
[
0
] |
[] |
[] |
[
"google_colaboratory",
"python"
] |
stackoverflow_0074491808_google_colaboratory_python.txt
|
Q:
error with notification of a new server to me in private messages
A couple of days ago the code worked, but now it gives an error, please help
`
#оповищение о новом сервере
@client.event
async def on_guild_join( guild ):
me = client.get_user(404915501727219723)
emb = discord.Embed( title = f'Я пришел на новый сервер' )
for guild in client.guilds:
category = guild.categories[0]
try:
channel = category.text_channels[0]
except:
channel = category.voice_channels[0]
link = await channel.create_invite()
emb.add_field( name = guild.name, value = f"Участников: {len(guild.members)}\nСсылка: {link}" )
await me.send( embed = emb )
`
Now it gives this error, didn't find anything on the internet.
Here is the error:
enter image description here
A:
The error is probably occuring because the first category in the guild doesn't have any channels or your bot doesn't have access to it.
I would suggest looping through all channels until you find one that you can create the invite in. Also you would still need a code for the case that there are no channels your bot can create an invite in, so the code would look like this:
link = ""
for channel in guild.channels:
try:
link = await channel.create_invite()
except:
pass
else:
break
if link == "":
link = "Failed to generate"
This should prevent every possibly occuring error
A:
According to the error message, the exception is thrown at channel = category.text_channels[0] after that the except clause was executed. It also throws list index out of range error.
The problem is that your category list is not populated with any element. I would suggest using a default value if the list has zero elements.
channel = category.text_channels[0] if not category.text_channels else YourDefaultInstance()
Modify the YourDefaultInstance() to correct the class.
|
error with notification of a new server to me in private messages
|
A couple of days ago the code worked, but now it gives an error, please help
`
#оповищение о новом сервере
@client.event
async def on_guild_join( guild ):
me = client.get_user(404915501727219723)
emb = discord.Embed( title = f'Я пришел на новый сервер' )
for guild in client.guilds:
category = guild.categories[0]
try:
channel = category.text_channels[0]
except:
channel = category.voice_channels[0]
link = await channel.create_invite()
emb.add_field( name = guild.name, value = f"Участников: {len(guild.members)}\nСсылка: {link}" )
await me.send( embed = emb )
`
Now it gives this error, didn't find anything on the internet.
Here is the error:
enter image description here
|
[
"The error is probably occuring because the first category in the guild doesn't have any channels or your bot doesn't have access to it.\nI would suggest looping through all channels until you find one that you can create the invite in. Also you would still need a code for the case that there are no channels your bot can create an invite in, so the code would look like this:\nlink = \"\"\nfor channel in guild.channels:\n try:\n link = await channel.create_invite()\n except:\n pass\n else:\n break\nif link == \"\":\n link = \"Failed to generate\"\n\nThis should prevent every possibly occuring error\n",
"According to the error message, the exception is thrown at channel = category.text_channels[0] after that the except clause was executed. It also throws list index out of range error.\nThe problem is that your category list is not populated with any element. I would suggest using a default value if the list has zero elements.\nchannel = category.text_channels[0] if not category.text_channels else YourDefaultInstance()\n\nModify the YourDefaultInstance() to correct the class.\n"
] |
[
0,
0
] |
[] |
[] |
[
"discord",
"discord.py",
"python"
] |
stackoverflow_0074497887_discord_discord.py_python.txt
|
Q:
What is the time complexity of the following algorithms, as a function of the number N of elements of mylist from position first to position last?
def mystery(mylist, first, last):
if (first == last):
return mylist[first]
mid = (first + last) // 2
return min(mystery(mylist, first, mid), mystery(mylist, mid+1, last))
Is it $O(logN)$ because every time the array size becomes half and called again?
A:
You can count exactly the operations in this function. First, one must observe that this function finds the smallest element in mylist between first and last.
We can see that return mylist[first] happens exactly once for each element of the input array, so happens exactly N times overall.
The second return (ie: return min(...)) chooses the smallest of the smallest of each half of the array. Each element in the array (except for the smallest element) is on the losing side of this min exactly once, so this statement occurs exactly N-1 times overall.
There's 2 calls to mystery for each execution of the second return statement, and none for the first return statement, and each call to mystery executes one or the other, so the total number of calls to mystery (including the initial call) is 1 + 2(N-1) = 2N-1.
|
What is the time complexity of the following algorithms, as a function of the number N of elements of mylist from position first to position last?
|
def mystery(mylist, first, last):
if (first == last):
return mylist[first]
mid = (first + last) // 2
return min(mystery(mylist, first, mid), mystery(mylist, mid+1, last))
Is it $O(logN)$ because every time the array size becomes half and called again?
|
[
"You can count exactly the operations in this function. First, one must observe that this function finds the smallest element in mylist between first and last.\nWe can see that return mylist[first] happens exactly once for each element of the input array, so happens exactly N times overall.\nThe second return (ie: return min(...)) chooses the smallest of the smallest of each half of the array. Each element in the array (except for the smallest element) is on the losing side of this min exactly once, so this statement occurs exactly N-1 times overall.\nThere's 2 calls to mystery for each execution of the second return statement, and none for the first return statement, and each call to mystery executes one or the other, so the total number of calls to mystery (including the initial call) is 1 + 2(N-1) = 2N-1.\n"
] |
[
0
] |
[] |
[] |
[
"algorithm",
"data_structures",
"python",
"recursion"
] |
stackoverflow_0074496989_algorithm_data_structures_python_recursion.txt
|
Q:
Multi-User & parallel & Dynamic workflow in Django
I'm looking for the best solution for the development of workflow engine in Django (Django-Rest-Framework) by this requirement :
permission checking/task assignment options
Parallel workflows allow to have several active tasks at once and probably have some sort of parallel sync/join functionality
dynamic workflows typically could be configuring by changing the contents of workflow database tables
The approach I found:
one approach is BPMN engines, and use the SpiffWorkflow package(which is python pure not Django)
one other approach is to use camunda API (can create limitations)
or use Django-based workflows packages that I did not find a package that supports Multi-user(permission) & Parallel & Dynamic workflows
What is the best solution for this problem?
A:
I solved this problem by django goflow package (github).
this package supports :
permission checking by user Group
task assignment to specific user or a group (push and pull strategeis)
dynamic design allow changes in workflow steps, transitions, permissions ,...
Exclusive gateway (xor gateway) and Parallel gateway (and gateway)
Any type of events (Message, Timer, Error, ...)
|
Multi-User & parallel & Dynamic workflow in Django
|
I'm looking for the best solution for the development of workflow engine in Django (Django-Rest-Framework) by this requirement :
permission checking/task assignment options
Parallel workflows allow to have several active tasks at once and probably have some sort of parallel sync/join functionality
dynamic workflows typically could be configuring by changing the contents of workflow database tables
The approach I found:
one approach is BPMN engines, and use the SpiffWorkflow package(which is python pure not Django)
one other approach is to use camunda API (can create limitations)
or use Django-based workflows packages that I did not find a package that supports Multi-user(permission) & Parallel & Dynamic workflows
What is the best solution for this problem?
|
[
"I solved this problem by django goflow package (github).\nthis package supports :\n\npermission checking by user Group\ntask assignment to specific user or a group (push and pull strategeis)\ndynamic design allow changes in workflow steps, transitions, permissions ,...\nExclusive gateway (xor gateway) and Parallel gateway (and gateway)\nAny type of events (Message, Timer, Error, ...)\n\n"
] |
[
0
] |
[] |
[] |
[
"bpmn",
"django",
"python"
] |
stackoverflow_0073551571_bpmn_django_python.txt
|
Q:
Beautiful Soup scraping Realtor.com. Four elements have same class. How to search using data-label?
I'm attempting my first web scraping using realtor.com.
While trying to extract property card info I ran into an issue searching by class. # bedrooms/#bathrooms/home square feet, and property square feet have the exact same class name.
When doing a find_all search I am unable to print "text only" because find_all prints to a list.
Is there a way for me to expand search criteria by searching by data-label??
Here is my code:
from bs4 import BeautifulSoup
import requests
#have to use to agent faker (below) specific to windows and chrome!
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"}
url = "https://www.realtor.com/realestateandhomes-search/Spring-Hill_FL"
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
#print(soup)
lists = soup.find_all('li', class_="jsx-1881802087 component_property-card")
#print(lists)
print('___________________________________________________')
#for item in soup.select('.component_property-card'):
# print(item)
# print('---------------')
for list in lists:
price = list.find('div', class_='ldp-redesign-price').text
address = list.find('div', class_='address').text
#summary = list.find('div', class_='summary-wrap').text
beds = list.find('li', class_='prop-meta')
info = [price, address, beds]
print(info)
A:
While you can use something like .find('li', {'data-label': 'pc-meta-beds'}), I think you should look into the .select method and CSS Selectors - they're awesome.
.select_one('li[data-label="pc-meta-beds"] span[data-label="meta-value"]').text [or just 'li[data-label="pc-meta-beds"]' as the selector if you're ok with the whole text like "3 beds" instead of just "3"] should give you the number of beds.
Btw, this is not what you asked about, but it's better not to give variables names like list/dict/bool (especially when it's easier to just use for l in lists...), since these are already names for existing data types in python; and also, it's safer to check that find/select has returned something before trying to get .text; if it's annoying to so for every variable, you can just do it in a loop or list-comprehension since it's all to form a list anyway - something like:
# [price, address, beds, baths, sqft, sqftlot, link]
selectors = [
'div[data-label="pc-price-wrapper"]', ## can use 'div.ldp-redesign-price'
'div[data-label="pc-address"]', ## can use 'div.address'
'li[data-label="pc-meta-beds"]',
'li[data-label="pc-meta-baths"]',
'li[data-label="pc-meta-sqft"]',
'li[data-label="pc-meta-sqftlot"]'
]
infoList = [ # first, selecting tags
([r.select_one(s) for s in selectors], r.select_one('a[href]'))
for r in soup.select('li[data-testid="result-card"]')
]# --> list of ([tags for rest of the list], hyperlink tag)
infoList = [( # getting the text (or link) from selected tags
[(t.get_text(' ').strip() if t else None) for t in tags] +
[('https://www.realtor.com'+hl.get('href')) if hl else None]
) for tags, hl in infoList]
# you can use for-loop just for printing now
for info in infoList: print(info)
## although, you could also: # print('\n'.join([str(info) for info in infoList]))
Using .get_text() instead of .text is mostly a matter of preference, however some versions of bs4 do raise an error if .text is tried on anything other than a NavigableString. Anyway, the output printed should be:
['$270,000', '12009 Viking St , Springhill , FL 34609', '3 bed', '2 bath', '1,655 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/12009-Viking-St_Spring-Hill_FL_34609_M53100-62430']
['$245,000', '6139 Waycross Dr , Springhill , FL 34606', '2 bed', '2 bath', '1,360 sqft', '0.32 acre lot', 'https://www.realtor.com/realestateandhomes-detail/6139-Waycross-Dr_Spring-Hill_FL_34606_M67332-22881']
['$265,000', '14075 Amero Ln , Springhill , FL 34609', '3 bed', '2 bath', '1,085 sqft', '0.24 acre lot', 'https://www.realtor.com/realestateandhomes-detail/14075-Amero-Ln_Spring-Hill_FL_34609_M52183-50946']
['$295,000', '5560 Baffin Cir , Springhill , FL 34606', '3 bed', '2.5 bath', '1,498 sqft', '0.39 acre lot', 'https://www.realtor.com/realestateandhomes-detail/5560-Baffin-Cir_Spring-Hill_FL_34606_M68652-93381']
['$325,000', '4189 Castle Ave , Springhill , FL 34609', '3 bed', '2 bath', '1,412 sqft', '8,619 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/4189-Castle-Ave_Spring-Hill_FL_34609_M53650-29696']
['$450,000', '241 Sable Knoll Ct , Springhill , FL 34609', '4 bed', '3 bath', '2,516 sqft', '0.49 acre lot', 'https://www.realtor.com/realestateandhomes-detail/241-Sable-Knoll-Ct_Spring-Hill_FL_34609_M95197-79066']
['$349,999', '5101 Teather St , Springhill , FL 34608', '4 bed', '2 bath', '2,108 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/5101-Teather-St_Spring-Hill_FL_34608_M53924-57429']
['$96,000', '7101 Pistachio St , Weeki Wachee , FL 34607', '3 bed', '2 bath', '876 sqft', '0.26 acre lot', 'https://www.realtor.com/realestateandhomes-detail/7101-Pistachio-St_Weeki-Wachee_FL_34607_M58885-41656']
['$320,000', '14018 Wilburton St , Springhill , FL 34609', '3 bed', '2 bath', '1,575 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/14018-Wilburton-St_Spring-Hill_FL_34609_M51973-70220']
['$239,900', '1109 Lodge Cir , Springhill , FL 34606', '2 bed', '2.5+ bath', '1,327 sqft', '0.33 acre lot', 'https://www.realtor.com/realestateandhomes-detail/1109-Lodge-Cir_Spring-Hill_FL_34606_M67820-78531']
['$429,990', '11876 Bristol Bridge Rd , Springhill , FL 34610', '4 bed', '2.5 bath', '2,370 sqft', '5,663 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/11876-Bristol-Bridge-Rd_Spring-Hill_FL_34610_M96483-93728']
['$295,000', '11119 Timbercrest Rd , Springhill , FL 34608', '3 bed', '2 bath', '1,391 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/11119-Timbercrest-Rd_Spring-Hill_FL_34608_M54442-94355']
['$359,900', '7076 Ortega Ave , Springhill , FL 34609', '4 bed', '2 bath', '1,986 sqft', '0.31 acre lot', 'https://www.realtor.com/realestateandhomes-detail/7076-Ortega-Ave_Spring-Hill_FL_34609_M55803-15045']
['$359,990', '12087 Beck St , Springhill , FL 34609', '3 bed', '2 bath', '1,932 sqft', '0.28 acre lot', 'https://www.realtor.com/realestateandhomes-detail/12087-Beck-St_Spring-Hill_FL_34609_M53475-51969']
['$275,000', '11007 Linden Dr , Springhill , FL 34609', '3 bed', '2.5 bath', '1,441 sqft', '0.28 acre lot', 'https://www.realtor.com/realestateandhomes-detail/11007-Linden-Dr_Spring-Hill_FL_34609_M50275-86586']
['$499,900', '8431 Day St , Springhill , FL 34606', '3 bed', '2 bath', '2,422 sqft', '0.45 acre lot', 'https://www.realtor.com/realestateandhomes-detail/8431-Day-St_Spring-Hill_FL_34606_M57954-88598']
['$269,999', '1451 Bentley Ave , Springhill , FL 34608', '3 bed', '2 bath', '1,665 sqft', '0.26 acre lot', 'https://www.realtor.com/realestateandhomes-detail/1451-Bentley-Ave_Spring-Hill_FL_34608_M50172-63920']
['$249,900', '1394 Escobar Ave , Springhill , FL 34608', '2 bed', '2 bath', '1,059 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/1394-Escobar-Ave_Spring-Hill_FL_34608_M50149-53432']
['$400,000', '10124 Swanson Ct , Springhill , FL 34608', '3 bed', '2 bath', '1,995 sqft', '0.4 acre lot', 'https://www.realtor.com/realestateandhomes-detail/10124-Swanson-Ct_Spring-Hill_FL_34608_M54014-92845']
['From $443,990', 'Barrington at Sterling Hill 13111 Pepper Stem Street , Spring Hill , FL 34609', '4 bed', '3.5 bath', '3,278 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/Jordyn-II_Barrington-at-Sterling-Hill_13111-Pepper-Stem-Street_Spring-Hill_FL_34609_P417000633685']
['$449,275', '2484 Magellan Ave , Springhill , FL 34608', '4 bed', '3 bath', '2,286 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/2484-Magellan-Ave_Spring-Hill_FL_34608_M54060-54362']
['$555,450', '13117 Curry Dr , Springhill , FL 34609', '4 bed', '3 bath', '3,526 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/13117-Curry-Dr_Spring-Hill_FL_34609_M60772-25359']
['$323,700', '2137 Ardenwood Dr , Springhill , FL 34609', '3 bed', '2 bath', '1,273 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/2137-Ardenwood-Dr_Spring-Hill_FL_34609_M69293-40176']
['$346,900', '5345 Landover Blvd , Springhill , FL 34609', '4 bed', '2 bath', '1,867 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/5345-Landover-Blvd_Spring-Hill_FL_34609_M60490-69977']
['$346,990', '4366 Montano Ave , Springhill , FL 34609', '4 bed', '2 bath', '1,867 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/4366-Montano-Ave_Spring-Hill_FL_34609_M51174-41010']
['$337,200', '2409 Bishop Rd , Springhill , FL 34608', '4 bed', '2 bath', '1,546 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/2409-Bishop-Rd_Spring-Hill_FL_34608_M69984-13564']
['$382,655 $20k', '3866 Autumn Amber Dr , Springhill , FL 34609', '4 bed', '2.5 bath', '2,045 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/3866-Autumn-Amber-Dr_Spring-Hill_FL_34609_M98667-50378']
['$458,990 $20k', '3891 Autumn Amber Dr , Springhill , FL 34609', '4 bed', '3.5 bath', '3,278 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/3891-Autumn-Amber-Dr_Spring-Hill_FL_34609_M91537-51366']
['$314,990 $15k', '5287 Deltona Blvd , Springhill , FL 34606', '4 bed', '2 bath', '1,828 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/5287-Deltona-Blvd_Spring-Hill_FL_34606_M62877-29296']
['$285,000', '7303 Apache Trl , Springhill , FL 34606', '4 bed', '2 bath', '1,560 sqft', '8,000 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/7303-Apache-Trl_Spring-Hill_FL_34606_M58686-15749']
['$349,000', '377 Royal Palm Way , Springhill , FL 34608', '2 bed', '2 bath', '1,552 sqft', '7,536 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/377-Royal-Palm-Way_Spring-Hill_FL_34608_M69020-34757']
['$180,000', '2104 Bishop Rd , Springhill , FL 34608', '2 bed', '2 bath', '1,239 sqft', '0.26 acre lot', 'https://www.realtor.com/realestateandhomes-detail/2104-Bishop-Rd_Spring-Hill_FL_34608_M69974-01147']
['$310,000', '11325 Outrigger Ave , Springhill , FL 34608', '3 bed', '2 bath', '1,586 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/11325-Outrigger-Ave_Spring-Hill_FL_34608_M54248-78799']
['$210,000', '11528 Tuscanny Ave , Springhill , FL 34608', '2 bed', '1.5 bath', '870 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/11528-Tuscanny-Ave_Spring-Hill_FL_34608_M53834-76337']
['$369,900', '7328 Lamplighter St , Springhill , FL 34606', '3 bed', '2 bath', '1,589 sqft', '0.28 acre lot', 'https://www.realtor.com/realestateandhomes-detail/7328-Lamplighter-St_Spring-Hill_FL_34606_M68373-06658']
['$99,900', '6121 Cartwrite Rd , Springhill , FL 34609', '3 bed', '2 bath', '960 sqft', '1.2 acre lot', 'https://www.realtor.com/realestateandhomes-detail/6121-Cartwrite-Rd_Spring-Hill_FL_34609_M60170-68254']
['$334,900', '10416 Norvell Rd , Springhill , FL 34608', '4 bed', '2 bath', '1,763 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/10416-Norvell-Rd_Spring-Hill_FL_34608_M54284-93596']
['$284,500', '8362 Sunflower Dr , Springhill , FL 34606', '3 bed', '2 bath', '1,191 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/8362-Sunflower-Dr_Spring-Hill_FL_34606_M57947-54651']
['$229,000', '5154 Springwood Rd , Springhill , FL 34609', '2 bed', '1.5 bath', '1,188 sqft', '7,841 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/5154-Springwood-Rd_Spring-Hill_FL_34609_M55232-60888']
['$220,000', '4384 Deltona Blvd , Springhill , FL 34606', '2 bed', '2 bath', '1,119 sqft', '8,669 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/4384-Deltona-Blvd_Spring-Hill_FL_34606_M57785-69860']
['$309,000', '1032 Godfrey Ave , Springhill , FL 34609', '3 bed', '2 bath', '1,626 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/1032-Godfrey-Ave_Spring-Hill_FL_34609_M52520-39358']
|
Beautiful Soup scraping Realtor.com. Four elements have same class. How to search using data-label?
|
I'm attempting my first web scraping using realtor.com.
While trying to extract property card info I ran into an issue searching by class. # bedrooms/#bathrooms/home square feet, and property square feet have the exact same class name.
When doing a find_all search I am unable to print "text only" because find_all prints to a list.
Is there a way for me to expand search criteria by searching by data-label??
Here is my code:
from bs4 import BeautifulSoup
import requests
#have to use to agent faker (below) specific to windows and chrome!
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"}
url = "https://www.realtor.com/realestateandhomes-search/Spring-Hill_FL"
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
#print(soup)
lists = soup.find_all('li', class_="jsx-1881802087 component_property-card")
#print(lists)
print('___________________________________________________')
#for item in soup.select('.component_property-card'):
# print(item)
# print('---------------')
for list in lists:
price = list.find('div', class_='ldp-redesign-price').text
address = list.find('div', class_='address').text
#summary = list.find('div', class_='summary-wrap').text
beds = list.find('li', class_='prop-meta')
info = [price, address, beds]
print(info)
|
[
"While you can use something like .find('li', {'data-label': 'pc-meta-beds'}), I think you should look into the .select method and CSS Selectors - they're awesome.\n.select_one('li[data-label=\"pc-meta-beds\"] span[data-label=\"meta-value\"]').text [or just 'li[data-label=\"pc-meta-beds\"]' as the selector if you're ok with the whole text like \"3 beds\" instead of just \"3\"] should give you the number of beds.\n\nBtw, this is not what you asked about, but it's better not to give variables names like list/dict/bool (especially when it's easier to just use for l in lists...), since these are already names for existing data types in python; and also, it's safer to check that find/select has returned something before trying to get .text; if it's annoying to so for every variable, you can just do it in a loop or list-comprehension since it's all to form a list anyway - something like:\n# [price, address, beds, baths, sqft, sqftlot, link]\nselectors = [\n 'div[data-label=\"pc-price-wrapper\"]', ## can use 'div.ldp-redesign-price' \n 'div[data-label=\"pc-address\"]', ## can use 'div.address'\n 'li[data-label=\"pc-meta-beds\"]', \n 'li[data-label=\"pc-meta-baths\"]', \n 'li[data-label=\"pc-meta-sqft\"]',\n 'li[data-label=\"pc-meta-sqftlot\"]'\n]\ninfoList = [ # first, selecting tags\n ([r.select_one(s) for s in selectors], r.select_one('a[href]'))\n for r in soup.select('li[data-testid=\"result-card\"]')\n]# --> list of ([tags for rest of the list], hyperlink tag)\n\ninfoList = [( # getting the text (or link) from selected tags\n [(t.get_text(' ').strip() if t else None) for t in tags] + \n [('https://www.realtor.com'+hl.get('href')) if hl else None]\n) for tags, hl in infoList]\n\n# you can use for-loop just for printing now\nfor info in infoList: print(info)\n## although, you could also: # print('\\n'.join([str(info) for info in infoList]))\n\nUsing .get_text() instead of .text is mostly a matter of preference, however some versions of bs4 do raise an error if .text is tried on anything other than a NavigableString. Anyway, the output printed should be:\n['$270,000', '12009 Viking St , Springhill , FL 34609', '3 bed', '2 bath', '1,655 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/12009-Viking-St_Spring-Hill_FL_34609_M53100-62430']\n['$245,000', '6139 Waycross Dr , Springhill , FL 34606', '2 bed', '2 bath', '1,360 sqft', '0.32 acre lot', 'https://www.realtor.com/realestateandhomes-detail/6139-Waycross-Dr_Spring-Hill_FL_34606_M67332-22881']\n['$265,000', '14075 Amero Ln , Springhill , FL 34609', '3 bed', '2 bath', '1,085 sqft', '0.24 acre lot', 'https://www.realtor.com/realestateandhomes-detail/14075-Amero-Ln_Spring-Hill_FL_34609_M52183-50946']\n['$295,000', '5560 Baffin Cir , Springhill , FL 34606', '3 bed', '2.5 bath', '1,498 sqft', '0.39 acre lot', 'https://www.realtor.com/realestateandhomes-detail/5560-Baffin-Cir_Spring-Hill_FL_34606_M68652-93381']\n['$325,000', '4189 Castle Ave , Springhill , FL 34609', '3 bed', '2 bath', '1,412 sqft', '8,619 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/4189-Castle-Ave_Spring-Hill_FL_34609_M53650-29696']\n['$450,000', '241 Sable Knoll Ct , Springhill , FL 34609', '4 bed', '3 bath', '2,516 sqft', '0.49 acre lot', 'https://www.realtor.com/realestateandhomes-detail/241-Sable-Knoll-Ct_Spring-Hill_FL_34609_M95197-79066']\n['$349,999', '5101 Teather St , Springhill , FL 34608', '4 bed', '2 bath', '2,108 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/5101-Teather-St_Spring-Hill_FL_34608_M53924-57429']\n['$96,000', '7101 Pistachio St , Weeki Wachee , FL 34607', '3 bed', '2 bath', '876 sqft', '0.26 acre lot', 'https://www.realtor.com/realestateandhomes-detail/7101-Pistachio-St_Weeki-Wachee_FL_34607_M58885-41656']\n['$320,000', '14018 Wilburton St , Springhill , FL 34609', '3 bed', '2 bath', '1,575 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/14018-Wilburton-St_Spring-Hill_FL_34609_M51973-70220']\n['$239,900', '1109 Lodge Cir , Springhill , FL 34606', '2 bed', '2.5+ bath', '1,327 sqft', '0.33 acre lot', 'https://www.realtor.com/realestateandhomes-detail/1109-Lodge-Cir_Spring-Hill_FL_34606_M67820-78531']\n['$429,990', '11876 Bristol Bridge Rd , Springhill , FL 34610', '4 bed', '2.5 bath', '2,370 sqft', '5,663 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/11876-Bristol-Bridge-Rd_Spring-Hill_FL_34610_M96483-93728']\n['$295,000', '11119 Timbercrest Rd , Springhill , FL 34608', '3 bed', '2 bath', '1,391 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/11119-Timbercrest-Rd_Spring-Hill_FL_34608_M54442-94355']\n['$359,900', '7076 Ortega Ave , Springhill , FL 34609', '4 bed', '2 bath', '1,986 sqft', '0.31 acre lot', 'https://www.realtor.com/realestateandhomes-detail/7076-Ortega-Ave_Spring-Hill_FL_34609_M55803-15045']\n['$359,990', '12087 Beck St , Springhill , FL 34609', '3 bed', '2 bath', '1,932 sqft', '0.28 acre lot', 'https://www.realtor.com/realestateandhomes-detail/12087-Beck-St_Spring-Hill_FL_34609_M53475-51969']\n['$275,000', '11007 Linden Dr , Springhill , FL 34609', '3 bed', '2.5 bath', '1,441 sqft', '0.28 acre lot', 'https://www.realtor.com/realestateandhomes-detail/11007-Linden-Dr_Spring-Hill_FL_34609_M50275-86586']\n['$499,900', '8431 Day St , Springhill , FL 34606', '3 bed', '2 bath', '2,422 sqft', '0.45 acre lot', 'https://www.realtor.com/realestateandhomes-detail/8431-Day-St_Spring-Hill_FL_34606_M57954-88598']\n['$269,999', '1451 Bentley Ave , Springhill , FL 34608', '3 bed', '2 bath', '1,665 sqft', '0.26 acre lot', 'https://www.realtor.com/realestateandhomes-detail/1451-Bentley-Ave_Spring-Hill_FL_34608_M50172-63920']\n['$249,900', '1394 Escobar Ave , Springhill , FL 34608', '2 bed', '2 bath', '1,059 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/1394-Escobar-Ave_Spring-Hill_FL_34608_M50149-53432']\n['$400,000', '10124 Swanson Ct , Springhill , FL 34608', '3 bed', '2 bath', '1,995 sqft', '0.4 acre lot', 'https://www.realtor.com/realestateandhomes-detail/10124-Swanson-Ct_Spring-Hill_FL_34608_M54014-92845']\n['From $443,990', 'Barrington at Sterling Hill 13111 Pepper Stem Street , Spring Hill , FL 34609', '4 bed', '3.5 bath', '3,278 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/Jordyn-II_Barrington-at-Sterling-Hill_13111-Pepper-Stem-Street_Spring-Hill_FL_34609_P417000633685']\n['$449,275', '2484 Magellan Ave , Springhill , FL 34608', '4 bed', '3 bath', '2,286 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/2484-Magellan-Ave_Spring-Hill_FL_34608_M54060-54362']\n['$555,450', '13117 Curry Dr , Springhill , FL 34609', '4 bed', '3 bath', '3,526 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/13117-Curry-Dr_Spring-Hill_FL_34609_M60772-25359']\n['$323,700', '2137 Ardenwood Dr , Springhill , FL 34609', '3 bed', '2 bath', '1,273 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/2137-Ardenwood-Dr_Spring-Hill_FL_34609_M69293-40176']\n['$346,900', '5345 Landover Blvd , Springhill , FL 34609', '4 bed', '2 bath', '1,867 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/5345-Landover-Blvd_Spring-Hill_FL_34609_M60490-69977']\n['$346,990', '4366 Montano Ave , Springhill , FL 34609', '4 bed', '2 bath', '1,867 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/4366-Montano-Ave_Spring-Hill_FL_34609_M51174-41010']\n['$337,200', '2409 Bishop Rd , Springhill , FL 34608', '4 bed', '2 bath', '1,546 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/2409-Bishop-Rd_Spring-Hill_FL_34608_M69984-13564']\n['$382,655 $20k', '3866 Autumn Amber Dr , Springhill , FL 34609', '4 bed', '2.5 bath', '2,045 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/3866-Autumn-Amber-Dr_Spring-Hill_FL_34609_M98667-50378']\n['$458,990 $20k', '3891 Autumn Amber Dr , Springhill , FL 34609', '4 bed', '3.5 bath', '3,278 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/3891-Autumn-Amber-Dr_Spring-Hill_FL_34609_M91537-51366']\n['$314,990 $15k', '5287 Deltona Blvd , Springhill , FL 34606', '4 bed', '2 bath', '1,828 sqft', None, 'https://www.realtor.com/realestateandhomes-detail/5287-Deltona-Blvd_Spring-Hill_FL_34606_M62877-29296']\n['$285,000', '7303 Apache Trl , Springhill , FL 34606', '4 bed', '2 bath', '1,560 sqft', '8,000 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/7303-Apache-Trl_Spring-Hill_FL_34606_M58686-15749']\n['$349,000', '377 Royal Palm Way , Springhill , FL 34608', '2 bed', '2 bath', '1,552 sqft', '7,536 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/377-Royal-Palm-Way_Spring-Hill_FL_34608_M69020-34757']\n['$180,000', '2104 Bishop Rd , Springhill , FL 34608', '2 bed', '2 bath', '1,239 sqft', '0.26 acre lot', 'https://www.realtor.com/realestateandhomes-detail/2104-Bishop-Rd_Spring-Hill_FL_34608_M69974-01147']\n['$310,000', '11325 Outrigger Ave , Springhill , FL 34608', '3 bed', '2 bath', '1,586 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/11325-Outrigger-Ave_Spring-Hill_FL_34608_M54248-78799']\n['$210,000', '11528 Tuscanny Ave , Springhill , FL 34608', '2 bed', '1.5 bath', '870 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/11528-Tuscanny-Ave_Spring-Hill_FL_34608_M53834-76337']\n['$369,900', '7328 Lamplighter St , Springhill , FL 34606', '3 bed', '2 bath', '1,589 sqft', '0.28 acre lot', 'https://www.realtor.com/realestateandhomes-detail/7328-Lamplighter-St_Spring-Hill_FL_34606_M68373-06658']\n['$99,900', '6121 Cartwrite Rd , Springhill , FL 34609', '3 bed', '2 bath', '960 sqft', '1.2 acre lot', 'https://www.realtor.com/realestateandhomes-detail/6121-Cartwrite-Rd_Spring-Hill_FL_34609_M60170-68254']\n['$334,900', '10416 Norvell Rd , Springhill , FL 34608', '4 bed', '2 bath', '1,763 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/10416-Norvell-Rd_Spring-Hill_FL_34608_M54284-93596']\n['$284,500', '8362 Sunflower Dr , Springhill , FL 34606', '3 bed', '2 bath', '1,191 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/8362-Sunflower-Dr_Spring-Hill_FL_34606_M57947-54651']\n['$229,000', '5154 Springwood Rd , Springhill , FL 34609', '2 bed', '1.5 bath', '1,188 sqft', '7,841 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/5154-Springwood-Rd_Spring-Hill_FL_34609_M55232-60888']\n['$220,000', '4384 Deltona Blvd , Springhill , FL 34606', '2 bed', '2 bath', '1,119 sqft', '8,669 sqft lot', 'https://www.realtor.com/realestateandhomes-detail/4384-Deltona-Blvd_Spring-Hill_FL_34606_M57785-69860']\n['$309,000', '1032 Godfrey Ave , Springhill , FL 34609', '3 bed', '2 bath', '1,626 sqft', '0.23 acre lot', 'https://www.realtor.com/realestateandhomes-detail/1032-Godfrey-Ave_Spring-Hill_FL_34609_M52520-39358']\n\n"
] |
[
0
] |
[] |
[] |
[
"beautifulsoup",
"python",
"web_scraping"
] |
stackoverflow_0074483760_beautifulsoup_python_web_scraping.txt
|
Q:
import throw ModuleNotFoundError
The import is working just fine from main.py outside of the scripts directory.
but when I use import in test directory, it doesn't work.. why?
from scripts.helpful_scripts import *
from scripts.print_something import *
print(add(1, 2))
print_something()
the Code inside main.py and test_scripts.py is exactly the same, but import in test_scripts.py throw ModuleNotFoundError.
This is how the directory looks like:
scripts--
|-- helpful_scripts.py
|-- print_something.py
|-- __init__.py
test----|
|-- test_scripts.py
|-- __init__.py
main.py
The problem is python file inside test folder doesn't recognize scripts folder as module. how to solve this?
A:
The test package donot have any package or module named scripts because the scripts is one step outside from where you are trying to execute the script.
While in main.py the directory from where you are executing the code has the package named scripts from where you can import the modules.
You may not be able to execute while being in test package the root directory must contain the imports or the pip
|
import throw ModuleNotFoundError
|
The import is working just fine from main.py outside of the scripts directory.
but when I use import in test directory, it doesn't work.. why?
from scripts.helpful_scripts import *
from scripts.print_something import *
print(add(1, 2))
print_something()
the Code inside main.py and test_scripts.py is exactly the same, but import in test_scripts.py throw ModuleNotFoundError.
This is how the directory looks like:
scripts--
|-- helpful_scripts.py
|-- print_something.py
|-- __init__.py
test----|
|-- test_scripts.py
|-- __init__.py
main.py
The problem is python file inside test folder doesn't recognize scripts folder as module. how to solve this?
|
[
"The test package donot have any package or module named scripts because the scripts is one step outside from where you are trying to execute the script.\nWhile in main.py the directory from where you are executing the code has the package named scripts from where you can import the modules.\nYou may not be able to execute while being in test package the root directory must contain the imports or the pip\n"
] |
[
1
] |
[] |
[] |
[
"modulenotfounderror",
"python"
] |
stackoverflow_0074498720_modulenotfounderror_python.txt
|
Q:
Python: errno2 No such file or directory
I am learning Python from "Learn Python the Hard Way" and searched up quite a bit on it with no solutions as of yet.
I configured the path for python to work on the command prompt. But whenever I type in
"python ex1.py"
it comes up with an error: Errno2 No such file or directory!
The code is a simple print code, nothing much there. But I do not know why it's showing this! I have all these exercises in the python directory
C:\python27\projects\ex1.py
A:
In general, windows defaults to the user directory in the command prompt. Saying "python ex1.py" is trying to find ex1.py in the C:\User\Username directory. Try moving your python script there or moving to the python projects folder using cd. Either way should fix the issue.
A:
Are you in the right directory when you type python ex1.py? In your case, does it say C:\python27\projects\ in the command prompt before you type the command in? It looks for the file in the current directory, not in any directory unless you specify it. (example: you could type python C:\python27\projects\ex1.py in this instance)
To switch directories, use the cd command
A:
im a newbie too for a little googling i found an easy way,it just.. you should change your cmd directory to where the file is.. by typing cd
in your cmd type it with space and drag your file to cmd it will change the cmd directory automaticly to the address of that file and now you can put python helloworld.py to cmd
|
Python: errno2 No such file or directory
|
I am learning Python from "Learn Python the Hard Way" and searched up quite a bit on it with no solutions as of yet.
I configured the path for python to work on the command prompt. But whenever I type in
"python ex1.py"
it comes up with an error: Errno2 No such file or directory!
The code is a simple print code, nothing much there. But I do not know why it's showing this! I have all these exercises in the python directory
C:\python27\projects\ex1.py
|
[
"In general, windows defaults to the user directory in the command prompt. Saying \"python ex1.py\" is trying to find ex1.py in the C:\\User\\Username directory. Try moving your python script there or moving to the python projects folder using cd. Either way should fix the issue.\n",
"Are you in the right directory when you type python ex1.py? In your case, does it say C:\\python27\\projects\\ in the command prompt before you type the command in? It looks for the file in the current directory, not in any directory unless you specify it. (example: you could type python C:\\python27\\projects\\ex1.py in this instance)\nTo switch directories, use the cd command\n",
"im a newbie too for a little googling i found an easy way,it just.. you should change your cmd directory to where the file is.. by typing cd\nin your cmd type it with space and drag your file to cmd it will change the cmd directory automaticly to the address of that file and now you can put python helloworld.py to cmd\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0017635269_python.txt
|
Q:
trying to move robot using the distance from camera to face
So, i am trying to move a dc motor using the distance from my face to a raspberry camera.
I have the raspberry connected to an arduino mega via serial comunication.
Currently i am testing only one dc motor.
I should say that i am using an raspberry pi 3b+ with 1 gb of ram.
This is the raspberry pi code:
`import numpy as np
import cv2
USB_PORT = "/dev/ttyUSB0" # Arduino Uno WiFi Rev2
# Imports
import serial
try:
usb = serial.Serial(USB_PORT, 9600, timeout=2)
except:
print("ERROR - Could not open USB serial port. Please check your port name and permissions.")
print("Exiting program.")
exit()
Known_distance = 76.2
Known_width = 14.3
GREEN = (0, 255, 0)
RED = (0, 0, 255)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
fonts = cv2.FONT_HERSHEY_COMPLEX
face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
def Focal_Length_Finder(measured_distance, real_width, width_in_rf_image):
focal_length = (width_in_rf_image * measured_distance) / real_width
return focal_length
def Distance_finder(Focal_Length, real_face_width, face_width_in_frame):
distance = (real_face_width * Focal_Length)/face_width_in_frame
return distance
def face_data(image):
face_width = 0
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray_image, 1.3, 5)
for (x, y, h, w) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), GREEN, 2)
face_width = w
return face_width
ref_image = cv2.imread("Ref_image.png")
ref_image_face_width = face_data(ref_image)
Focal_length_found = Focal_Length_Finder(
Known_distance, Known_width, ref_image_face_width)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
face_width_in_frame = face_data(frame)
if face_width_in_frame != 0:
Distance = Distance_finder(Focal_length_found, Known_width, face_width_in_frame)
cv2.line(frame,(30,30),(230,30),RED,32)
cv2.line(frame, (30, 30), (230, 30), BLACK, 28)
cv2.putText(
frame, f"Distance: {round(Distance,2)} CM", (30, 35),
fonts, 0.6, GREEN, 2)
if(Distance<50 ):
print("back")
elif(50<Distance<80):
print("stop")
usb.write(b'of')
elif(Distance>80):
print("forward")
usb.write(b'on')
# Display the resulting frame
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()`
and the arduino code is this:
`#include <AFMotor.h>
AF_DCMotor motor(1);
void setup() {
//mstop();
Serial.begin(9600);
}
void loop() {
if (Serial.available()) { // check for incoming serial data
String command = Serial.readString();
if (command == "on"){
forward();
}else if(command=="of"){
mstop();
}}
}
void forward(){
motor.setSpeed(200);
motor.run(FORWARD);
}
void mstop(){
motor.run(RELEASE);
}`
So, the problem is that when i run the python code it's working till the if statements, those one :
`if(Distance<50 ):
print("back")
elif(50<Distance<80):
print("stop")
usb.write(b'of')
elif(Distance>80):
print("forward")
usb.write(b'on')`
and i know that the print statements work just fine, but the usb.write(b'of') and usb.write(b'on') parts are only working sometimes.
I want them to send info to the arduino smoothly to the arduino, i tried using the sleep function but it won' t work.
I am expecting to start and to stop the motor based on the distance from the camera to my face, and to do this smoothly.
A:
Try using 1 character like '1' or '0' (use single quote instead of double, Serial.read() in arduino instead of Serial.readString(), and char instead of String.
char command = Serial.read();
if (command == '1') {
Then usb.write(b'1') and usb.write(b'0') in Python
From my past experience, I had arduino readString()s like "on " instead of "on"
|
trying to move robot using the distance from camera to face
|
So, i am trying to move a dc motor using the distance from my face to a raspberry camera.
I have the raspberry connected to an arduino mega via serial comunication.
Currently i am testing only one dc motor.
I should say that i am using an raspberry pi 3b+ with 1 gb of ram.
This is the raspberry pi code:
`import numpy as np
import cv2
USB_PORT = "/dev/ttyUSB0" # Arduino Uno WiFi Rev2
# Imports
import serial
try:
usb = serial.Serial(USB_PORT, 9600, timeout=2)
except:
print("ERROR - Could not open USB serial port. Please check your port name and permissions.")
print("Exiting program.")
exit()
Known_distance = 76.2
Known_width = 14.3
GREEN = (0, 255, 0)
RED = (0, 0, 255)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
fonts = cv2.FONT_HERSHEY_COMPLEX
face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
def Focal_Length_Finder(measured_distance, real_width, width_in_rf_image):
focal_length = (width_in_rf_image * measured_distance) / real_width
return focal_length
def Distance_finder(Focal_Length, real_face_width, face_width_in_frame):
distance = (real_face_width * Focal_Length)/face_width_in_frame
return distance
def face_data(image):
face_width = 0
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray_image, 1.3, 5)
for (x, y, h, w) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), GREEN, 2)
face_width = w
return face_width
ref_image = cv2.imread("Ref_image.png")
ref_image_face_width = face_data(ref_image)
Focal_length_found = Focal_Length_Finder(
Known_distance, Known_width, ref_image_face_width)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Our operations on the frame come here
face_width_in_frame = face_data(frame)
if face_width_in_frame != 0:
Distance = Distance_finder(Focal_length_found, Known_width, face_width_in_frame)
cv2.line(frame,(30,30),(230,30),RED,32)
cv2.line(frame, (30, 30), (230, 30), BLACK, 28)
cv2.putText(
frame, f"Distance: {round(Distance,2)} CM", (30, 35),
fonts, 0.6, GREEN, 2)
if(Distance<50 ):
print("back")
elif(50<Distance<80):
print("stop")
usb.write(b'of')
elif(Distance>80):
print("forward")
usb.write(b'on')
# Display the resulting frame
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()`
and the arduino code is this:
`#include <AFMotor.h>
AF_DCMotor motor(1);
void setup() {
//mstop();
Serial.begin(9600);
}
void loop() {
if (Serial.available()) { // check for incoming serial data
String command = Serial.readString();
if (command == "on"){
forward();
}else if(command=="of"){
mstop();
}}
}
void forward(){
motor.setSpeed(200);
motor.run(FORWARD);
}
void mstop(){
motor.run(RELEASE);
}`
So, the problem is that when i run the python code it's working till the if statements, those one :
`if(Distance<50 ):
print("back")
elif(50<Distance<80):
print("stop")
usb.write(b'of')
elif(Distance>80):
print("forward")
usb.write(b'on')`
and i know that the print statements work just fine, but the usb.write(b'of') and usb.write(b'on') parts are only working sometimes.
I want them to send info to the arduino smoothly to the arduino, i tried using the sleep function but it won' t work.
I am expecting to start and to stop the motor based on the distance from the camera to my face, and to do this smoothly.
|
[
"Try using 1 character like '1' or '0' (use single quote instead of double, Serial.read() in arduino instead of Serial.readString(), and char instead of String.\nchar command = Serial.read();\nif (command == '1') {\n\nThen usb.write(b'1') and usb.write(b'0') in Python\nFrom my past experience, I had arduino readString()s like \"on \" instead of \"on\"\n"
] |
[
0
] |
[] |
[] |
[
"arduino",
"arduino_c++",
"python",
"raspberry_pi3",
"serial_port"
] |
stackoverflow_0074498667_arduino_arduino_c++_python_raspberry_pi3_serial_port.txt
|
Q:
Parse list to get new list with same structure
I applied a previous code for a log, to get the following list
log = ['',
'',
'ABC KLSC: XYZ',
'',
'some text',
'some text',
'%%ABC KLSC: XYZ',
'some text',
'',
'ID = 5',
'TME = KRE',
'DDFFLE = SOFYU',
'QWWRTYA = GRRZNY',
'',
'some text',
'-----------------------------------------------',
'',
'QUWERW WALS RUSZ CRORS ELME',
'P <NULL> R 98028',
'P <NULL> R 30310',
'',
'',
'Some text',
'',
'Some text',
'',
'--- FINISH'
]
and I want to filter those lines in order to get a list with only the lines that contains "=" and the
lines that are ordered in columns format (those below headers QUWERW, WALS, RUSZ, CRORS), but additionally, for those lines with column format, store
each value with its corresponding header.
I was able to filter the desired lines with code below (not sure here if there is a better condition to filter the lines with columns)
d1 = [line for line in log if len(line) > 50 or " = " in line]
d1
>>
[
'ID = 5',
'TME = KRE',
'DDFFLE = SOFYU',
'QWWRTYA = GRRZNY',
'QUWERW WALS RUSZ CRORS ELME',
'P <NULL> R 98028',
'P <NULL> R 30310',
]
But I don´t know how to get the output I'm looking for as follows. Thanks for any help
[
'ID = 5',
'TME = KRE',
'DDFFLE = SOFYU',
'QWWRTYA = GRRZNY',
'QUWERW = P',
'WALS = <NULL>',
'RUSZ = R',
'CRORS = 98028',
'QUWERW = P',
'WALS = <NULL>',
'RUSZ = R',
'CRORS = 30310'
]
A:
Finding the = is straight-forward. One way to find the column values might be, as follows, to identify header rows that contain the headings, and then zipping the following rows when splitting by white-space.
items_list = []
for item in log:
if '=' in item:
items_list.append(item)
elif len(item.split()) > 3:
splits = item.split()
if all(header in splits for header in ['QUWERW', 'WALS', 'RUSZ', 'CRORS']):
headers = splits
else:
for lhs,rhs in zip(headers,splits):
items_list.append(f'{lhs} = {rhs}')
print('\n'.join(items_list))
|
Parse list to get new list with same structure
|
I applied a previous code for a log, to get the following list
log = ['',
'',
'ABC KLSC: XYZ',
'',
'some text',
'some text',
'%%ABC KLSC: XYZ',
'some text',
'',
'ID = 5',
'TME = KRE',
'DDFFLE = SOFYU',
'QWWRTYA = GRRZNY',
'',
'some text',
'-----------------------------------------------',
'',
'QUWERW WALS RUSZ CRORS ELME',
'P <NULL> R 98028',
'P <NULL> R 30310',
'',
'',
'Some text',
'',
'Some text',
'',
'--- FINISH'
]
and I want to filter those lines in order to get a list with only the lines that contains "=" and the
lines that are ordered in columns format (those below headers QUWERW, WALS, RUSZ, CRORS), but additionally, for those lines with column format, store
each value with its corresponding header.
I was able to filter the desired lines with code below (not sure here if there is a better condition to filter the lines with columns)
d1 = [line for line in log if len(line) > 50 or " = " in line]
d1
>>
[
'ID = 5',
'TME = KRE',
'DDFFLE = SOFYU',
'QWWRTYA = GRRZNY',
'QUWERW WALS RUSZ CRORS ELME',
'P <NULL> R 98028',
'P <NULL> R 30310',
]
But I don´t know how to get the output I'm looking for as follows. Thanks for any help
[
'ID = 5',
'TME = KRE',
'DDFFLE = SOFYU',
'QWWRTYA = GRRZNY',
'QUWERW = P',
'WALS = <NULL>',
'RUSZ = R',
'CRORS = 98028',
'QUWERW = P',
'WALS = <NULL>',
'RUSZ = R',
'CRORS = 30310'
]
|
[
"Finding the = is straight-forward. One way to find the column values might be, as follows, to identify header rows that contain the headings, and then zipping the following rows when splitting by white-space.\nitems_list = []\nfor item in log:\n if '=' in item:\n items_list.append(item)\n elif len(item.split()) > 3:\n splits = item.split()\n if all(header in splits for header in ['QUWERW', 'WALS', 'RUSZ', 'CRORS']):\n headers = splits\n else:\n for lhs,rhs in zip(headers,splits):\n items_list.append(f'{lhs} = {rhs}')\n\nprint('\\n'.join(items_list))\n\n"
] |
[
2
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0074498676_list_python.txt
|
Q:
Finding the maximum digit in an integer
I want to find the max value of a number that consists of
for example:
123 (max digit is 3)
346 (max digit is 6)
like that.
I know how to find among several numbers:
numbers = [9, 34, 11, -4, 27]
# find the maximum number
max_number = max(numbers)
print(max_number)
But I can't find in a number.
|
Finding the maximum digit in an integer
|
I want to find the max value of a number that consists of
for example:
123 (max digit is 3)
346 (max digit is 6)
like that.
I know how to find among several numbers:
numbers = [9, 34, 11, -4, 27]
# find the maximum number
max_number = max(numbers)
print(max_number)
But I can't find in a number.
|
[] |
[] |
[
"#this is just an example for maximum numbers\nnumb = [11,21,211,5,-7,0]\ntemp = max(numb)\nprint(temp)\n"
] |
[
-2
] |
[
"python"
] |
stackoverflow_0074498942_python.txt
|
Q:
How to set up SFTPSensor in Airflow to react on any file appearing on the server?
I am pretty new to Airflow. I am trying to set up SFTPSensor to look on the folder on the SFTP server for any file appear. It sounds for me like a regular expression "*" in the file_pattern property:
import airflow
import logging
from airflow import DAG
from airflow.operators.dummy import DummyOperator
from airflow.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.providers.sftp.hooks.sftp import SFTPHook
from airflow.providers.sftp.sensors.sftp import SFTPSensor
from airflow.sensors.python import PythonSensor
from datetime import datetime, timedelta
args = {
"owner": "My_company",
"start_date": datetime(2022,10,17)}
def get_list_of_files():
ftp_hook = SFTPHook(ftp_conn_id="My_company")
files_list = ftp_hook.list_directory("/in/")
logging.info("The list of files is the following:")
logging.info(files_list)
return files_list
dag = DAG(
dag_id = "Checking_SFTP_Server_with_sensor",
default_args=args,
schedule_interval="0 8 * * *",
dagrun_timeout=timedelta(minutes=1),
tags=['My_company'])
check_SFTP = SFTPSensor(task_id="check_SFTP",
sftp_conn_id="My_company",
path="/in/",
file_pattern="*",
poke_interval=15,
timeout=60*5,
dag=dag
)
start = DummyOperator(task_id='start', dag = dag)
def createOrderProcessingTask(file):
return TriggerDagRunOperator(
task_id = f'process_order_{file}',
trigger_dag_id = "Processing_the_order",
conf = {"file_name": file},
dag = dag
)
end = DummyOperator(task_id='end', dag = dag)
files = get_list_of_files()
check_SFTP >> start
for file in files:
task = createOrderProcessingTask(file)
start >> task >> end
But I can't handle that property "file_pattern". The DAG above breaks with the error:
Broken DAG: [/opt/airflow/dags/repo/dags/check_sftp_server_with_sensor.py] Traceback (most recent call last):
File "/home/airflow/.local/lib/python3.7/site-packages/airflow/models/baseoperator.py", line 390, in apply_defaults
result = func(self, **kwargs, default_args=default_args)
File "/home/airflow/.local/lib/python3.7/site-packages/airflow/models/baseoperator.py", line 744, in __init__
f"Invalid arguments were passed to {self.__class__.__name__} (task_id: {task_id}). "
airflow.exceptions.AirflowException: Invalid arguments were passed to SFTPSensor (task_id: check_SFTP). Invalid arguments were:
**kwargs: {'file_pattern': '*'}
What am I missing? Should I use the different approach for that problem?
A:
You probably mixed up the order of your keyword arguments
Have a look at the signature:
SFTPSensor(*, path, file_pattern='', newer_than=None, sftp_conn_id='sftp_default', **kwargs)
You'll see that certain arguments (path, file_pattern, newer_than and sftp_conn_id) have their own, explicit argument. If you pass any other keyword arguments, they are packed into the catch-all **kwargs dict.
In your case, you are passing task_id as your first argument. Since it's not an explicit argument, python assumes that task_id and all following arguments should be packed into kwargs.
SFTPSensor doesn't expect kwargs to contain the expicit argument file_pattern, and thus it throws the error:
Invalid arguments were: **kwargs: {'file_pattern': '*'}
Hope this helps
Summary: When calling a function, kwargs come after explicit arguments.
|
How to set up SFTPSensor in Airflow to react on any file appearing on the server?
|
I am pretty new to Airflow. I am trying to set up SFTPSensor to look on the folder on the SFTP server for any file appear. It sounds for me like a regular expression "*" in the file_pattern property:
import airflow
import logging
from airflow import DAG
from airflow.operators.dummy import DummyOperator
from airflow.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.providers.sftp.hooks.sftp import SFTPHook
from airflow.providers.sftp.sensors.sftp import SFTPSensor
from airflow.sensors.python import PythonSensor
from datetime import datetime, timedelta
args = {
"owner": "My_company",
"start_date": datetime(2022,10,17)}
def get_list_of_files():
ftp_hook = SFTPHook(ftp_conn_id="My_company")
files_list = ftp_hook.list_directory("/in/")
logging.info("The list of files is the following:")
logging.info(files_list)
return files_list
dag = DAG(
dag_id = "Checking_SFTP_Server_with_sensor",
default_args=args,
schedule_interval="0 8 * * *",
dagrun_timeout=timedelta(minutes=1),
tags=['My_company'])
check_SFTP = SFTPSensor(task_id="check_SFTP",
sftp_conn_id="My_company",
path="/in/",
file_pattern="*",
poke_interval=15,
timeout=60*5,
dag=dag
)
start = DummyOperator(task_id='start', dag = dag)
def createOrderProcessingTask(file):
return TriggerDagRunOperator(
task_id = f'process_order_{file}',
trigger_dag_id = "Processing_the_order",
conf = {"file_name": file},
dag = dag
)
end = DummyOperator(task_id='end', dag = dag)
files = get_list_of_files()
check_SFTP >> start
for file in files:
task = createOrderProcessingTask(file)
start >> task >> end
But I can't handle that property "file_pattern". The DAG above breaks with the error:
Broken DAG: [/opt/airflow/dags/repo/dags/check_sftp_server_with_sensor.py] Traceback (most recent call last):
File "/home/airflow/.local/lib/python3.7/site-packages/airflow/models/baseoperator.py", line 390, in apply_defaults
result = func(self, **kwargs, default_args=default_args)
File "/home/airflow/.local/lib/python3.7/site-packages/airflow/models/baseoperator.py", line 744, in __init__
f"Invalid arguments were passed to {self.__class__.__name__} (task_id: {task_id}). "
airflow.exceptions.AirflowException: Invalid arguments were passed to SFTPSensor (task_id: check_SFTP). Invalid arguments were:
**kwargs: {'file_pattern': '*'}
What am I missing? Should I use the different approach for that problem?
|
[
"You probably mixed up the order of your keyword arguments\nHave a look at the signature:\nSFTPSensor(*, path, file_pattern='', newer_than=None, sftp_conn_id='sftp_default', **kwargs)\n\nYou'll see that certain arguments (path, file_pattern, newer_than and sftp_conn_id) have their own, explicit argument. If you pass any other keyword arguments, they are packed into the catch-all **kwargs dict.\nIn your case, you are passing task_id as your first argument. Since it's not an explicit argument, python assumes that task_id and all following arguments should be packed into kwargs.\nSFTPSensor doesn't expect kwargs to contain the expicit argument file_pattern, and thus it throws the error:\nInvalid arguments were: **kwargs: {'file_pattern': '*'}\n\nHope this helps\nSummary: When calling a function, kwargs come after explicit arguments.\n"
] |
[
0
] |
[] |
[] |
[
"airflow",
"filepattern",
"python"
] |
stackoverflow_0074498822_airflow_filepattern_python.txt
|
Q:
What is the fastest way to generate 100 000 000 normally distributed values?
I am struggling with generating a large list having normal values mean=5.357 and std-dev=2.37
Original list
org_list=[3.65, 4.11, 1.63, 6.7, 9, 7.61, 5.5, 2.9, 3.99, 8.48]
Candidates methods
Currently I am trying to use the following modules: random.normalvariate, random.gauss and np.normal
Tryings and goal
First I tried them on a relatively reduced length:
For random.normalvariate I got:
new_list_normalvariate = [random.normalvariate(5.357, 2.37) for x in range(1000)]
print(new_list_normalvariate[0:10])
print('mean = ', np.mean(new_list_normalvariate))
print('std = ', np.std(new_list_normalvariate))
>>> [6.576049386450241, 8.62262371117091, 4.921246966899101, 6.751587914411607, 5.6042223736139105, 4.493753810671122, 7.868066836581562, 6.299169672752275, 6.081202725113191, 7.27255885543875]
>>> mean = 5.3337034248054875
>>> std = 2.4124820216611336
For random.gauss I got:
new_list_gauss = [random.gauss(5.357, 2.37) for x in range(1000)]
print(new_list_gauss[0:10])
print('mean = ', np.mean(new_list_gauss))
print('std = ', np.std(new_list_gauss))
>>> [4.160280814524453, 8.376767324676795, 8.476968737124544, 6.050223384914485, 2.6635671201126785, 2.4441297408189167, 7.624650437282289, 7.5957096799039485, 1.990806588702878, 1.7821756994741982]
>>> mean = 5.347638951117946
>>> std = 2.374617608342891
And for np.normal I got:
new_list_np_normal = [np.random.normal(5.357, 2.37) for x in range(1000)]
print(new_list_np_normal[0:10])
print('mean = ', np.mean(new_list_np_normal))
print('std = ', np.std(new_list_np_normal))
>>> [4.294445875786478, 4.930900785615266, 8.244969311017886, 3.380908919026986, 3.636133194752361, 6.191836517294145, 5.17400630491519, 3.16529157634111, 1.9176117359394778, 8.269659173531764]
>>> mean = 5.417575775284877
>>> std = 2.373787525312793
Problem
When I make the size very large (e.g. 10000000), it seems that each of above methods take long time.
new_list_gauss = [random.gauss(5.357, 2.37) for x in range(10000000)]
So I want a best method allowing me to generate a large number of normal values with a low time cost.
A:
If you use the size argument of np.normal, it is pretty fast. I.e. np.random.normal(5.357, 2.37, size=(10000000)) executes in less than half a second on my machine, compared to 24 seconds for the list comprehension approach
|
What is the fastest way to generate 100 000 000 normally distributed values?
|
I am struggling with generating a large list having normal values mean=5.357 and std-dev=2.37
Original list
org_list=[3.65, 4.11, 1.63, 6.7, 9, 7.61, 5.5, 2.9, 3.99, 8.48]
Candidates methods
Currently I am trying to use the following modules: random.normalvariate, random.gauss and np.normal
Tryings and goal
First I tried them on a relatively reduced length:
For random.normalvariate I got:
new_list_normalvariate = [random.normalvariate(5.357, 2.37) for x in range(1000)]
print(new_list_normalvariate[0:10])
print('mean = ', np.mean(new_list_normalvariate))
print('std = ', np.std(new_list_normalvariate))
>>> [6.576049386450241, 8.62262371117091, 4.921246966899101, 6.751587914411607, 5.6042223736139105, 4.493753810671122, 7.868066836581562, 6.299169672752275, 6.081202725113191, 7.27255885543875]
>>> mean = 5.3337034248054875
>>> std = 2.4124820216611336
For random.gauss I got:
new_list_gauss = [random.gauss(5.357, 2.37) for x in range(1000)]
print(new_list_gauss[0:10])
print('mean = ', np.mean(new_list_gauss))
print('std = ', np.std(new_list_gauss))
>>> [4.160280814524453, 8.376767324676795, 8.476968737124544, 6.050223384914485, 2.6635671201126785, 2.4441297408189167, 7.624650437282289, 7.5957096799039485, 1.990806588702878, 1.7821756994741982]
>>> mean = 5.347638951117946
>>> std = 2.374617608342891
And for np.normal I got:
new_list_np_normal = [np.random.normal(5.357, 2.37) for x in range(1000)]
print(new_list_np_normal[0:10])
print('mean = ', np.mean(new_list_np_normal))
print('std = ', np.std(new_list_np_normal))
>>> [4.294445875786478, 4.930900785615266, 8.244969311017886, 3.380908919026986, 3.636133194752361, 6.191836517294145, 5.17400630491519, 3.16529157634111, 1.9176117359394778, 8.269659173531764]
>>> mean = 5.417575775284877
>>> std = 2.373787525312793
Problem
When I make the size very large (e.g. 10000000), it seems that each of above methods take long time.
new_list_gauss = [random.gauss(5.357, 2.37) for x in range(10000000)]
So I want a best method allowing me to generate a large number of normal values with a low time cost.
|
[
"If you use the size argument of np.normal, it is pretty fast. I.e. np.random.normal(5.357, 2.37, size=(10000000)) executes in less than half a second on my machine, compared to 24 seconds for the list comprehension approach\n"
] |
[
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074499032_python.txt
|
Q:
Button object not callable in Tkinter
I am trying to create a calculator app using Tkinter in python.
However, when I am trying to input my text in entry box i am getting the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Optimus\anaconda3\envs\virtual_enviournment\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\Optimus\AppData\Local\Temp/ipykernel_2608/2120973008.py", line 18, in <lambda>
button_7=Button(root, text="7", padx=40,pady=20, command=lambda: button_click(7))
TypeError: 'Button' object is not callable
my Code for the app is:
from tkinter import *
root=Tk()
root.title("Simple Calculator")
e=Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10 )
def button_click(number):
e.delete(0, END)
e.insert(0, number)
#Define buttons
button_1=Button(root, text="1", padx=40,pady=20, command=lambda: button_click(1))
button_2=Button(root, text="2", padx=40,pady=20, command=lambda: button_click(2))
button_3=Button(root, text="3", padx=40,pady=20, command=lambda: button_click(3))
button_4=Button(root, text="4", padx=40,pady=20, command=lambda: button_click(4))
button_5=Button(root, text="5", padx=40,pady=20, command=lambda: button_click(5))
button_6=Button(root, text="6", padx=40,pady=20, command=lambda: button_click(6))
button_7=Button(root, text="7", padx=40,pady=20, command=lambda: button_click(7))
button_8=Button(root, text="8", padx=40,pady=20, command=lambda: button_click(8))
button_9=Button(root, text="9", padx=40,pady=20, command=lambda: button_click(9))
button_0=Button(root, text="0", padx=40,pady=20, command=lambda: button_click(0))
button_click=Button(root, text="+", padx=40,pady=20, command=lambda: button_click())
button_equals=Button(root, text="=", padx=120,pady=20, command=lambda: button_click())
button_clear=Button(root, text="Clear", padx=30,pady=20, command=lambda: button_click())
# Put the bottons
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_click.grid(row=4, column=1)
button_equals.grid(row=6, column=0, columnspan=3)
button_clear.grid(row=4, column=2)
root.mainloop()
Text is not getting entered in entry box.
A:
You have a function button_click whereas you also have a button with the same name. Hence when you are passing a function in the command, the button calls by that name but by that time the button_click is just a Button that isn't callable.
Rename the function to Click_Button or rename the button in case the function does not have the same name as anything else it will work
A:
It seems to be because of this line:
button_click=Button(root, text="+", padx=40,pady=20, command=lambda: button_click())
Where you redefine button_click as a Button.
A:
I found a workaround for this problem, however, it makes the code a bit complex if there are greater number of buttons.
There is code for it:
from tkinter import *
from functools import partial
root=Tk()
root.title("Simple Calculator")
e=Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10 )
def button_click(number):
e.delete(0, END)
e.insert(0, number)
action_with_arg1 = partial(button_click, 1)
action_with_arg2 = partial(button_click, 2)
action_with_arg3 = partial(button_click, 3)
action_with_arg4 = partial(button_click, 4)
action_with_arg5 = partial(button_click, 5)
action_with_arg6 = partial(button_click, 6)
action_with_arg7 = partial(button_click, 7)
action_with_arg8 = partial(button_click, 8)
action_with_arg9 = partial(button_click, 9)
action_with_arg0 = partial(button_click, 0)
#Define buttons
button_1=Button(root, text="1", padx=40,pady=20, command=action_with_arg1)
button_2=Button(root, text="2", padx=40,pady=20, command=action_with_arg2)
button_3=Button(root, text="3", padx=40,pady=20, command=action_with_arg3)
button_4=Button(root, text="4", padx=40,pady=20, command=action_with_arg4)
button_5=Button(root, text="5", padx=40,pady=20, command=action_with_arg5)
button_6=Button(root, text="6", padx=40,pady=20, command=action_with_arg6)
button_7=Button(root, text="7", padx=40,pady=20, command=action_with_arg7)
button_8=Button(root, text="8", padx=40,pady=20, command=action_with_arg8)
button_9=Button(root, text="9", padx=40,pady=20, command=action_with_arg9)
button_0=Button(root, text="0", padx=40,pady=20, command=action_with_arg0)
button_click=Button(root, text="+", padx=40,pady=20, command=button_click())
button_equals=Button(root, text="=", padx=120,pady=20, command=button_click())
button_clear=Button(root, text="Clear", padx=30,pady=20, command=button_click())
# Put the bottons
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_click.grid(row=4, column=1)
button_equals.grid(row=6, column=0, columnspan=3)
button_clear.grid(row=4, column=2)
root.mainloop()
|
Button object not callable in Tkinter
|
I am trying to create a calculator app using Tkinter in python.
However, when I am trying to input my text in entry box i am getting the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Optimus\anaconda3\envs\virtual_enviournment\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\Optimus\AppData\Local\Temp/ipykernel_2608/2120973008.py", line 18, in <lambda>
button_7=Button(root, text="7", padx=40,pady=20, command=lambda: button_click(7))
TypeError: 'Button' object is not callable
my Code for the app is:
from tkinter import *
root=Tk()
root.title("Simple Calculator")
e=Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10 )
def button_click(number):
e.delete(0, END)
e.insert(0, number)
#Define buttons
button_1=Button(root, text="1", padx=40,pady=20, command=lambda: button_click(1))
button_2=Button(root, text="2", padx=40,pady=20, command=lambda: button_click(2))
button_3=Button(root, text="3", padx=40,pady=20, command=lambda: button_click(3))
button_4=Button(root, text="4", padx=40,pady=20, command=lambda: button_click(4))
button_5=Button(root, text="5", padx=40,pady=20, command=lambda: button_click(5))
button_6=Button(root, text="6", padx=40,pady=20, command=lambda: button_click(6))
button_7=Button(root, text="7", padx=40,pady=20, command=lambda: button_click(7))
button_8=Button(root, text="8", padx=40,pady=20, command=lambda: button_click(8))
button_9=Button(root, text="9", padx=40,pady=20, command=lambda: button_click(9))
button_0=Button(root, text="0", padx=40,pady=20, command=lambda: button_click(0))
button_click=Button(root, text="+", padx=40,pady=20, command=lambda: button_click())
button_equals=Button(root, text="=", padx=120,pady=20, command=lambda: button_click())
button_clear=Button(root, text="Clear", padx=30,pady=20, command=lambda: button_click())
# Put the bottons
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_click.grid(row=4, column=1)
button_equals.grid(row=6, column=0, columnspan=3)
button_clear.grid(row=4, column=2)
root.mainloop()
Text is not getting entered in entry box.
|
[
"You have a function button_click whereas you also have a button with the same name. Hence when you are passing a function in the command, the button calls by that name but by that time the button_click is just a Button that isn't callable.\nRename the function to Click_Button or rename the button in case the function does not have the same name as anything else it will work\n",
"It seems to be because of this line:\nbutton_click=Button(root, text=\"+\", padx=40,pady=20, command=lambda: button_click())\n\nWhere you redefine button_click as a Button.\n",
"I found a workaround for this problem, however, it makes the code a bit complex if there are greater number of buttons.\nThere is code for it:\nfrom tkinter import *\nfrom functools import partial\nroot=Tk()\nroot.title(\"Simple Calculator\")\ne=Entry(root, width=35, borderwidth=5)\ne.grid(row=0, column=0, columnspan=3, padx=10, pady=10 )\n\ndef button_click(number):\n e.delete(0, END)\n e.insert(0, number)\n\naction_with_arg1 = partial(button_click, 1)\naction_with_arg2 = partial(button_click, 2)\naction_with_arg3 = partial(button_click, 3)\naction_with_arg4 = partial(button_click, 4)\naction_with_arg5 = partial(button_click, 5)\naction_with_arg6 = partial(button_click, 6)\naction_with_arg7 = partial(button_click, 7)\naction_with_arg8 = partial(button_click, 8)\naction_with_arg9 = partial(button_click, 9)\naction_with_arg0 = partial(button_click, 0)\n#Define buttons\nbutton_1=Button(root, text=\"1\", padx=40,pady=20, command=action_with_arg1)\n\nbutton_2=Button(root, text=\"2\", padx=40,pady=20, command=action_with_arg2)\nbutton_3=Button(root, text=\"3\", padx=40,pady=20, command=action_with_arg3)\nbutton_4=Button(root, text=\"4\", padx=40,pady=20, command=action_with_arg4)\nbutton_5=Button(root, text=\"5\", padx=40,pady=20, command=action_with_arg5)\nbutton_6=Button(root, text=\"6\", padx=40,pady=20, command=action_with_arg6)\nbutton_7=Button(root, text=\"7\", padx=40,pady=20, command=action_with_arg7)\nbutton_8=Button(root, text=\"8\", padx=40,pady=20, command=action_with_arg8)\nbutton_9=Button(root, text=\"9\", padx=40,pady=20, command=action_with_arg9)\nbutton_0=Button(root, text=\"0\", padx=40,pady=20, command=action_with_arg0)\nbutton_click=Button(root, text=\"+\", padx=40,pady=20, command=button_click())\nbutton_equals=Button(root, text=\"=\", padx=120,pady=20, command=button_click())\nbutton_clear=Button(root, text=\"Clear\", padx=30,pady=20, command=button_click())\n\n# Put the bottons \nbutton_1.grid(row=3, column=0)\nbutton_2.grid(row=3, column=1)\nbutton_3.grid(row=3, column=2)\nbutton_4.grid(row=2, column=0)\nbutton_5.grid(row=2, column=1)\nbutton_6.grid(row=2, column=2)\nbutton_7.grid(row=1, column=0)\nbutton_8.grid(row=1, column=1)\nbutton_9.grid(row=1, column=2)\nbutton_0.grid(row=4, column=0)\nbutton_click.grid(row=4, column=1)\nbutton_equals.grid(row=6, column=0, columnspan=3)\nbutton_clear.grid(row=4, column=2)\n\nroot.mainloop()\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0074498888_python_tkinter.txt
|
Q:
PermissionError: [Errno 1] Operation not permitted after macOS Catalina Update
After installing macOS 10.15 Catalina I am getting the following error for simple file and directory operations in Python 3.x: "PermissionError: [Errno 1] Operation not permitted"
Several operations trigger this error including opening an existing file from the cwd using open(...,'rb'), listdir() and getcwd().
After updating to Catalina and finding that Anaconda and Spyder wouldn't open I read about some of the problems. I removed Anaconda and re-installed it in /Users/myname/ using the .sh terminal installer. Conda and Spyder now open but I still can't perform the operations above.
This works:
os.chdir(basedir)
These do not work and throw the error above:
os.getcwd()
Traceback (most recent call last):
File "<ipython-input-3-a78b1fb2bab9>", line 1, in <module>
os.getcwd()
PermissionError: [Errno 1] Operation not permitted
os.listdir()
Traceback (most recent call last):
File "<ipython-input-2-67fdccf289bf>", line 1, in <module>
os.listdir()
PermissionError: [Errno 1] Operation not permitted
f=open([pre-existing file],'rb')
However, this does NOT throw the error:
f=open('f1.txt','wb')
f.close()
f=open('f1.txt','rb')
I've already tried setting Full Disk Access permissions for Anaconda and Spyder.
A:
Go to System Preference->Security and Privacy.
In the below image, see Label 1
On the left side click on Full Disk Access see Label 2
Now click on bottom left lock icon and enter password to make changes, see Label 3
Now click on + sign button, see Label 4
Browse the terminal app from Application -> Utilities
Now Terminal added with permission.
Done.
A:
If you encounter this issue with Workflows / Automator scripts like I did, the following might help:
Open System Preferences -> Security & Privacy -> Privacy
Click the lock in the bottom left and enter your password to allow changes
Under 'Full Disk Access' click the '+' sign
Add Finder (to quickly find it, press CMD + Shift + G and enter /System/Library/CoreServices/Finder.app)
This should make all workflows work (again)!
A:
Solved:
What I did I create a new folder I call it 'dev' in my user folder and moved all my files & folders in there, then the permission error disappeared.
Hope this will help you as well.
A:
I had the same problem and went to the System Preferences and under Security and Privacy > Developer Tools tab, added the Anaconda program under "Allow Apps below to run software locally...." and restarted the anaconda program and it worked.
EDIT:
Something else i observed since i tried out this solution was that it only works when i run spyder from the terminal as a bash command.
A:
To access folder and files.
Go to system preferences
go to security and privacy.
In the privacy tab, select the files and folders in the left dialog.
Unlock the make changes and select the terminal.
A:
I had similar problem with PyCharm which was unable to install any packages. Running chown on the file pyvenv.cfg and setting the same user as it was set for that file before solved the problem.
A:
In Full Disk Access section add Intellij or some IDE else would do the trick.
For more: https://support.apple.com/en-us/HT210595
A:
I encountered this error because I attempted to start the http server in a directory I had deleted.
A:
I was getting this error when using Pathlib.Path.rmdir(). The issue was not permission, even though that was the error I was getting and lead me here, the documentation says the directory should be empty and mine wasn't. I used shutil.rmtree instead and it worked without granting any of the permissions mentioned here.
A:
You may add the jupter-kernel (of the env you are using) into Full disk access under Privacy in Security & Privacy.
Screenshots:
https://imgur.com/a/OQlM4zn
A:
I had similar issues when trying to install packages with pip after an upgrade to macOS Ventura.
Here's the procedure which worked for me on macOS Ventura:
Click the Apple icon in the top left corner of the screen
Go to System settings...
Select Privacy and Security in the menu on the left
Scroll down to Developer Tools in the right-hand panel and click on it
Toggle the switch next to Terminal
|
PermissionError: [Errno 1] Operation not permitted after macOS Catalina Update
|
After installing macOS 10.15 Catalina I am getting the following error for simple file and directory operations in Python 3.x: "PermissionError: [Errno 1] Operation not permitted"
Several operations trigger this error including opening an existing file from the cwd using open(...,'rb'), listdir() and getcwd().
After updating to Catalina and finding that Anaconda and Spyder wouldn't open I read about some of the problems. I removed Anaconda and re-installed it in /Users/myname/ using the .sh terminal installer. Conda and Spyder now open but I still can't perform the operations above.
This works:
os.chdir(basedir)
These do not work and throw the error above:
os.getcwd()
Traceback (most recent call last):
File "<ipython-input-3-a78b1fb2bab9>", line 1, in <module>
os.getcwd()
PermissionError: [Errno 1] Operation not permitted
os.listdir()
Traceback (most recent call last):
File "<ipython-input-2-67fdccf289bf>", line 1, in <module>
os.listdir()
PermissionError: [Errno 1] Operation not permitted
f=open([pre-existing file],'rb')
However, this does NOT throw the error:
f=open('f1.txt','wb')
f.close()
f=open('f1.txt','rb')
I've already tried setting Full Disk Access permissions for Anaconda and Spyder.
|
[
"Go to System Preference->Security and Privacy.\nIn the below image, see Label 1\nOn the left side click on Full Disk Access see Label 2\nNow click on bottom left lock icon and enter password to make changes, see Label 3\nNow click on + sign button, see Label 4\nBrowse the terminal app from Application -> Utilities\nNow Terminal added with permission.\nDone.\n\n",
"If you encounter this issue with Workflows / Automator scripts like I did, the following might help:\n\nOpen System Preferences -> Security & Privacy -> Privacy\nClick the lock in the bottom left and enter your password to allow changes\nUnder 'Full Disk Access' click the '+' sign\nAdd Finder (to quickly find it, press CMD + Shift + G and enter /System/Library/CoreServices/Finder.app)\n\nThis should make all workflows work (again)!\n",
"Solved:\nWhat I did I create a new folder I call it 'dev' in my user folder and moved all my files & folders in there, then the permission error disappeared.\nHope this will help you as well.\n",
"I had the same problem and went to the System Preferences and under Security and Privacy > Developer Tools tab, added the Anaconda program under \"Allow Apps below to run software locally....\" and restarted the anaconda program and it worked. \nEDIT:\nSomething else i observed since i tried out this solution was that it only works when i run spyder from the terminal as a bash command. \n",
"To access folder and files.\n\nGo to system preferences\ngo to security and privacy.\nIn the privacy tab, select the files and folders in the left dialog.\nUnlock the make changes and select the terminal.\n\n",
"I had similar problem with PyCharm which was unable to install any packages. Running chown on the file pyvenv.cfg and setting the same user as it was set for that file before solved the problem.\n",
"In Full Disk Access section add Intellij or some IDE else would do the trick.\nFor more: https://support.apple.com/en-us/HT210595\n",
"I encountered this error because I attempted to start the http server in a directory I had deleted.\n",
"I was getting this error when using Pathlib.Path.rmdir(). The issue was not permission, even though that was the error I was getting and lead me here, the documentation says the directory should be empty and mine wasn't. I used shutil.rmtree instead and it worked without granting any of the permissions mentioned here.\n",
"You may add the jupter-kernel (of the env you are using) into Full disk access under Privacy in Security & Privacy.\nScreenshots:\nhttps://imgur.com/a/OQlM4zn\n",
"I had similar issues when trying to install packages with pip after an upgrade to macOS Ventura.\nHere's the procedure which worked for me on macOS Ventura:\n\nClick the Apple icon in the top left corner of the screen\n\nGo to System settings...\n\nSelect Privacy and Security in the menu on the left\n\nScroll down to Developer Tools in the right-hand panel and click on it\n\nToggle the switch next to Terminal\n\n\n"
] |
[
75,
11,
2,
1,
1,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"macos_catalina",
"permissions",
"python"
] |
stackoverflow_0058479686_macos_catalina_permissions_python.txt
|
Q:
How to use pylint as a bazel run/build command?
I have seen some threads that show me how to use Pylint as a test inside bazel.
However, I want to use Pylint with one of the following commands:
bazel run --config=pylint
or
bazel build --config=pylint
What would be the best strategy here?
In the future, I will use the same strategy to also implement black and buildifier as bazel run --config=black and bazel run --config=buildifier
So I want to standarize it, if possible.
I am already able to run Pylint through a test, but this is not what I want.
A:
This is explained in the documentation. You have to setup an alias() rule that points to the correct entry_point():
load("@pip_deps//:requirements.bzl", "entry_point")
alias(
name = "pylint",
actual = entry_point("pylint"),
)
This should then be executable via bazel run :pylint.
|
How to use pylint as a bazel run/build command?
|
I have seen some threads that show me how to use Pylint as a test inside bazel.
However, I want to use Pylint with one of the following commands:
bazel run --config=pylint
or
bazel build --config=pylint
What would be the best strategy here?
In the future, I will use the same strategy to also implement black and buildifier as bazel run --config=black and bazel run --config=buildifier
So I want to standarize it, if possible.
I am already able to run Pylint through a test, but this is not what I want.
|
[
"This is explained in the documentation. You have to setup an alias() rule that points to the correct entry_point():\nload(\"@pip_deps//:requirements.bzl\", \"entry_point\")\n\nalias(\n name = \"pylint\",\n actual = entry_point(\"pylint\"),\n)\n\nThis should then be executable via bazel run :pylint.\n"
] |
[
0
] |
[] |
[] |
[
"bazel",
"pylint",
"python"
] |
stackoverflow_0074293557_bazel_pylint_python.txt
|
Q:
Step-by-step debugging with IPython
From what I have read, there are two ways to debug code in Python:
With a traditional debugger such as pdb or ipdb. This supports commands such as c for continue, n for step-over, s for step-into etc.), but you don't have direct access to an IPython shell which can be extremely useful for object inspection.
Using IPython by embedding an IPython shell in your code. You can do from IPython import embed, and then use embed() in your code. When your program/script hits an embed() statement, you are dropped into an IPython shell. This allows the full inspection of objects and testing of Python code using all the IPython goodies. However, when using embed() you can't step-by-step through the code anymore with handy keyboard shortcuts.
Is there any way to combine the best of both worlds? I.e.
Be able to step-by-step through your code with handy pdb/ipdb keyboard shortcuts.
At any such step (e.g. on a given statement), have access to a full-fledged IPython shell.
IPython debugging as in MATLAB:
An example of this type of "enhanced debugging" can be found in MATLAB, where the user always has full access to the MATLAB engine/shell, and she can still step-by-step through her code, define conditional breakpoints, etc. From what I have discussed with other users, this is the debugging feature that people miss the most when moving from MATLAB to IPython.
IPython debugging in Emacs and other editors:
I don't want to make the question too specific, but I work mostly in Emacs, so I wonder if there is any way to bring this functionality into it. Ideally, Emacs (or the editor) would allow the programmer to set breakpoints anywhere on the code and communicate with the interpreter or debugger to have it stop in the location of your choice, and bring to a full IPython interpreter on that location.
A:
What about ipdb.set_trace() ? In your code :
import ipdb; ipdb.set_trace()
update: now in Python 3.7, we can write breakpoint(). It works the same, but it also obeys to the PYTHONBREAKPOINT environment variable. This feature comes from this PEP.
This allows for full inspection of your code, and you have access to commands such as c (continue), n (execute next line), s (step into the method at point) and so on.
See the ipdb repo and a list of commands. IPython is now called (edit: part of) Jupyter.
ps: note that an ipdb command takes precedence over python code. So in order to write list(foo) you'd need print(list(foo)), or !list(foo) .
Also, if you like the ipython prompt (its emacs and vim modes, history, completions,…) it's easy to get the same for your project since it's based on the python prompt toolkit.
A:
You can use IPython's %pdb magic. Just call %pdb in IPython and when an error occurs, you're automatically dropped to ipdb. While you don't have the stepping immediately, you're in ipdb afterwards.
This makes debugging individual functions easy, as you can just load a file with %load and then run a function. You could force an error with an assert at the right position.
%pdb is a line magic. Call it as %pdb on, %pdb 1, %pdb off or %pdb 0. If called without argument it works as a toggle.
A:
(Update on May 28, 2016) Using RealGUD in Emacs
For anyone in Emacs, this thread shows how to accomplish everything described in the OP (and more) using
a new important debugger in Emacs called RealGUD which can operate with any debugger (including ipdb).
The Emacs package isend-mode.
The combination of these two packages is extremely powerful and allows one to recreate exactly the behavior described in the OP and do even more.
More info on the wiki article of RealGUD for ipdb.
Original answer:
After having tried many different methods for debugging Python, including everything mentioned in this thread, one of my preferred ways of debugging Python with IPython is with embedded shells.
Defining a custom embedded IPython shell:
Add the following on a script to your PYTHONPATH, so that the method ipsh() becomes available.
import inspect
# First import the embed function
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.config.loader import Config
# Configure the prompt so that I know I am in a nested (embedded) shell
cfg = Config()
prompt_config = cfg.PromptManager
prompt_config.in_template = 'N.In <\\#>: '
prompt_config.in2_template = ' .\\D.: '
prompt_config.out_template = 'N.Out<\\#>: '
# Messages displayed when I drop into and exit the shell.
banner_msg = ("\n**Nested Interpreter:\n"
"Hit Ctrl-D to exit interpreter and continue program.\n"
"Note that if you use %kill_embedded, you can fully deactivate\n"
"This embedded instance so it will never turn on again")
exit_msg = '**Leaving Nested interpreter'
# Wrap it in a function that gives me more context:
def ipsh():
ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)
frame = inspect.currentframe().f_back
msg = 'Stopped at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame)
# Go back one level!
# This is needed because the call to ipshell is inside the function ipsh()
ipshell(msg,stack_depth=2)
Then, whenever I want to debug something in my code, I place ipsh() right at the location where I need to do object inspection, etc. For example, say I want to debug my_function below
Using it:
def my_function(b):
a = b
ipsh() # <- This will embed a full-fledged IPython interpreter
a = 4
and then I invoke my_function(2) in one of the following ways:
Either by running a Python program that invokes this function from a Unix shell
Or by invoking it directly from IPython
Regardless of how I invoke it, the interpreter stops at the line that says ipsh(). Once you are done, you can do Ctrl-D and Python will resume execution (with any variable updates that you made). Note that, if you run the code from a regular IPython the IPython shell (case 2 above), the new IPython shell will be nested inside the one from which you invoked it, which is perfectly fine, but it's good to be aware of. Eitherway, once the interpreter stops on the location of ipsh, I can inspect the value of a (which be 2), see what functions and objects are defined, etc.
The problem:
The solution above can be used to have Python stop anywhere you want in your code, and then drop you into a fully-fledged IPython interpreter. Unfortunately it does not let you add or remove breakpoints once you invoke the script, which is highly frustrating. In my opinion, this is the only thing that is preventing IPython from becoming a great debugging tool for Python.
The best you can do for now:
A workaround is to place ipsh() a priori at the different locations where you want the Python interpreter to launch an IPython shell (i.e. a breakpoint). You can then "jump" between different pre-defined, hard-coded "breakpoints" with Ctrl-D, which would exit the current embedded IPython shell and stop again whenever the interpreter hits the next call to ipsh().
If you go this route, one way to exit "debugging mode" and ignore all subsequent breakpoints, is to use ipshell.dummy_mode = True which will make Python ignore any subsequent instantiations of the ipshell object that we created above.
A:
You can start IPython session from pudb and go back to the debugging session as you like.
BTW, ipdb is using IPython behind the scenes and you can actually use IPython functionality such as TAB completion and magic commands (the one starts with %). If you are OK with ipdb you can start it from IPython using commands such as %run and %debug. ipdb session is actually better than plain IPython one in the sense you can go up and down in the stack trace etc. What is missing in ipdb for "object inspection"?
Also, python.el bundled with Emacs >= 24.3 has nice ipdb support.
A:
Looks like the approach in @gaborous's answer is deprecated.
The new approach seems to be:
from IPython.core import debugger
debug = debugger.Pdb().set_trace
def buggy_method():
debug()
A:
Prefixing an "!" symbol to commands you type in pdb seems to have the same effect as doing something in an IPython shell. This works for accessing help for a certain function, or even variable names. Maybe this will help you to some extent. For example,
ipdb> help(numpy.transpose)
*** No help on (numpy.transpose)
But !help(numpy.transpose) will give you the expected help page on numpy.transpose. Similarly for variable names, say you have a variable l, typing "l" in pdb lists the code, but !l prints the value of l.
A:
You can start IPython from within ipdb.
Induce the ipdb debugger1:
import idpb; ipdb.set_trace()
Enter IPython from within in the ipdb> console2:
from IPython import embed; embed()
Return to the ipdb> console from within IPython:
exit
If you're lucky enough to be using Emacs, things can be made even more convenient.
This requires using M-x shell. Using yasnippet and bm, define the following snippet. This will replace the text ipdb in the editor with the set-trace line. After inserting the snippet, the line will be highlighted so that it is easily noticeable and navigable. Use M-x bm-next to navigate.
# -*- mode: snippet -*-
# name: ipdb
# key: ipdb
# expand-env: ((yas-after-exit-snippet-hook #'bm-toggle))
# --
import ipdb; ipdb.set_trace()
1 All on one line for easy deletion. Since imports only happen once, this form ensures ipdb will be imported when you need it with no extra overhead.
2 You can save yourself some typing by importing IPython within your .pdbrc file:
try:
from IPython import embed
except:
pass
This allows you to simply call embed() from within ipdb (of course, only when IPython is installed).
A:
Did you try this tip?
Or better still, use ipython, and call:
from IPython.Debugger import Tracer; debug_here = Tracer()
then you can just use
debug_here()
whenever you want to set a breakpoint
A:
the right, easy, cool, exact answer for the question is to use %run macro with -d flag.
In [4]: run -d myscript.py
NOTE: Enter 'c' at the ipdb> prompt to continue execution.
> /cygdrive/c/Users/mycodefolder/myscript.py(4)<module>()
2
3
----> 4 a=1
5 b=2
A:
One option is to use an IDE like Spyder which should allow you to interact with your code while debugging (using an IPython console, in fact). In fact, Spyder is very MATLAB-like, which I presume was intentional. That includes variable inspectors, variable editing, built-in access to documentation, etc.
A:
If you type exit() in embed() console the code continue and go to the next embed() line.
A:
The Pyzo IDE has similar capabilities as the OP asked for. You don't have to start in debug mode. Similarly to MATLAB, the commands are executed in the shell. When you set up a break-point in some source code line, the IDE stops the execution there and you can debug and issue regular IPython commands as well.
It does seem however that step-into doesn't (yet?) work well (i.e. stopping in one line and then stepping into another function) unless you set up another break-point.
Still, coming from MATLAB, this seems the best solution I've found.
A:
From python 3.2, you have the interact command, which gives you access to the full python/ipython command space.
A:
Running from inside Emacs' IPython-shell and breakpoint set via pdb.set_trace() should work.
Checked with python-mode.el, M-x ipython RET etc.
A:
Developing New Code
Debugging inside IPython
Use Jupyter/IPython cell execution to speed up experiment iterations
Use %%debug for step through
Cell Example:
%%debug
...: for n in range(4):
...: n>2
Debugging Existing Code
IPython inside debugging
Debugging a broken unit test: pytest ... --pdbcls=IPython.terminal.debugger:TerminalPdb --pdb
Debugging outside of test case: breakpoint(), python -m ipdb, etc.
IPython.embed() for full IPython functionality where needed while in the debugger
Thoughts on Python
I agree with the OP that many things MATLAB does nicely Python still does not have and really should since just about everything in the language favors development speed over production speed. Maybe someday I will contribute more than trivial bug fixes to CPython.
https://github.com/ipython/ipython/commit/f042f3fea7560afcb518a1940daa46a72fbcfa68
See also Is it possible to run commands in IPython with debugging?
A:
If put import ipdb; ipdb.set_trace() at cell outside function, it will occur error.
Using %pdb or %debug, you can only see the filnal error result. You cannot see the code doing step by step.
I use following skill:
%%writefile temp.py
.....cell code.....
save the code of cell to file temp.py.
and then
%run -i -d temp.py, it will run the cell code by pdb .
-i: run the file in IPython’s namespace instead of an empty one.
-d: run your program under the control of pdb, the Python debugger.
|
Step-by-step debugging with IPython
|
From what I have read, there are two ways to debug code in Python:
With a traditional debugger such as pdb or ipdb. This supports commands such as c for continue, n for step-over, s for step-into etc.), but you don't have direct access to an IPython shell which can be extremely useful for object inspection.
Using IPython by embedding an IPython shell in your code. You can do from IPython import embed, and then use embed() in your code. When your program/script hits an embed() statement, you are dropped into an IPython shell. This allows the full inspection of objects and testing of Python code using all the IPython goodies. However, when using embed() you can't step-by-step through the code anymore with handy keyboard shortcuts.
Is there any way to combine the best of both worlds? I.e.
Be able to step-by-step through your code with handy pdb/ipdb keyboard shortcuts.
At any such step (e.g. on a given statement), have access to a full-fledged IPython shell.
IPython debugging as in MATLAB:
An example of this type of "enhanced debugging" can be found in MATLAB, where the user always has full access to the MATLAB engine/shell, and she can still step-by-step through her code, define conditional breakpoints, etc. From what I have discussed with other users, this is the debugging feature that people miss the most when moving from MATLAB to IPython.
IPython debugging in Emacs and other editors:
I don't want to make the question too specific, but I work mostly in Emacs, so I wonder if there is any way to bring this functionality into it. Ideally, Emacs (or the editor) would allow the programmer to set breakpoints anywhere on the code and communicate with the interpreter or debugger to have it stop in the location of your choice, and bring to a full IPython interpreter on that location.
|
[
"What about ipdb.set_trace() ? In your code :\nimport ipdb; ipdb.set_trace()\nupdate: now in Python 3.7, we can write breakpoint(). It works the same, but it also obeys to the PYTHONBREAKPOINT environment variable. This feature comes from this PEP.\nThis allows for full inspection of your code, and you have access to commands such as c (continue), n (execute next line), s (step into the method at point) and so on.\nSee the ipdb repo and a list of commands. IPython is now called (edit: part of) Jupyter.\n\nps: note that an ipdb command takes precedence over python code. So in order to write list(foo) you'd need print(list(foo)), or !list(foo) .\nAlso, if you like the ipython prompt (its emacs and vim modes, history, completions,…) it's easy to get the same for your project since it's based on the python prompt toolkit.\n",
"You can use IPython's %pdb magic. Just call %pdb in IPython and when an error occurs, you're automatically dropped to ipdb. While you don't have the stepping immediately, you're in ipdb afterwards.\nThis makes debugging individual functions easy, as you can just load a file with %load and then run a function. You could force an error with an assert at the right position.\n%pdb is a line magic. Call it as %pdb on, %pdb 1, %pdb off or %pdb 0. If called without argument it works as a toggle.\n",
"(Update on May 28, 2016) Using RealGUD in Emacs\nFor anyone in Emacs, this thread shows how to accomplish everything described in the OP (and more) using\n\na new important debugger in Emacs called RealGUD which can operate with any debugger (including ipdb).\nThe Emacs package isend-mode.\n\nThe combination of these two packages is extremely powerful and allows one to recreate exactly the behavior described in the OP and do even more.\nMore info on the wiki article of RealGUD for ipdb.\n\nOriginal answer:\nAfter having tried many different methods for debugging Python, including everything mentioned in this thread, one of my preferred ways of debugging Python with IPython is with embedded shells.\nDefining a custom embedded IPython shell:\nAdd the following on a script to your PYTHONPATH, so that the method ipsh() becomes available.\nimport inspect\n\n# First import the embed function\nfrom IPython.terminal.embed import InteractiveShellEmbed\nfrom IPython.config.loader import Config\n\n# Configure the prompt so that I know I am in a nested (embedded) shell\ncfg = Config()\nprompt_config = cfg.PromptManager\nprompt_config.in_template = 'N.In <\\\\#>: '\nprompt_config.in2_template = ' .\\\\D.: '\nprompt_config.out_template = 'N.Out<\\\\#>: '\n\n# Messages displayed when I drop into and exit the shell.\nbanner_msg = (\"\\n**Nested Interpreter:\\n\"\n\"Hit Ctrl-D to exit interpreter and continue program.\\n\"\n\"Note that if you use %kill_embedded, you can fully deactivate\\n\"\n\"This embedded instance so it will never turn on again\") \nexit_msg = '**Leaving Nested interpreter'\n\n# Wrap it in a function that gives me more context:\ndef ipsh():\n ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)\n\n frame = inspect.currentframe().f_back\n msg = 'Stopped at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame)\n\n # Go back one level! \n # This is needed because the call to ipshell is inside the function ipsh()\n ipshell(msg,stack_depth=2)\n\nThen, whenever I want to debug something in my code, I place ipsh() right at the location where I need to do object inspection, etc. For example, say I want to debug my_function below\nUsing it:\ndef my_function(b):\n a = b\n ipsh() # <- This will embed a full-fledged IPython interpreter\n a = 4\n\nand then I invoke my_function(2) in one of the following ways:\n\nEither by running a Python program that invokes this function from a Unix shell\nOr by invoking it directly from IPython\n\nRegardless of how I invoke it, the interpreter stops at the line that says ipsh(). Once you are done, you can do Ctrl-D and Python will resume execution (with any variable updates that you made). Note that, if you run the code from a regular IPython the IPython shell (case 2 above), the new IPython shell will be nested inside the one from which you invoked it, which is perfectly fine, but it's good to be aware of. Eitherway, once the interpreter stops on the location of ipsh, I can inspect the value of a (which be 2), see what functions and objects are defined, etc.\nThe problem:\nThe solution above can be used to have Python stop anywhere you want in your code, and then drop you into a fully-fledged IPython interpreter. Unfortunately it does not let you add or remove breakpoints once you invoke the script, which is highly frustrating. In my opinion, this is the only thing that is preventing IPython from becoming a great debugging tool for Python.\nThe best you can do for now:\nA workaround is to place ipsh() a priori at the different locations where you want the Python interpreter to launch an IPython shell (i.e. a breakpoint). You can then \"jump\" between different pre-defined, hard-coded \"breakpoints\" with Ctrl-D, which would exit the current embedded IPython shell and stop again whenever the interpreter hits the next call to ipsh().\nIf you go this route, one way to exit \"debugging mode\" and ignore all subsequent breakpoints, is to use ipshell.dummy_mode = True which will make Python ignore any subsequent instantiations of the ipshell object that we created above.\n",
"You can start IPython session from pudb and go back to the debugging session as you like.\nBTW, ipdb is using IPython behind the scenes and you can actually use IPython functionality such as TAB completion and magic commands (the one starts with %). If you are OK with ipdb you can start it from IPython using commands such as %run and %debug. ipdb session is actually better than plain IPython one in the sense you can go up and down in the stack trace etc. What is missing in ipdb for \"object inspection\"?\nAlso, python.el bundled with Emacs >= 24.3 has nice ipdb support.\n",
"Looks like the approach in @gaborous's answer is deprecated.\nThe new approach seems to be:\nfrom IPython.core import debugger\ndebug = debugger.Pdb().set_trace\n\ndef buggy_method():\n debug()\n\n",
"Prefixing an \"!\" symbol to commands you type in pdb seems to have the same effect as doing something in an IPython shell. This works for accessing help for a certain function, or even variable names. Maybe this will help you to some extent. For example,\nipdb> help(numpy.transpose)\n*** No help on (numpy.transpose)\n\nBut !help(numpy.transpose) will give you the expected help page on numpy.transpose. Similarly for variable names, say you have a variable l, typing \"l\" in pdb lists the code, but !l prints the value of l.\n",
"You can start IPython from within ipdb.\nInduce the ipdb debugger1:\nimport idpb; ipdb.set_trace()\n\nEnter IPython from within in the ipdb> console2:\nfrom IPython import embed; embed()\n\nReturn to the ipdb> console from within IPython:\nexit\n\n\nIf you're lucky enough to be using Emacs, things can be made even more convenient.\nThis requires using M-x shell. Using yasnippet and bm, define the following snippet. This will replace the text ipdb in the editor with the set-trace line. After inserting the snippet, the line will be highlighted so that it is easily noticeable and navigable. Use M-x bm-next to navigate.\n# -*- mode: snippet -*-\n# name: ipdb\n# key: ipdb\n# expand-env: ((yas-after-exit-snippet-hook #'bm-toggle))\n# --\nimport ipdb; ipdb.set_trace()\n\n\n1 All on one line for easy deletion. Since imports only happen once, this form ensures ipdb will be imported when you need it with no extra overhead.\n2 You can save yourself some typing by importing IPython within your .pdbrc file:\ntry:\n from IPython import embed\nexcept:\n pass\n\nThis allows you to simply call embed() from within ipdb (of course, only when IPython is installed).\n",
"Did you try this tip?\n\nOr better still, use ipython, and call:\nfrom IPython.Debugger import Tracer; debug_here = Tracer()\n\nthen you can just use\ndebug_here()\n\nwhenever you want to set a breakpoint\n\n",
"the right, easy, cool, exact answer for the question is to use %run macro with -d flag.\nIn [4]: run -d myscript.py\nNOTE: Enter 'c' at the ipdb> prompt to continue execution. \n> /cygdrive/c/Users/mycodefolder/myscript.py(4)<module>()\n 2 \n 3 \n----> 4 a=1 \n 5 b=2\n\n",
"One option is to use an IDE like Spyder which should allow you to interact with your code while debugging (using an IPython console, in fact). In fact, Spyder is very MATLAB-like, which I presume was intentional. That includes variable inspectors, variable editing, built-in access to documentation, etc.\n",
"If you type exit() in embed() console the code continue and go to the next embed() line.\n",
"The Pyzo IDE has similar capabilities as the OP asked for. You don't have to start in debug mode. Similarly to MATLAB, the commands are executed in the shell. When you set up a break-point in some source code line, the IDE stops the execution there and you can debug and issue regular IPython commands as well.\nIt does seem however that step-into doesn't (yet?) work well (i.e. stopping in one line and then stepping into another function) unless you set up another break-point.\nStill, coming from MATLAB, this seems the best solution I've found.\n",
"From python 3.2, you have the interact command, which gives you access to the full python/ipython command space.\n",
"Running from inside Emacs' IPython-shell and breakpoint set via pdb.set_trace() should work.\nChecked with python-mode.el, M-x ipython RET etc.\n",
"Developing New Code\nDebugging inside IPython\n\nUse Jupyter/IPython cell execution to speed up experiment iterations\nUse %%debug for step through\n\nCell Example:\n%%debug\n...: for n in range(4):\n...: n>2\n\nDebugging Existing Code\nIPython inside debugging\n\nDebugging a broken unit test: pytest ... --pdbcls=IPython.terminal.debugger:TerminalPdb --pdb\nDebugging outside of test case: breakpoint(), python -m ipdb, etc.\nIPython.embed() for full IPython functionality where needed while in the debugger\n\nThoughts on Python\nI agree with the OP that many things MATLAB does nicely Python still does not have and really should since just about everything in the language favors development speed over production speed. Maybe someday I will contribute more than trivial bug fixes to CPython.\nhttps://github.com/ipython/ipython/commit/f042f3fea7560afcb518a1940daa46a72fbcfa68\nSee also Is it possible to run commands in IPython with debugging?\n",
"If put import ipdb; ipdb.set_trace() at cell outside function, it will occur error.\nUsing %pdb or %debug, you can only see the filnal error result. You cannot see the code doing step by step.\nI use following skill:\n%%writefile temp.py\n.....cell code.....\n\nsave the code of cell to file temp.py.\nand then\n%run -i -d temp.py, it will run the cell code by pdb .\n-i: run the file in IPython’s namespace instead of an empty one.\n-d: run your program under the control of pdb, the Python debugger.\n"
] |
[
120,
81,
40,
19,
13,
7,
6,
4,
4,
3,
2,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"debugging",
"emacs",
"ipython",
"pdb",
"python"
] |
stackoverflow_0016867347_debugging_emacs_ipython_pdb_python.txt
|
Q:
I want different authentication system for normal user and admin user in Django?
I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in into user page.
def userlogin(request):
error = ""
if request.method == 'POST':
u = request.POST['emailid']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
try:
if user:
login(request, user)
error = "no"
return redirect(profile)
else:
error = "yes"
except:
error = "yes"
return render(request, 'login.html', locals())
def login_admin(request):
error = ""
if request.method == 'POST':
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
try:
if user.is_staff:
login(request, user)
error = "no"
else:
error ="yes"
except:
error = "yes"
return render(request,'login_admin.html', locals())
This model is used for normal user signup
class Signup(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
contact = models.CharField(max_length=10)
branch = models.CharField(max_length=30)
role = models.CharField(max_length=15)
username = models.CharField(max_length=15, unique=True)
image = models.ImageField(upload_to="images/img", default="")
upvotesuser = models.IntegerField(default=0)
I want to achive different authentication system for user and also for admin.
A:
Make some roles explicitly in SignUp model as follows as Django provides that too:
admin
staff
simple user/regular user
Define the role of each user in the SignUp model. If a regular user is logged in it will definitely be filtered from the signUp model and that will return him/her as a regular/simple user.
A:
You don't need to create another model for signup
You can easily check the current user permissions
E.g
is_admin
is_staff
is_superuser
Then redirect depending on the permisions
|
I want different authentication system for normal user and admin user in Django?
|
I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in into user page.
def userlogin(request):
error = ""
if request.method == 'POST':
u = request.POST['emailid']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
try:
if user:
login(request, user)
error = "no"
return redirect(profile)
else:
error = "yes"
except:
error = "yes"
return render(request, 'login.html', locals())
def login_admin(request):
error = ""
if request.method == 'POST':
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
try:
if user.is_staff:
login(request, user)
error = "no"
else:
error ="yes"
except:
error = "yes"
return render(request,'login_admin.html', locals())
This model is used for normal user signup
class Signup(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
contact = models.CharField(max_length=10)
branch = models.CharField(max_length=30)
role = models.CharField(max_length=15)
username = models.CharField(max_length=15, unique=True)
image = models.ImageField(upload_to="images/img", default="")
upvotesuser = models.IntegerField(default=0)
I want to achive different authentication system for user and also for admin.
|
[
"Make some roles explicitly in SignUp model as follows as Django provides that too:\n\nadmin\nstaff\nsimple user/regular user\n\nDefine the role of each user in the SignUp model. If a regular user is logged in it will definitely be filtered from the signUp model and that will return him/her as a regular/simple user.\n",
"You don't need to create another model for signup\nYou can easily check the current user permissions\nE.g\n\nis_admin\nis_staff\nis_superuser\nThen redirect depending on the permisions\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"authentication",
"django",
"django_models",
"python"
] |
stackoverflow_0074498025_authentication_django_django_models_python.txt
|
Q:
Python; TypeError: 'str' object is not callable
So basically I don't understand why my code is giving me this error, I tried looking it up, but I do not understand the error or how it affects me. This is my code for a simple shop simulator.
isBuying = True
#Create a map for our store's inventory. Each item in our store will have a string name and a floating point number for its price.
store = [('arrows', 20.00), ('bombs', 40.00), ('heart container', 120.00),
('sword', 100.00), ('potion', 15.00)]
#Define a function to print out the store's inventory. This function will take in an inventory.
def PrintStore(inventory):
#For every item in the inventory, it will print out the item name and price in our formatted way.
for item in inventory:
print(' ' * 4 + item[0] + '.' * 3 + ' ' * 4 + str(item[1]))
while isBuying:
#Use our function to print out our store's inventory.
PrintStore(store)
#Ask the user what they would like to buy and store the input in a variable. Lowercase it to prevent case sensitivity.
input = input('What would you like to buy?\n')
input = input.lower()
#For every item in our store, check to see if our input is equal to the item's name. If it is, print out the item's price.
for item in store:
if input == item[0]:
print(f'That will be {item[1]} dollars.')
answer = input('Would you like to continue shopping?\n')
answer = answer.lower()
if answer == 'n' or 'no':
isBuying = False
The error is on line answer = input('Would you like to continue shopping?\n') and the error is TypeError: 'str' object is not callable
A:
You redefine the input builtin function
input = input('What would you like to buy?\n')
and now it's just a string. After that you call the input
answer = input('Would you like to continue shopping?\n')
but it is just a string (str) not a function. This is why you shouldn't use builtin functions as variable names.
|
Python; TypeError: 'str' object is not callable
|
So basically I don't understand why my code is giving me this error, I tried looking it up, but I do not understand the error or how it affects me. This is my code for a simple shop simulator.
isBuying = True
#Create a map for our store's inventory. Each item in our store will have a string name and a floating point number for its price.
store = [('arrows', 20.00), ('bombs', 40.00), ('heart container', 120.00),
('sword', 100.00), ('potion', 15.00)]
#Define a function to print out the store's inventory. This function will take in an inventory.
def PrintStore(inventory):
#For every item in the inventory, it will print out the item name and price in our formatted way.
for item in inventory:
print(' ' * 4 + item[0] + '.' * 3 + ' ' * 4 + str(item[1]))
while isBuying:
#Use our function to print out our store's inventory.
PrintStore(store)
#Ask the user what they would like to buy and store the input in a variable. Lowercase it to prevent case sensitivity.
input = input('What would you like to buy?\n')
input = input.lower()
#For every item in our store, check to see if our input is equal to the item's name. If it is, print out the item's price.
for item in store:
if input == item[0]:
print(f'That will be {item[1]} dollars.')
answer = input('Would you like to continue shopping?\n')
answer = answer.lower()
if answer == 'n' or 'no':
isBuying = False
The error is on line answer = input('Would you like to continue shopping?\n') and the error is TypeError: 'str' object is not callable
|
[
"You redefine the input builtin function\ninput = input('What would you like to buy?\\n')\n\nand now it's just a string. After that you call the input\nanswer = input('Would you like to continue shopping?\\n')\n\nbut it is just a string (str) not a function. This is why you shouldn't use builtin functions as variable names.\n"
] |
[
1
] |
[] |
[] |
[
"input",
"python",
"string",
"typeerror"
] |
stackoverflow_0074499086_input_python_string_typeerror.txt
|
Q:
How do you split an array into specific intervals in Num.py for Python?
The question follows a such:
x = np.arange(100)
Write Python code to split the following array at these intervals: 10, 25, 45, 75, 95
I have used the split function and unable to get at these specific intervals, can anyone enlighten me on another method or am i doing it wrongly?
A:
Here's both the manual way and the numpy way with split.
# Manual method
x = np.arange(100)
split_indices = [10, 25, 45, 75, 95]
split_arrays = []
for i, j in zip([0]+split_indices[:-1], split_indices):
split_arrays.append(x[i:j])
print(split_arrays)
# Numpy method
split_arrays_np = np.split(x, split_indices)
print(split_arrays_np)
And the result is (for both)
[array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]),
array([25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]),
array([45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74]),
array([75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94])
]
|
How do you split an array into specific intervals in Num.py for Python?
|
The question follows a such:
x = np.arange(100)
Write Python code to split the following array at these intervals: 10, 25, 45, 75, 95
I have used the split function and unable to get at these specific intervals, can anyone enlighten me on another method or am i doing it wrongly?
|
[
"Here's both the manual way and the numpy way with split.\n# Manual method\nx = np.arange(100)\nsplit_indices = [10, 25, 45, 75, 95]\n\nsplit_arrays = []\nfor i, j in zip([0]+split_indices[:-1], split_indices):\n split_arrays.append(x[i:j])\n\nprint(split_arrays)\n\n# Numpy method\nsplit_arrays_np = np.split(x, split_indices)\nprint(split_arrays_np)\n\nAnd the result is (for both)\n[array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), \n array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]), \n array([25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]), \n array([45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74]),\n array([75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94])\n]\n\n"
] |
[
0
] |
[] |
[] |
[
"arrays",
"concatenation",
"numpy",
"python",
"split"
] |
stackoverflow_0074499101_arrays_concatenation_numpy_python_split.txt
|
Q:
How is the value assigned to Dictionary?
This is a very simple problem where it reads file from a CSV with first column header as "title" and then counts how many times the title appears in side the dictionary. But I am not understanding in which step it is assigning the "title" to "titles" dictionary.
The code is:
import csv
titles = {}
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
if title in titles:
titles[title] = titles[title] + 1
else:
titles[title] = 1
If it is assigning inside the else block then why is my second code where I just want to assign values to the dictionary named "titles" and not count the number of times it appears, is not Working?:
import csv
titles = {}
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
if not title in titles:
titles[title]
print(titles[title])
Error: Key Value error
A:
In your second version, you have this line titles[title], which is not adding the title to your titles dictionary as you do in your first version. Since the title is missing in the dictionary, accessing it will give you a key value error. Why do you have a line titles[title] that does nothing?
But I think there's a bigger problem here with your first version of code. You want to add the title to the dictionary when it's not already in it, and add the count by 1 if otherwise. But your first version is doing the opposite, which will throw you an error.
A:
If titles is a dictionary titles[title] finds the value corresponding to the key title. Your second version does not put anything in the dictionary, so titles[title] raises a key error.
You say you want to "assign values to the dictionary but not count anything". A dictionary is the wrong structure to use for this. If you want unique titles, you could use a set:
import csv
titles = set()
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
titles.add(title)
print(titles)
Notice the add method only adds something if it does not already exist in the set, rather like a mathematical set. You no longer have key, value pairs, just items.
|
How is the value assigned to Dictionary?
|
This is a very simple problem where it reads file from a CSV with first column header as "title" and then counts how many times the title appears in side the dictionary. But I am not understanding in which step it is assigning the "title" to "titles" dictionary.
The code is:
import csv
titles = {}
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
if title in titles:
titles[title] = titles[title] + 1
else:
titles[title] = 1
If it is assigning inside the else block then why is my second code where I just want to assign values to the dictionary named "titles" and not count the number of times it appears, is not Working?:
import csv
titles = {}
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
if not title in titles:
titles[title]
print(titles[title])
Error: Key Value error
|
[
"In your second version, you have this line titles[title], which is not adding the title to your titles dictionary as you do in your first version. Since the title is missing in the dictionary, accessing it will give you a key value error. Why do you have a line titles[title] that does nothing?\nBut I think there's a bigger problem here with your first version of code. You want to add the title to the dictionary when it's not already in it, and add the count by 1 if otherwise. But your first version is doing the opposite, which will throw you an error.\n",
"If titles is a dictionary titles[title] finds the value corresponding to the key title. Your second version does not put anything in the dictionary, so titles[title] raises a key error.\nYou say you want to \"assign values to the dictionary but not count anything\". A dictionary is the wrong structure to use for this. If you want unique titles, you could use a set:\nimport csv\n\ntitles = set()\n\nwith open(\"movies.csv\", \"r\") as file:\n reader = csv.DictReader(file)\n\n for row in reader:\n #title is defined here\n title = row[\"title\"].strip().upper()\n titles.add(title)\n \nprint(titles)\n\nNotice the add method only adds something if it does not already exist in the set, rather like a mathematical set. You no longer have key, value pairs, just items.\n"
] |
[
1,
0
] |
[] |
[] |
[
"cs50",
"csv",
"dictionary",
"python",
"title"
] |
stackoverflow_0074499036_cs50_csv_dictionary_python_title.txt
|
Q:
accessing private websocket data from tradingview in python
I am able to get live ticker data and the prior 500-100 candle chart data with this code but I am unable to get data that isn't delayed for CME_MINI:ESH2021. TradingView puts a 600 second delay I believe on the public stream. I do pay for the data and I can pull it up on the web client but I am unable to get the non-delayed data on python since I am unsure how to log into TradingView via python. If someone knows how I can fix my code to do what I want it to I would greatly appreciate your input or any advice.
from websocket import create_connection
import json
import random
import string
import re
from datetime import datetime
from time import sleep
def filter_raw_message(text):
try:
found = re.search('"p":(.+?"}"])}', text).group(1)
print(found)
return found
except AttributeError:
print("error")
def generateSession():
stringLength=12
letters = string.ascii_lowercase
random_string= ''.join(random.choice(letters) for i in range(stringLength))
return "qs_" +random_string
def generateChartSession():
stringLength=12
letters = string.ascii_lowercase
random_string= ''.join(random.choice(letters) for i in range(stringLength))
return "cs_" +random_string
def prependHeader(st):
return "~m~" + str(len(st)) + "~m~" + st
def constructMessage(func, paramList):
#json_mylist = json.dumps(mylist, separators=(',', ':'))
return json.dumps({
"m":func,
"p":paramList
}, separators=(',', ':'))
def createMessage(func, paramList):
return prependHeader(constructMessage(func, paramList))
def sendRawMessage(ws, message):
ws.send(prependHeader(message))
def sendMessage(ws, func, args):
ws.send(createMessage(func, args))
# Initialize the headers needed for the websocket connection
headers = json.dumps({
'Connection': 'upgrade',
'Host': 'data.tradingview.com',
'Origin': 'https://data.tradingview.com',
'Cache-Control': 'no-cache',
'Upgrade': 'websocket',
'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
'Sec-WebSocket-Key': '1H41q97V8BbMKUq0knV1UA==',
'Sec-WebSocket-Version': '13',
'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.56',
'Pragma': 'no-cache',
'Upgrade': 'websocket'
})
# Then create a connection to the tunnel
ws = create_connection(
'wss://data.tradingview.com/socket.io/websocket',headers=headers)
session= generateSession()
print("session generated {}".format(session))
chart_session= generateChartSession()
print("chart_session generated {}".format(chart_session))
symbol = "CME_MINI:ESH2021"
timeframe = "5"
candles = 100
# Then send a message through the tunnel
sendMessage(ws, "set_auth_token", ["unauthorized_user_token"])
sendMessage(ws, "chart_create_session", [chart_session, ""])
sendMessage(ws, "quote_create_session", [session])
sendMessage(ws,"quote_set_fields", [session,"ch","chp","current_session","description","local_description","language","exchange","fractional","is_tradable","lp","lp_time","minmov","minmove2","original_name","pricescale","pro_name","short_name","type","update_mode","volume","currency_code","rchp","rtc"])
sendMessage(ws, "quote_add_symbols",[session, symbol, {"flags":['force_permission']}])
theString1 = "={\"symbol\":\""
theString2 = "\",\"adjustment\":\"splits\"}"
theString3 = theString1 + symbol + theString2
sendMessage(ws, "resolve_symbol", [chart_session, "symbol_" + timeframe, theString3])
sendMessage(ws, "create_series", [chart_session,"s" + timeframe,"s" + timeframe,"symbol_" + timeframe,timeframe,candles])
sendMessage(ws, "quote_fast_symbols", [session,symbol])
sendMessage(ws, "create_study", [chart_session,"st" + timeframe,"st" + timeframe,"s" + timeframe,"Volume@tv-basicstudies-118",{"length":20,"col_prev_close":"false"}])
sendMessage(ws, "quote_hibernate_all", [session])
# Printing all the result
a=""
while True:
try:
sleep(1)
result = ws.recv()
pattern = re.compile("~m~\d+~m~~h~\d+$")
if pattern.match(result):
ws.recv()
ws.send(result)
print("\n\n\n hhhhhhhhhhhhhhhhhhhhhh "+ str(result) + "\n\n")
print(result)
a=a+result+"\n"
except Exception as e:
print(e)
break
A:
This post is quite old, and the OP probably has the answer already, but regardless, I'm posting for people who visit this page in the future.
This solution comes from the Github page here: https://github.com/rushic24/tradingview-scraper
In fact, what I'm about to post is literally on the front page of that link. I'm just remaking it into a step-by-step guide.
In the original code, you can find the following line:
sendMessage(ws, "set_auth_token", ["unauthorized_user_token"])
Do you see the part where it says "unauthorized_user_token"? That means you're an anonymous random person to TradingView.
So you must create an auth_token to let TradingView know you're logging in as yourself and that you indeed have paid access to real-time data.
1.
Add the following to your code:
def get_auth_token():
sign_in_url = 'https://www.tradingview.com/accounts/signin/'
username = 'username'
password = 'password'
data = {"username": username, "password": password, "remember": "on"}
headers = {
'Referer': 'https://www.tradingview.com'
}
response = requests.post(url=sign_in_url, data=data, headers=headers)
auth_token = response.json()['user']['auth_token']
return auth_token
Replace 'username' and 'password' with your own.
2.
replace
sendMessage(ws, "set_auth_token", ["unauthorized_user_token"])
With the following:
auth_token = get_auth_token()
sendMessage(ws, "set_auth_token", [auth_token])
replace
ws = create_connection('wss://data.tradingview.com/socket.io/websocket', headers=headers)
With the following:
ws = create_connection( 'wss://data.tradingview.com/socket.io/websocket?from=chart/XXyour_chartXX/&date=XXXX_XX_XX-XX_XX',headers=headers)
replace 'XXyour_chartXX' with one of your saved charts' URLs. (https://www.tradingview.com/chart/***###THIS_PART###***/)
A:
this is very useful, thanks a ton!
I guess it only works with the 2FA disabled, otherwise it throws this "{'error': '2FA_required', 'code': '2FA_required', 'message': 'Second authentication factor is needed', 'two_factor_types': [{'name': 'totp'}]}"
|
accessing private websocket data from tradingview in python
|
I am able to get live ticker data and the prior 500-100 candle chart data with this code but I am unable to get data that isn't delayed for CME_MINI:ESH2021. TradingView puts a 600 second delay I believe on the public stream. I do pay for the data and I can pull it up on the web client but I am unable to get the non-delayed data on python since I am unsure how to log into TradingView via python. If someone knows how I can fix my code to do what I want it to I would greatly appreciate your input or any advice.
from websocket import create_connection
import json
import random
import string
import re
from datetime import datetime
from time import sleep
def filter_raw_message(text):
try:
found = re.search('"p":(.+?"}"])}', text).group(1)
print(found)
return found
except AttributeError:
print("error")
def generateSession():
stringLength=12
letters = string.ascii_lowercase
random_string= ''.join(random.choice(letters) for i in range(stringLength))
return "qs_" +random_string
def generateChartSession():
stringLength=12
letters = string.ascii_lowercase
random_string= ''.join(random.choice(letters) for i in range(stringLength))
return "cs_" +random_string
def prependHeader(st):
return "~m~" + str(len(st)) + "~m~" + st
def constructMessage(func, paramList):
#json_mylist = json.dumps(mylist, separators=(',', ':'))
return json.dumps({
"m":func,
"p":paramList
}, separators=(',', ':'))
def createMessage(func, paramList):
return prependHeader(constructMessage(func, paramList))
def sendRawMessage(ws, message):
ws.send(prependHeader(message))
def sendMessage(ws, func, args):
ws.send(createMessage(func, args))
# Initialize the headers needed for the websocket connection
headers = json.dumps({
'Connection': 'upgrade',
'Host': 'data.tradingview.com',
'Origin': 'https://data.tradingview.com',
'Cache-Control': 'no-cache',
'Upgrade': 'websocket',
'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
'Sec-WebSocket-Key': '1H41q97V8BbMKUq0knV1UA==',
'Sec-WebSocket-Version': '13',
'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.56',
'Pragma': 'no-cache',
'Upgrade': 'websocket'
})
# Then create a connection to the tunnel
ws = create_connection(
'wss://data.tradingview.com/socket.io/websocket',headers=headers)
session= generateSession()
print("session generated {}".format(session))
chart_session= generateChartSession()
print("chart_session generated {}".format(chart_session))
symbol = "CME_MINI:ESH2021"
timeframe = "5"
candles = 100
# Then send a message through the tunnel
sendMessage(ws, "set_auth_token", ["unauthorized_user_token"])
sendMessage(ws, "chart_create_session", [chart_session, ""])
sendMessage(ws, "quote_create_session", [session])
sendMessage(ws,"quote_set_fields", [session,"ch","chp","current_session","description","local_description","language","exchange","fractional","is_tradable","lp","lp_time","minmov","minmove2","original_name","pricescale","pro_name","short_name","type","update_mode","volume","currency_code","rchp","rtc"])
sendMessage(ws, "quote_add_symbols",[session, symbol, {"flags":['force_permission']}])
theString1 = "={\"symbol\":\""
theString2 = "\",\"adjustment\":\"splits\"}"
theString3 = theString1 + symbol + theString2
sendMessage(ws, "resolve_symbol", [chart_session, "symbol_" + timeframe, theString3])
sendMessage(ws, "create_series", [chart_session,"s" + timeframe,"s" + timeframe,"symbol_" + timeframe,timeframe,candles])
sendMessage(ws, "quote_fast_symbols", [session,symbol])
sendMessage(ws, "create_study", [chart_session,"st" + timeframe,"st" + timeframe,"s" + timeframe,"Volume@tv-basicstudies-118",{"length":20,"col_prev_close":"false"}])
sendMessage(ws, "quote_hibernate_all", [session])
# Printing all the result
a=""
while True:
try:
sleep(1)
result = ws.recv()
pattern = re.compile("~m~\d+~m~~h~\d+$")
if pattern.match(result):
ws.recv()
ws.send(result)
print("\n\n\n hhhhhhhhhhhhhhhhhhhhhh "+ str(result) + "\n\n")
print(result)
a=a+result+"\n"
except Exception as e:
print(e)
break
|
[
"This post is quite old, and the OP probably has the answer already, but regardless, I'm posting for people who visit this page in the future.\nThis solution comes from the Github page here: https://github.com/rushic24/tradingview-scraper\nIn fact, what I'm about to post is literally on the front page of that link. I'm just remaking it into a step-by-step guide.\nIn the original code, you can find the following line:\nsendMessage(ws, \"set_auth_token\", [\"unauthorized_user_token\"])\nDo you see the part where it says \"unauthorized_user_token\"? That means you're an anonymous random person to TradingView.\nSo you must create an auth_token to let TradingView know you're logging in as yourself and that you indeed have paid access to real-time data.\n1.\nAdd the following to your code:\ndef get_auth_token():\n sign_in_url = 'https://www.tradingview.com/accounts/signin/'\n username = 'username'\n password = 'password'\n data = {\"username\": username, \"password\": password, \"remember\": \"on\"}\n headers = {\n 'Referer': 'https://www.tradingview.com'\n }\n response = requests.post(url=sign_in_url, data=data, headers=headers)\n auth_token = response.json()['user']['auth_token'] \n return auth_token\n\nReplace 'username' and 'password' with your own.\n2.\nreplace\nsendMessage(ws, \"set_auth_token\", [\"unauthorized_user_token\"])\nWith the following:\nauth_token = get_auth_token()\nsendMessage(ws, \"set_auth_token\", [auth_token])\n\n\n\n\nreplace\nws = create_connection('wss://data.tradingview.com/socket.io/websocket', headers=headers)\nWith the following:\nws = create_connection( 'wss://data.tradingview.com/socket.io/websocket?from=chart/XXyour_chartXX/&date=XXXX_XX_XX-XX_XX',headers=headers)\n\nreplace 'XXyour_chartXX' with one of your saved charts' URLs. (https://www.tradingview.com/chart/***###THIS_PART###***/)\n",
"this is very useful, thanks a ton!\nI guess it only works with the 2FA disabled, otherwise it throws this \"{'error': '2FA_required', 'code': '2FA_required', 'message': 'Second authentication factor is needed', 'two_factor_types': [{'name': 'totp'}]}\"\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"tradingview_api",
"websocket"
] |
stackoverflow_0065731895_python_tradingview_api_websocket.txt
|
Q:
How to remove only the last letter in string, python?
I am making a "Wordle" type of game in Python and wanted to remove the last letters you wrote when you press backspace and it worked in most cases but I have a problem if your word has the letter that are the same for example "start".
I tried using the .replace() function like this:
word = 'start'
new_word = word.replace(word[4], '', 1)
print(new_word)
But the result isn't 'star', but rather 'sart'.
As you see it replaces the first 't' and not the last.
Does anyone know how to replace the last 't' but the solution needs to work on any case, like in 'aaaaa' it just needs to replace the last 'a'?
|
How to remove only the last letter in string, python?
|
I am making a "Wordle" type of game in Python and wanted to remove the last letters you wrote when you press backspace and it worked in most cases but I have a problem if your word has the letter that are the same for example "start".
I tried using the .replace() function like this:
word = 'start'
new_word = word.replace(word[4], '', 1)
print(new_word)
But the result isn't 'star', but rather 'sart'.
As you see it replaces the first 't' and not the last.
Does anyone know how to replace the last 't' but the solution needs to work on any case, like in 'aaaaa' it just needs to replace the last 'a'?
|
[] |
[] |
[
"Extract from the total length of the word the last character, like this for example:\nword = 'start'\nnew_word = word[:len(word)-1]\nprint(new_word)\n",
"word = 'start'\nnew_word = word.replace(word[1], word[4]) #replaces letter 1 with letter 4\nnew_word = new_word[:-1] #removes last letter\nprint(new_word)\n\n"
] |
[
-2,
-2
] |
[
"letter",
"python",
"replace",
"string"
] |
stackoverflow_0074498947_letter_python_replace_string.txt
|
Q:
How to get a dict lookup by adjacent value
I have the following object:
ancestorTitles': [{
u 'contentType': u 'SERIES',
u 'titleId': u 'B00ERMZZRA',
u 'title': u 'Criminal Minds'
}, {
u 'contentType': u 'SEASON',
u 'number': 10,
u 'titleId': u 'B00SSFZWB6',
u 'title': u 'Criminal Minds Staffel 10'
}]
How would I get the titleId of the "SERIES" here("B00ERMZZRA")? My current approach uses a for loop.
A:
>>> [item.get('titleId') for item in t if item.get('contentType') == 'SERIES'][0]
'B00ERMZZRA'
A:
I reverse engineered your answer to make a reusable function
def get_dict_by_value(dict_list, field, value):
"""returns dictionary with specific value in given field"""
for d in dict_list:
if d.get(field) == value:
return d
The function returns the entire dictionary from which you can get the value(s) you want
list = [{
'contentType': 'SERIES',
'titleId': 'B00ERMZZRA',
'title': 'Criminal Minds'
}, {
'contentType': 'SEASON',
'number': 10,
'titleId': 'B00SSFZWB6',
'title': 'Criminal Minds Staffel 10'
}]
single_dict = get_dict_by_value(list, 'contentType', 'SERIES')
print(single_dict)
>>> { 'contentType': 'SERIES', 'titleId': 'B00ERMZZRA', 'title': 'Criminal Minds' }
Get any value you want like this
print single_dict.get('contentType')
>>> SERIES
print single_dict.get('titleId')
>>> B00ERMZZRA
|
How to get a dict lookup by adjacent value
|
I have the following object:
ancestorTitles': [{
u 'contentType': u 'SERIES',
u 'titleId': u 'B00ERMZZRA',
u 'title': u 'Criminal Minds'
}, {
u 'contentType': u 'SEASON',
u 'number': 10,
u 'titleId': u 'B00SSFZWB6',
u 'title': u 'Criminal Minds Staffel 10'
}]
How would I get the titleId of the "SERIES" here("B00ERMZZRA")? My current approach uses a for loop.
|
[
">>> [item.get('titleId') for item in t if item.get('contentType') == 'SERIES'][0]\n'B00ERMZZRA'\n\n",
"I reverse engineered your answer to make a reusable function\ndef get_dict_by_value(dict_list, field, value):\n \"\"\"returns dictionary with specific value in given field\"\"\"\n for d in dict_list:\n if d.get(field) == value:\n return d\n\nThe function returns the entire dictionary from which you can get the value(s) you want\nlist = [{\n 'contentType': 'SERIES',\n 'titleId': 'B00ERMZZRA',\n 'title': 'Criminal Minds'\n}, {\n 'contentType': 'SEASON',\n 'number': 10,\n 'titleId': 'B00SSFZWB6',\n 'title': 'Criminal Minds Staffel 10'\n}]\n\n\nsingle_dict = get_dict_by_value(list, 'contentType', 'SERIES')\n\nprint(single_dict)\n\n>>> { 'contentType': 'SERIES', 'titleId': 'B00ERMZZRA', 'title': 'Criminal Minds' }\n\nGet any value you want like this\nprint single_dict.get('contentType')\n\n>>> SERIES\n\n\nprint single_dict.get('titleId')\n\n>>> B00ERMZZRA\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0032729949_python.txt
|
Q:
Python create multiple dictionaries from values read from a list
I have the following list of values: Numbers = [1,2,3,4].
Is it possible to create a dictionary with the same name as the values contained in the list?
Example: dictionary_1 = {}
dictionary_2 = {}
....
dictionary_Number.. {}
I would like to create these dictionaries automatically, without creating them manually, reading the numbers contained in the list
A:
You may use the keyword exec in python. Here is an example of your solution,
List = [1, 2,3]
for ele in List:
dic = f"Dictionary_{ele}"
exec(dic+" = {}")
print(Dictionary_1, Dictionary_2, Dictionary_3, sep='\n')
you may use it according to you, but the disadvantage for it is that you will need to use exec every time you need to use it or you must know what would be the name outcome of the first use of exec ...
I hope I helped...
A:
Use the inbuild functions and remember that a dictionary needs a tuble (key & value):
Python Dictionaries
Python Dictionary fromkeys() Method
Example-Code:
Numbers = [1,2,3,4]
Numbers_dict = dict.fromkeys(Numbers,"dict_value")
print(Numbers_dict)
This will output:
{'1': 'dict_value', '2': 'dict_value', '3': 'dict_value', '4': 'dict_value'}
If you want to get a single dictonaries for each list-value, you first have to create for each list-value an empty variable.
After this you have to fill this empty vairables within a loop.
|
Python create multiple dictionaries from values read from a list
|
I have the following list of values: Numbers = [1,2,3,4].
Is it possible to create a dictionary with the same name as the values contained in the list?
Example: dictionary_1 = {}
dictionary_2 = {}
....
dictionary_Number.. {}
I would like to create these dictionaries automatically, without creating them manually, reading the numbers contained in the list
|
[
"You may use the keyword exec in python. Here is an example of your solution,\nList = [1, 2,3]\nfor ele in List:\n dic = f\"Dictionary_{ele}\"\n exec(dic+\" = {}\")\nprint(Dictionary_1, Dictionary_2, Dictionary_3, sep='\\n') \n\nyou may use it according to you, but the disadvantage for it is that you will need to use exec every time you need to use it or you must know what would be the name outcome of the first use of exec ...\nI hope I helped...\n",
"Use the inbuild functions and remember that a dictionary needs a tuble (key & value):\n\nPython Dictionaries\nPython Dictionary fromkeys() Method\n\nExample-Code:\nNumbers = [1,2,3,4]\nNumbers_dict = dict.fromkeys(Numbers,\"dict_value\")\nprint(Numbers_dict)\n\nThis will output:\n{'1': 'dict_value', '2': 'dict_value', '3': 'dict_value', '4': 'dict_value'}\n\nIf you want to get a single dictonaries for each list-value, you first have to create for each list-value an empty variable.\nAfter this you have to fill this empty vairables within a loop.\n"
] |
[
1,
0
] |
[] |
[] |
[
"arrays",
"dictionary",
"python"
] |
stackoverflow_0074499073_arrays_dictionary_python.txt
|
Q:
How to sup up rows within a dictionary?
I have a dictionary:
{
"account": "x*", 'amount': 300, 'day': 3, 'month': 'June',
"account": "y*", 'amount': 550, 'day': 9, 'month': 'May',
"account": 'z*', 'amount': -200, 'day': 21, 'month': 'June'
"account" : "g", "amount" : 80" "day" : 10" month" : "May"
}
How do I find the total amount for each month June and May separately?
dictionary= sum(d["amount"] for d in my_dict)
A:
You can filter which elements to sum, by adding an if statement at the end of the one-liner for-loop:
sum(d['amount'] for d in my_dict if d['month'] == month)
Then, we can wrap this line of code inside a small function to compute the results for May and June:
my_dict = [{'account': 'x*', 'amount': 300, 'day': 3, 'month': 'June'},
{'account': 'y*', 'amount': 550, 'day': 9, 'month': 'May' },
{'account': 'z*', 'amount': -200, 'day': 21, 'month': 'June'},
{'account': 'g' , 'amount': 80, 'day': 10, 'month': 'May' }]
get_sum = lambda my_dict, month: sum(d['amount'] for d in my_dict if d['month'] == month)
sum_June = get_sum(my_dict, 'June')
sum_May = get_sum(my_dict, 'May' )
print('sum_June:', sum_June)
# sum_June: 100
print('sum_May :', sum_May)
# sum_May : 630
PS. Initially, the dictionary my_dict was over-writting data, because everything was stored in the same object. In the code above, my_dict is split into a list with multiple rows to avoid this issue. Please consider this methodology to store data in your project - it is very common.
|
How to sup up rows within a dictionary?
|
I have a dictionary:
{
"account": "x*", 'amount': 300, 'day': 3, 'month': 'June',
"account": "y*", 'amount': 550, 'day': 9, 'month': 'May',
"account": 'z*', 'amount': -200, 'day': 21, 'month': 'June'
"account" : "g", "amount" : 80" "day" : 10" month" : "May"
}
How do I find the total amount for each month June and May separately?
dictionary= sum(d["amount"] for d in my_dict)
|
[
"You can filter which elements to sum, by adding an if statement at the end of the one-liner for-loop:\nsum(d['amount'] for d in my_dict if d['month'] == month)\n\nThen, we can wrap this line of code inside a small function to compute the results for May and June:\nmy_dict = [{'account': 'x*', 'amount': 300, 'day': 3, 'month': 'June'},\n {'account': 'y*', 'amount': 550, 'day': 9, 'month': 'May' },\n {'account': 'z*', 'amount': -200, 'day': 21, 'month': 'June'},\n {'account': 'g' , 'amount': 80, 'day': 10, 'month': 'May' }]\n\n\nget_sum = lambda my_dict, month: sum(d['amount'] for d in my_dict if d['month'] == month)\nsum_June = get_sum(my_dict, 'June')\nsum_May = get_sum(my_dict, 'May' )\n\nprint('sum_June:', sum_June)\n# sum_June: 100\n\nprint('sum_May :', sum_May)\n# sum_May : 630\n\n\nPS. Initially, the dictionary my_dict was over-writting data, because everything was stored in the same object. In the code above, my_dict is split into a list with multiple rows to avoid this issue. Please consider this methodology to store data in your project - it is very common.\n"
] |
[
1
] |
[] |
[] |
[
"dictionary",
"python",
"sum"
] |
stackoverflow_0074499128_dictionary_python_sum.txt
|
Q:
convert elements in list of lists by another list of lists
Hi there I have 2 list of lists as the example below:
list1=[['a','b','c'],
['d','e','f'],
['g','h','d'],
['n','m','j']]
list2 is list of lists of indice of list1
list2=[[0,2],
[1,3]]
#output :
list2=[[['a','b','c'],['g','h','d']],
[['d','e','f'],['n','m','j']]]
i want to convert elemnts of list2 by elements of list1 by thy indcies
thank you in advance
A:
This simple code works:
for lis in list2:
for i in range(len(lis)):
lis[i] = list1[lis[i]]
Another more convoluted version, that works for more depths of list embedding:
def lreplace(l2, l1):
for obj in l2:
if type(obj)==list:
lreplace(obj, l1)
else:
l2[l2.index(obj)]=l1[obj]
list2 = [[[1],[0,0]],[3,2,3]]
lreplace(list2,list1)
list2
#Out[222]:
#[[[['d', 'e', 'f']], [['a', 'b', 'c'], ['a', 'b', 'c']]],
# [['n', 'm', 'j'], ['g', 'h', 'd'], ['n', 'm', 'j']]]
|
convert elements in list of lists by another list of lists
|
Hi there I have 2 list of lists as the example below:
list1=[['a','b','c'],
['d','e','f'],
['g','h','d'],
['n','m','j']]
list2 is list of lists of indice of list1
list2=[[0,2],
[1,3]]
#output :
list2=[[['a','b','c'],['g','h','d']],
[['d','e','f'],['n','m','j']]]
i want to convert elemnts of list2 by elements of list1 by thy indcies
thank you in advance
|
[
"This simple code works:\nfor lis in list2:\n for i in range(len(lis)):\n lis[i] = list1[lis[i]]\n\nAnother more convoluted version, that works for more depths of list embedding:\ndef lreplace(l2, l1):\n for obj in l2:\n if type(obj)==list:\n lreplace(obj, l1)\n else:\n l2[l2.index(obj)]=l1[obj]\n\nlist2 = [[[1],[0,0]],[3,2,3]]\nlreplace(list2,list1)\nlist2\n#Out[222]: \n#[[[['d', 'e', 'f']], [['a', 'b', 'c'], ['a', 'b', 'c']]],\n# [['n', 'm', 'j'], ['g', 'h', 'd'], ['n', 'm', 'j']]]\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074499194_python.txt
|
Q:
APK app is crashing when I use mysql Localhost
I just finish with designing the app interface and connect it to MySql db for send and retrieve data,
I was excited to convert it to an APK file and test it on my Android, application works fine but whenever I try to communicate with my database, app is crashing, Even I am using Try ,Except statement
at this point I guess that I am still missing something to connect in between my app on android and my localhost database on PC.
Here is my Connection Code :
class FifthScreen(Screen):
users = os.environ.get('USER_NAME')
pass_word = os.environ.get('WORDPASS')
try:
database = mysql.connector.connect(host="localhost", user=users, password=pass_word, database="logintest", port= "3306")
cursor = database.cursor()
except Error as e:
print(e)
admin_email = "rasheed@hotmail.com"
admin_password = "King"
loggedin = False
def receive_data(self, email, password):
try:
self.cursor.execute("select email,password from logs")
email_list = []
for i in self.cursor.fetchall():
email_list.append(i[0])
if email.text in email_list and email.text != "":
self.cursor.execute(f"select password,user_name from logs where email='{email.text}'")
for j in self.cursor:
if email.text == self.admin_email and password.text == self.admin_password:
print("Hello Admin")
self.manager.current = 'Data_Table'
elif password.text == j[0]:
print("you successfully logged in")
self.manager.current = 'Doctors_Patients_Details'
self.loggedin = True
self.manager.get_screen('photo_page').ids.user_name.text = j[1]
else:
print("incorrect password ")
else:
print("incorrect email")
except Error as e:
print(e)
finally:
if self.database.is_connected():
self.database.close()
self.cursor.close()
print("closed4")
Here is Requirments :
requirements = python3,kivy==2.1.0,kivymd==0.104.2,pillow, requests,android,docutils,mysql_connector,mysql-connector-python,fpdf
android.permissions = INTERNET,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE
So I need some guide about what is the method or tool to connect in between my app on android and database on pc.
I am using Kivy, Python3 and mysql db, I am using local host for now and i didn't miss to give android permission in buildozer specs file.
Edit part:
I added IP Address instead of localhost, port 3306 and blocked firewall
I faced two issues:
1- again crashing after communicate with database
class FifthScreen(Screen):
users = os.environ.get('USER_NAME')
pass_word = os.environ.get('WORDPASS')
try:
database = mysql.connector.connect(host="192.168.43.64", user=users, password=pass_word, database="logintest", port= "3306")
cursor = database.cursor()
Traceback (most recent call last):
10-25 21:19:50.841 3641 4045 I python : File "/content/.buildozer/android/app/main.py", line 328, in receive_data
10-25 21:19:50.843 3641 4045 I python : AttributeError: 'FifthScreen' object has no attribute 'cursor'
AttributeError: 'FifthScreen' object has no attribute 'database'
10-25 21:19:50.848 3641 4045 I python : Python for android ended.
2- Black Screen after splash Screen is tacking too long around 3 to 4 minutes
win=Window{3e4abc u0 Splash Screen org.test.test3 EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true
A:
I Solved this issue, and It was Stupid mistake, but I want to share the problem because anyone new with this like me could fall to same mistake,
I created remote user in MySQL and give it password contain special character (&), for some reason you can't access to sever with special character.
That was the whole issue :)
|
APK app is crashing when I use mysql Localhost
|
I just finish with designing the app interface and connect it to MySql db for send and retrieve data,
I was excited to convert it to an APK file and test it on my Android, application works fine but whenever I try to communicate with my database, app is crashing, Even I am using Try ,Except statement
at this point I guess that I am still missing something to connect in between my app on android and my localhost database on PC.
Here is my Connection Code :
class FifthScreen(Screen):
users = os.environ.get('USER_NAME')
pass_word = os.environ.get('WORDPASS')
try:
database = mysql.connector.connect(host="localhost", user=users, password=pass_word, database="logintest", port= "3306")
cursor = database.cursor()
except Error as e:
print(e)
admin_email = "rasheed@hotmail.com"
admin_password = "King"
loggedin = False
def receive_data(self, email, password):
try:
self.cursor.execute("select email,password from logs")
email_list = []
for i in self.cursor.fetchall():
email_list.append(i[0])
if email.text in email_list and email.text != "":
self.cursor.execute(f"select password,user_name from logs where email='{email.text}'")
for j in self.cursor:
if email.text == self.admin_email and password.text == self.admin_password:
print("Hello Admin")
self.manager.current = 'Data_Table'
elif password.text == j[0]:
print("you successfully logged in")
self.manager.current = 'Doctors_Patients_Details'
self.loggedin = True
self.manager.get_screen('photo_page').ids.user_name.text = j[1]
else:
print("incorrect password ")
else:
print("incorrect email")
except Error as e:
print(e)
finally:
if self.database.is_connected():
self.database.close()
self.cursor.close()
print("closed4")
Here is Requirments :
requirements = python3,kivy==2.1.0,kivymd==0.104.2,pillow, requests,android,docutils,mysql_connector,mysql-connector-python,fpdf
android.permissions = INTERNET,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE
So I need some guide about what is the method or tool to connect in between my app on android and database on pc.
I am using Kivy, Python3 and mysql db, I am using local host for now and i didn't miss to give android permission in buildozer specs file.
Edit part:
I added IP Address instead of localhost, port 3306 and blocked firewall
I faced two issues:
1- again crashing after communicate with database
class FifthScreen(Screen):
users = os.environ.get('USER_NAME')
pass_word = os.environ.get('WORDPASS')
try:
database = mysql.connector.connect(host="192.168.43.64", user=users, password=pass_word, database="logintest", port= "3306")
cursor = database.cursor()
Traceback (most recent call last):
10-25 21:19:50.841 3641 4045 I python : File "/content/.buildozer/android/app/main.py", line 328, in receive_data
10-25 21:19:50.843 3641 4045 I python : AttributeError: 'FifthScreen' object has no attribute 'cursor'
AttributeError: 'FifthScreen' object has no attribute 'database'
10-25 21:19:50.848 3641 4045 I python : Python for android ended.
2- Black Screen after splash Screen is tacking too long around 3 to 4 minutes
win=Window{3e4abc u0 Splash Screen org.test.test3 EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true
|
[
"I Solved this issue, and It was Stupid mistake, but I want to share the problem because anyone new with this like me could fall to same mistake,\nI created remote user in MySQL and give it password contain special character (&), for some reason you can't access to sever with special character.\nThat was the whole issue :)\n"
] |
[
0
] |
[] |
[] |
[
"kivy",
"mysql",
"python"
] |
stackoverflow_0074148767_kivy_mysql_python.txt
|
Q:
Send email at specific time with millisecond precision
I would like to send email at given time preferably using gmail. The rationale behind this is that the school I am applying is ordering candidates based on when they receive the participation email after given time.
I could use gmail schedule send feature but there is X delay between sending email from gmail server to school email and it potentially should be achieveable to cut it down slightly so I thought about python script to do it. I think I can get around sending it at a given time but struggle to actually send the message.
There are threads in stackoverflow suggesting python solution e.g.: How do I schedule an email to send at a certain time using cron and smtp, in python? but unfortunately it looks like gmail disabled the option to send mails from non-authorized apps.
Other threads suggest that enabling less secure apps is needed. Unfortunately, this setting has been closed by Google. What could be the way around it?
My sample code:
`
def send_mail():
try:
server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server_ssl.ehlo() # optional
print('Server initialized')
sent_from = gmail_user
to = ['xxxxxxxx@gmail.com']
subject = 'my subject'
body = 'my body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
server_ssl.sendmail(sent_from, to, email_text)
server_ssl.close()
except Exception as inst:
print('Something went wrong')
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst)
`
is returning an error:
<class 'smtplib.SMTPSenderRefused'> (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError
A:
You need to supply the login to the account, as well as an apps password. You cant just send an email without being authenticated to the mail server.
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
print( 'waiting to login...')
server.login(sender_email, password)
print( 'waiting to send...')
server.sendmail(sender_email, receiver_email, text)
|
Send email at specific time with millisecond precision
|
I would like to send email at given time preferably using gmail. The rationale behind this is that the school I am applying is ordering candidates based on when they receive the participation email after given time.
I could use gmail schedule send feature but there is X delay between sending email from gmail server to school email and it potentially should be achieveable to cut it down slightly so I thought about python script to do it. I think I can get around sending it at a given time but struggle to actually send the message.
There are threads in stackoverflow suggesting python solution e.g.: How do I schedule an email to send at a certain time using cron and smtp, in python? but unfortunately it looks like gmail disabled the option to send mails from non-authorized apps.
Other threads suggest that enabling less secure apps is needed. Unfortunately, this setting has been closed by Google. What could be the way around it?
My sample code:
`
def send_mail():
try:
server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server_ssl.ehlo() # optional
print('Server initialized')
sent_from = gmail_user
to = ['xxxxxxxx@gmail.com']
subject = 'my subject'
body = 'my body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
server_ssl.sendmail(sent_from, to, email_text)
server_ssl.close()
except Exception as inst:
print('Something went wrong')
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst)
`
is returning an error:
<class 'smtplib.SMTPSenderRefused'> (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError
|
[
"You need to supply the login to the account, as well as an apps password. You cant just send an email without being authenticated to the mail server.\nwith smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:\n print( 'waiting to login...')\n server.login(sender_email, password)\n print( 'waiting to send...')\n server.sendmail(sender_email, receiver_email, text)\n\n"
] |
[
0
] |
[] |
[] |
[
"gmail",
"python",
"smtp"
] |
stackoverflow_0074496302_gmail_python_smtp.txt
|
Q:
How to Vectorize for loop/pandad iterrows with condition outside of loop python
I am trying to make a set of code I have faster using vectorization in Pandas (or NumPy). I basically need to have a "trailing" condition as I loop through each row of a dataframe so that I can create a condition based on that.
example code:
lst1 = pd.DataFrame([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
lst2 = pd.DataFrame([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
output_lst = pd.DataFrame(index=lst1.index, columns=lst1.columns)
previous_column_value_even = False
for row, values in lst1.iterrows():
for col_index in values.index:
value1 = lst1.loc[row, col_index]
value2 = lst2.loc[row, col_index]
if previous_column_value_even:
if value1 > value2:
output_lst.loc[row, col_index] = True
print(value1)
if value1 % 2 == 0:
previous_column_value_even = True
else:
previous_column_value_even = False
previous_column_value_even = False
output
9
I'd like to have a vectorized form of this condition.
The main thing I'm looking for is having an overall condition for each row that can be used in something like numpy.where(). I'd like to use numpy.where but pandas.dataframe.apply seems to be another option - I just can't figure out how to get the previous column's condition to be set as I "loop" through each column of a row in a vectorized form.
This is my biggest constraint: having the condition dynamically go through the iteration of each column so that my second condition can be called. Preferably without a loop in the vectorized condition as that is my main problem
A:
Although I mentioned in my comment that programs like these aren't usually vectorizable, your code doesn't actually have the read-after-write dependency. In pure NumPy, we can simplify your code to something of the form:
import numpy as np
def process_arrays(A, B):
C = np.zeros_like(A, dtype=np.bool)
for i in range(A.shape[0]):
for j in range(1, A.shape[1]): # no need to check column 0 for previous even
if A[i, j - 1] % 2 == 0:
if A[i, j] > B[i, j]:
C[i, j] = True
return C
As the values of previous_column_value_even can all be computed independently in advance, so it should be possible to vectorize the above into:
C = np.where(np.logical_and(np.pad((A % 2) == 0, ((0, 0), (1, 0)))[:, :-1], A > B), True, False)
|
How to Vectorize for loop/pandad iterrows with condition outside of loop python
|
I am trying to make a set of code I have faster using vectorization in Pandas (or NumPy). I basically need to have a "trailing" condition as I loop through each row of a dataframe so that I can create a condition based on that.
example code:
lst1 = pd.DataFrame([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
lst2 = pd.DataFrame([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
output_lst = pd.DataFrame(index=lst1.index, columns=lst1.columns)
previous_column_value_even = False
for row, values in lst1.iterrows():
for col_index in values.index:
value1 = lst1.loc[row, col_index]
value2 = lst2.loc[row, col_index]
if previous_column_value_even:
if value1 > value2:
output_lst.loc[row, col_index] = True
print(value1)
if value1 % 2 == 0:
previous_column_value_even = True
else:
previous_column_value_even = False
previous_column_value_even = False
output
9
I'd like to have a vectorized form of this condition.
The main thing I'm looking for is having an overall condition for each row that can be used in something like numpy.where(). I'd like to use numpy.where but pandas.dataframe.apply seems to be another option - I just can't figure out how to get the previous column's condition to be set as I "loop" through each column of a row in a vectorized form.
This is my biggest constraint: having the condition dynamically go through the iteration of each column so that my second condition can be called. Preferably without a loop in the vectorized condition as that is my main problem
|
[
"Although I mentioned in my comment that programs like these aren't usually vectorizable, your code doesn't actually have the read-after-write dependency. In pure NumPy, we can simplify your code to something of the form:\nimport numpy as np\n\ndef process_arrays(A, B):\n C = np.zeros_like(A, dtype=np.bool)\n for i in range(A.shape[0]):\n for j in range(1, A.shape[1]): # no need to check column 0 for previous even\n if A[i, j - 1] % 2 == 0:\n if A[i, j] > B[i, j]:\n C[i, j] = True\n return C\n\nAs the values of previous_column_value_even can all be computed independently in advance, so it should be possible to vectorize the above into:\nC = np.where(np.logical_and(np.pad((A % 2) == 0, ((0, 0), (1, 0)))[:, :-1], A > B), True, False)\n\n"
] |
[
0
] |
[] |
[] |
[
"loops",
"numpy",
"pandas",
"python",
"vectorization"
] |
stackoverflow_0074497979_loops_numpy_pandas_python_vectorization.txt
|
Q:
How to show exe file in right click context menu in Python for desktop software / app?
I wrote a python script and then convert it into executable file.
In below image you can see my exe file.
my exe file.
Now, I want to show my exe file in context menu after right click only on the folder, I also want to take folder name as an argument, than user click the exe file which I want to show in a right click context menu.
In this image you can easily understand, what i want.
A:
This is what I used for a simple app I wrote, it has stupid logic to check if it's run with or without arguments, and tries to add an entry to the context menu when it's run without arguments (eg. directly, not from context menu)
Just for simple explanation:
Running the EXE directly will create a .reg file and run said registry file. This will add the menu entry to the context menu. It uses the path of the EXE to tell windows where the EXE can be found.
After this, when right-clicking a file/directory/whatever, it will show the menu entry and if you click on that, it won't meet the contitions for the if statement, so it will continue with the rest of the script.
I'm not sure how this handles different Windows versions, as it was made specifically for Windows 11 and I added zero error checking.
import sys
import os
context_menu_text_string = "This is the text shown in the context menu"
if len(sys.argv) != 2:
repl = sys.argv[0].replace("\\", "\\\\")
with open("registryfile.reg", "w") as outfile:
outfile.write(
rf"""Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\Background\shell\{context_menu_text_string}\command]
@="{repl} \"%1\""
"""
)
os.startfile("registryfile.reg")
input("Press enter to continue, after finishing the registry import...")
os.remove("registryfile.reg")
sys.exit(0)
full_file_path = sys.argv[1]
# your logic here, full_file_path contains the path to
# the file/directory which was right-clicked
|
How to show exe file in right click context menu in Python for desktop software / app?
|
I wrote a python script and then convert it into executable file.
In below image you can see my exe file.
my exe file.
Now, I want to show my exe file in context menu after right click only on the folder, I also want to take folder name as an argument, than user click the exe file which I want to show in a right click context menu.
In this image you can easily understand, what i want.
|
[
"This is what I used for a simple app I wrote, it has stupid logic to check if it's run with or without arguments, and tries to add an entry to the context menu when it's run without arguments (eg. directly, not from context menu)\nJust for simple explanation:\n\nRunning the EXE directly will create a .reg file and run said registry file. This will add the menu entry to the context menu. It uses the path of the EXE to tell windows where the EXE can be found.\nAfter this, when right-clicking a file/directory/whatever, it will show the menu entry and if you click on that, it won't meet the contitions for the if statement, so it will continue with the rest of the script.\n\nI'm not sure how this handles different Windows versions, as it was made specifically for Windows 11 and I added zero error checking.\nimport sys\nimport os\n\n\ncontext_menu_text_string = \"This is the text shown in the context menu\"\n\nif len(sys.argv) != 2:\n repl = sys.argv[0].replace(\"\\\\\", \"\\\\\\\\\")\n with open(\"registryfile.reg\", \"w\") as outfile:\n outfile.write(\n rf\"\"\"Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Directory\\Background\\shell\\{context_menu_text_string}\\command]\n@=\"{repl} \\\"%1\\\"\"\n\"\"\"\n )\n os.startfile(\"registryfile.reg\")\n input(\"Press enter to continue, after finishing the registry import...\")\n os.remove(\"registryfile.reg\")\n sys.exit(0)\n\n\nfull_file_path = sys.argv[1]\n\n# your logic here, full_file_path contains the path to \n# the file/directory which was right-clicked\n\n"
] |
[
0
] |
[] |
[] |
[
"desktop",
"desktop_application",
"python",
"windows"
] |
stackoverflow_0074498564_desktop_desktop_application_python_windows.txt
|
Q:
Sweep a table in Python in a particular way
I have a table such as:
Groups SP1 SP2 SP3 SP4_1 SP4_2 SP5_1 SP5_2
G1 3 4 NA 2 4 2 1
G2 NA 1 NA 3 NA NA NA
G3 1 2 NA NA NA 8 NA
G4 4 6 NA NA NA NA NA
G5 8 9 NA NA NA NA 2
And I would like to sweep that table into:
G1 G2 G3 G4 G5
SP1 SP1-3 NA SP1-1 SP1-4 SP1-8
SP2 SP2-4 SP2-1 SP2-2 SP2-6 SP2-9
SP3 NA NA NA NA NA
SP4 SP4_1-2;SP4_2-4 SP4_1-3 NA NA NA
SP5 SP5_1-2;SP5_2-1 NA SP5_1-8 NA SP5_2-2
Let me explain:
Let's take the G1 to explain,
The Idea is first to create a new column G1 and add all SPn present as rows:
G1
SP1
SP2
SP3
SP4
SP5
Then, in G1, I have one value for SP1 which is 3, then I add a row SP1-3
G1
SP1 SP1-3
SP2
SP3
SP4
SP5
I have one value for SP2 which is 4, then I add a row SP1-4
G1
SP1 SP1-3
SP2 SP1-4
SP3
SP4
SP5
I have no value for SP3
G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4
SP5
I have two values for SP4 which are 2 in SP4_1 and 4 in SP4_2, then I merge them by a semicolon ";" within the cell and add a row SP4_1-2;SP4_2-4
G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4 SP4_1-2;SP4_2-4
SP5
And finally I have two values for SP5 which are 2 in SP5_1 and 1 in SP5_2, then I merge them by a semicolon ";" within the cell and add a row SP5_1-2;SP5_2-1
G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4 SP4_1-2;SP4_2-4
SP5 SP5_1-2;SP5_2-1
And so on for the other groups.
Does someone have an idea using python please?
A:
so this is my attempt, doesn't look nice but seems working:
t = df.melt('Groups')
t['val'] = t['variable'].str.cat(t['value'].dropna().astype(str),sep='-')
t['col'] = t['variable'].str[:3]
def f(x):
return x.dropna().str.cat(sep=';') or pd.NA
res = t.pivot_table('val','col','Groups',f)
print(res)
'''
Groups G1 G2 G3 G4 G5
col
SP1 SP1-3.0 NaN SP1-1.0 SP1-4.0 SP1-8.0
SP2 SP2-4.0 SP2-1.0 SP2-2.0 SP2-6.0 SP2-9.0
SP4 SP4_1-2.0;SP4_2-4.0 SP4_1-3.0 NaN NaN NaN
SP5 SP5_1-2.0;SP5_2-1.0 NaN SP5_1-8.0 NaN SP5_2-2.0
|
Sweep a table in Python in a particular way
|
I have a table such as:
Groups SP1 SP2 SP3 SP4_1 SP4_2 SP5_1 SP5_2
G1 3 4 NA 2 4 2 1
G2 NA 1 NA 3 NA NA NA
G3 1 2 NA NA NA 8 NA
G4 4 6 NA NA NA NA NA
G5 8 9 NA NA NA NA 2
And I would like to sweep that table into:
G1 G2 G3 G4 G5
SP1 SP1-3 NA SP1-1 SP1-4 SP1-8
SP2 SP2-4 SP2-1 SP2-2 SP2-6 SP2-9
SP3 NA NA NA NA NA
SP4 SP4_1-2;SP4_2-4 SP4_1-3 NA NA NA
SP5 SP5_1-2;SP5_2-1 NA SP5_1-8 NA SP5_2-2
Let me explain:
Let's take the G1 to explain,
The Idea is first to create a new column G1 and add all SPn present as rows:
G1
SP1
SP2
SP3
SP4
SP5
Then, in G1, I have one value for SP1 which is 3, then I add a row SP1-3
G1
SP1 SP1-3
SP2
SP3
SP4
SP5
I have one value for SP2 which is 4, then I add a row SP1-4
G1
SP1 SP1-3
SP2 SP1-4
SP3
SP4
SP5
I have no value for SP3
G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4
SP5
I have two values for SP4 which are 2 in SP4_1 and 4 in SP4_2, then I merge them by a semicolon ";" within the cell and add a row SP4_1-2;SP4_2-4
G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4 SP4_1-2;SP4_2-4
SP5
And finally I have two values for SP5 which are 2 in SP5_1 and 1 in SP5_2, then I merge them by a semicolon ";" within the cell and add a row SP5_1-2;SP5_2-1
G1
SP1 SP1-3
SP2 SP1-4
SP3 NA
SP4 SP4_1-2;SP4_2-4
SP5 SP5_1-2;SP5_2-1
And so on for the other groups.
Does someone have an idea using python please?
|
[
"so this is my attempt, doesn't look nice but seems working:\nt = df.melt('Groups')\nt['val'] = t['variable'].str.cat(t['value'].dropna().astype(str),sep='-')\nt['col'] = t['variable'].str[:3]\n\ndef f(x):\n return x.dropna().str.cat(sep=';') or pd.NA\n\nres = t.pivot_table('val','col','Groups',f)\n\nprint(res)\n'''\nGroups G1 G2 G3 G4 G5\ncol \nSP1 SP1-3.0 NaN SP1-1.0 SP1-4.0 SP1-8.0\nSP2 SP2-4.0 SP2-1.0 SP2-2.0 SP2-6.0 SP2-9.0\nSP4 SP4_1-2.0;SP4_2-4.0 SP4_1-3.0 NaN NaN NaN\nSP5 SP5_1-2.0;SP5_2-1.0 NaN SP5_1-8.0 NaN SP5_2-2.0\n\n"
] |
[
1
] |
[] |
[] |
[
"numpy",
"pandas",
"python",
"python_3.x"
] |
stackoverflow_0074498398_numpy_pandas_python_python_3.x.txt
|
Q:
How to filter for rows with close values across columns
I have columns of probabilities in a pandas dataframe as an output from multiclass machine learning.
I am looking to filter rows for which the model had very close probabilities between the classes for that row, and ideally only care about similar values that are similar to the highest value in that row, but I'm not sure where to start.
For example my data looks like this:
ID class1 class2 class3 class4 class5
row1 0.97 0.2 0.4 0.3 0.2
row2 0.97 0.96 0.4 0.3 0.2
row3 0.7 0.5 0.3 0.4 0.5
row4 0.97 0.98 0.99 0.3 0.2
row5 0.1 0.2 0.3 0.78 0.8
row6 0.1 0.11 0.3 0.9 0.2
I'd like to filter for rows where at least 2 (or more) probability class columns have a probability that is close to at least one other probability column in that row (e.g., maybe within 0.05). So an example output would filter to:
ID class1 class2 class3 class4 class5
row2 0.97 0.96 0.4 0.3 0.2
row4 0.97 0.98 0.99 0.3 0.2
row5 0.1 0.2 0.3 0.78 0.8
I don't mind if a filter includes row6 as it also meets my <0.05 different main requirement, but ideally because the 0.05 difference isn't with the largest probability I'd prefer to ignore this too.
What can I do to develop a filter like this?
Example data:
Edit: I have increased the size of my example data, as I do not want pairs specifically but any and all rows that in inside their row their column values for 2 or more probabilities have close values
d = {'ID': ['row1', 'row2', 'row3', 'row4', 'row5', 'row6'],
'class1': [0.97, 0.97, 0.7, 0.97, 0.1, 0.1],
'class2': [0.2, 0.96, 0.5, 0.98, 0.2, 0.11],
'class3': [0.4, 0.4, 0.3, 0.2, 0.3, 0.3],
'class4': [0.3, 0.3, 0.4, 0.3, 0.78, 0.9],
'class5': [0.2, 0.2, 0.5, 0.2, 0.8, 0.2]}
df = pd.DataFrame(data=d)
A:
Here is an example using numpy and itertools.combinations to get the pairs of similar rows with at least N matches with 0.05:
from itertools import combinations
import numpy as np
df2 = df.set_index('ID')
N = 2
out = [(a, b) for a,b in combinations(df2.index, r=2)
if np.isclose(df2.loc[a], df2.loc[b], atol=0.05).sum()>=N]
Output:
[('row1', 'row2'), ('row1', 'row4'), ('row2', 'row4')]
follow-up
My real data is 10,000 rows and I want to filter out all rows that
have more than one column of probabilities that are close to each
other. Is there a way to do this without specifying pairs
from itertools import combinations
N = 2
df2 = df.set_index('ID')
keep = set()
seen = set()
for a,b in combinations(df2.index, r=2):
if {a,b}.issubset(seen):
continue
if np.isclose(df2.loc[a], df2.loc[b], atol=0.05).sum()>=N:
keep.update({a, b})
seen.update({a, b})
print(keep)
# {'row1', 'row2', 'row4'}
A:
You can do that with:
Transpose the dataframe to get each sample as column and classes probabilities as rows.
We only need to check the minimal requirement which is if the difference between the 2 largest values is less than or equal 0.05.
df = pd.DataFrame(data=d).set_index("ID").T
result = [col for col in df.columns if np.isclose(*df[col].nlargest(2), atol=0.05)]
Output:
['row2', 'row4', 'row5']'
Dataframe after the transpose:
ID row1 row2 row3 row4 row5 row6
class1 0.97 0.97 0.7 0.97 0.10 0.10
class2 0.20 0.96 0.5 0.98 0.20 0.11
class3 0.40 0.40 0.3 0.20 0.30 0.30
class4 0.30 0.30 0.4 0.30 0.75 0.90
class5 0.20 0.20 0.5 0.20 0.80 0.20
|
How to filter for rows with close values across columns
|
I have columns of probabilities in a pandas dataframe as an output from multiclass machine learning.
I am looking to filter rows for which the model had very close probabilities between the classes for that row, and ideally only care about similar values that are similar to the highest value in that row, but I'm not sure where to start.
For example my data looks like this:
ID class1 class2 class3 class4 class5
row1 0.97 0.2 0.4 0.3 0.2
row2 0.97 0.96 0.4 0.3 0.2
row3 0.7 0.5 0.3 0.4 0.5
row4 0.97 0.98 0.99 0.3 0.2
row5 0.1 0.2 0.3 0.78 0.8
row6 0.1 0.11 0.3 0.9 0.2
I'd like to filter for rows where at least 2 (or more) probability class columns have a probability that is close to at least one other probability column in that row (e.g., maybe within 0.05). So an example output would filter to:
ID class1 class2 class3 class4 class5
row2 0.97 0.96 0.4 0.3 0.2
row4 0.97 0.98 0.99 0.3 0.2
row5 0.1 0.2 0.3 0.78 0.8
I don't mind if a filter includes row6 as it also meets my <0.05 different main requirement, but ideally because the 0.05 difference isn't with the largest probability I'd prefer to ignore this too.
What can I do to develop a filter like this?
Example data:
Edit: I have increased the size of my example data, as I do not want pairs specifically but any and all rows that in inside their row their column values for 2 or more probabilities have close values
d = {'ID': ['row1', 'row2', 'row3', 'row4', 'row5', 'row6'],
'class1': [0.97, 0.97, 0.7, 0.97, 0.1, 0.1],
'class2': [0.2, 0.96, 0.5, 0.98, 0.2, 0.11],
'class3': [0.4, 0.4, 0.3, 0.2, 0.3, 0.3],
'class4': [0.3, 0.3, 0.4, 0.3, 0.78, 0.9],
'class5': [0.2, 0.2, 0.5, 0.2, 0.8, 0.2]}
df = pd.DataFrame(data=d)
|
[
"Here is an example using numpy and itertools.combinations to get the pairs of similar rows with at least N matches with 0.05:\nfrom itertools import combinations\nimport numpy as np\n\ndf2 = df.set_index('ID')\n\nN = 2\n\nout = [(a, b) for a,b in combinations(df2.index, r=2)\n if np.isclose(df2.loc[a], df2.loc[b], atol=0.05).sum()>=N]\n\nOutput:\n[('row1', 'row2'), ('row1', 'row4'), ('row2', 'row4')]\n\nfollow-up\n\nMy real data is 10,000 rows and I want to filter out all rows that\nhave more than one column of probabilities that are close to each\nother. Is there a way to do this without specifying pairs\n\nfrom itertools import combinations\n\nN = 2\n\ndf2 = df.set_index('ID')\n\nkeep = set()\nseen = set()\n\nfor a,b in combinations(df2.index, r=2):\n if {a,b}.issubset(seen):\n continue\n if np.isclose(df2.loc[a], df2.loc[b], atol=0.05).sum()>=N:\n keep.update({a, b})\n seen.update({a, b})\n \nprint(keep)\n# {'row1', 'row2', 'row4'}\n\n",
"You can do that with:\n\nTranspose the dataframe to get each sample as column and classes probabilities as rows.\n\nWe only need to check the minimal requirement which is if the difference between the 2 largest values is less than or equal 0.05.\ndf = pd.DataFrame(data=d).set_index(\"ID\").T\n\nresult = [col for col in df.columns if np.isclose(*df[col].nlargest(2), atol=0.05)]\n\n\n\nOutput:\n['row2', 'row4', 'row5']'\n\nDataframe after the transpose:\n ID row1 row2 row3 row4 row5 row6\nclass1 0.97 0.97 0.7 0.97 0.10 0.10\nclass2 0.20 0.96 0.5 0.98 0.20 0.11\nclass3 0.40 0.40 0.3 0.20 0.30 0.30\nclass4 0.30 0.30 0.4 0.30 0.75 0.90\nclass5 0.20 0.20 0.5 0.20 0.80 0.20\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"machine_learning",
"pandas",
"python"
] |
stackoverflow_0074452015_machine_learning_pandas_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.