content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
sequence | answers_scores
sequence | non_answers
sequence | non_answers_scores
sequence | tags
sequence | name
stringlengths 35
137
|
---|---|---|---|---|---|---|---|---|
Q:
small project that is a phone book first for loop its dosent work and in need
phone_book = {1111111111:"amal",
2222222222:"Mohammed",
3333333333:"Khadijah",
4444444444:"Abdullah",
5555555555:"Rawan",
6666666666:"Faisal",
7777777777:"Layla"}
xx = int(input('Enter the number : '))
for key, value in phone_book.items():
if xx == value:
print('this phone number', v, 'belong to ', k)
phone_belong_to = k
print('thank you')
quit()
print("think you !: ")
print(type(phone_book))
frist
In the event that a number in the directory is sent, the name of the owner of the entered number will be printed
second
If the phone number is less than or more than 10 digits, or some other value (contains letters, symbols, and logical values for example
A:
I dind't understand the second part but try it like this:
code:
phone_book = {1111111111:"amal",
2222222222:"Mohammed",
3333333333:"Khadijah",
4444444444:"Abdullah",
5555555555:"Rawan",
6666666666:"Faisal",
7777777777:"Layla"}
xx = int(input('Enter the number : '))
for key, value in phone_book.items():
if xx == key:
print("this phone number {} belong to {}".format(key, value))
phone_belong_to = value
print('thank you')
quit()
print('not found!')
Input:
Enter the number : 1111111111
Output:
this phone number 1111111111 belong to amal
thank you
| small project that is a phone book first for loop its dosent work and in need | phone_book = {1111111111:"amal",
2222222222:"Mohammed",
3333333333:"Khadijah",
4444444444:"Abdullah",
5555555555:"Rawan",
6666666666:"Faisal",
7777777777:"Layla"}
xx = int(input('Enter the number : '))
for key, value in phone_book.items():
if xx == value:
print('this phone number', v, 'belong to ', k)
phone_belong_to = k
print('thank you')
quit()
print("think you !: ")
print(type(phone_book))
frist
In the event that a number in the directory is sent, the name of the owner of the entered number will be printed
second
If the phone number is less than or more than 10 digits, or some other value (contains letters, symbols, and logical values for example
| [
"I dind't understand the second part but try it like this:\ncode:\nphone_book = {1111111111:\"amal\",\n 2222222222:\"Mohammed\",\n 3333333333:\"Khadijah\",\n 4444444444:\"Abdullah\",\n 5555555555:\"Rawan\",\n 6666666666:\"Faisal\",\n 7777777777:\"Layla\"}\nxx = int(input('Enter the number : '))\nfor key, value in phone_book.items():\n if xx == key:\n print(\"this phone number {} belong to {}\".format(key, value))\n phone_belong_to = value\n print('thank you')\n quit()\nprint('not found!')\n\n\nInput:\nEnter the number : 1111111111\n\nOutput:\nthis phone number 1111111111 belong to amal\nthank you\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"for_loop",
"function",
"python"
] | stackoverflow_0074668930_dictionary_for_loop_function_python.txt |
Q:
cant add lowercase text discord bot in python
I have a small code to use it in discord created in python and I have a small problem
The command is currently written in uppercase text and I would like it to be written in lowercase, if it is not written in lowercase the bot does not send the images to discord
he command is used:
!ubi ESTABLO ELEVADO
Should be used:
!ubi establo elevado
but in this case it does not work for me I have tried several codes and it does not work:
This is the code:
@bot.command()
async def ubi(ctx, *, args):
response = requests.get('https://jose89fcb.es/apifortnite/api.io.php')
data = response.json()
for api in data['list']:
if args in api["name"]:
await ctx.send(f'{api["images"][0]["url"]}')
A:
this is what you are looking for!
@bot.command()
async def ubi(ctx, *, args):
response = requests.get('https://jose89fcb.es/apifortnite/api.io.php')
data = response.json()
for api in data['list']:
if args in api["name"].lower():
await ctx.send(f'{api["images"][0]["url"]}')
| cant add lowercase text discord bot in python | I have a small code to use it in discord created in python and I have a small problem
The command is currently written in uppercase text and I would like it to be written in lowercase, if it is not written in lowercase the bot does not send the images to discord
he command is used:
!ubi ESTABLO ELEVADO
Should be used:
!ubi establo elevado
but in this case it does not work for me I have tried several codes and it does not work:
This is the code:
@bot.command()
async def ubi(ctx, *, args):
response = requests.get('https://jose89fcb.es/apifortnite/api.io.php')
data = response.json()
for api in data['list']:
if args in api["name"]:
await ctx.send(f'{api["images"][0]["url"]}')
| [
"this is what you are looking for!\[email protected]()\n async def ubi(ctx, *, args):\n response = requests.get('https://jose89fcb.es/apifortnite/api.io.php')\n data = response.json()\n for api in data['list']:\n if args in api[\"name\"].lower():\n \n await ctx.send(f'{api[\"images\"][0][\"url\"]}')\n\n"
] | [
0
] | [] | [] | [
"discord",
"python"
] | stackoverflow_0074669087_discord_python.txt |
Q:
Assign data in JSON file to a variable based on condition python
I am trying to grab data from JSON file based on what quarter the dates represent. My goal is to assign the data to a variable so I should have Q1, Q2, Q3, Q4 variables holding the data inside. Below is the JSON:
{
"lastDate":{
"0":"2022Q4",
"1":"2022Q4",
"2":"2022Q4",
"7":"2022Q4",
"8":"2022Q4",
"9":"2022Q4",
"18":"2022Q3",
"19":"2022Q3",
"22":"2022Q3",
"24":"2022Q2"
},
"transactionType":{
"0":"Sell",
"1":"Automatic Sell",
"2":"Automatic Sell",
"7":"Automatic Sell",
"8":"Sell",
"9":"Automatic Sell",
"18":"Automatic Sell",
"19":"Automatic Sell",
"22":"Automatic Sell",
"24":"Automatic Sell"
},
"sharesTraded":{
"0":"20,200",
"1":"176,299",
"2":"8,053",
"7":"167,889",
"8":"13,250",
"9":"176,299",
"18":"96,735",
"19":"15,366",
"22":"25,000",
"24":"25,000"
}
}
Now if i try to use the following code:
import json
data = json.load(open("AAPL22data.json"))
Q2data = [item for item in data if '2022Q2' in data['lastDate']]
print(Q2data)
My ideal output should be:
{
"lastDate":{
"24":"2022Q2"
},
"transactionType":{
"24":"Automatic Sell"
},
"sharesTraded":{
"24":"25,000"
}
}
And then repeat the same structure for the other quarters. However, my current output gives me "[ ]"
A:
With pandas you can read this nested dictionary a transform it to a table representation. Then the aggregation you are required becomes quite natural.
import pandas as pd
sample_dict = {
"lastDate":{
"0":"2022Q4",
"1":"2022Q4",
"2":"2022Q4",
"7":"2022Q4",
"8":"2022Q4",
"9":"2022Q4",
"18":"2022Q3",
"19":"2022Q3",
"22":"2022Q3",
"24":"2022Q2"
},
"transactionType":{
"0":"Sell",
"1":"Automatic Sell",
"2":"Automatic Sell",
"7":"Automatic Sell",
"8":"Sell",
"9":"Automatic Sell",
"18":"Automatic Sell",
"19":"Automatic Sell",
"22":"Automatic Sell",
"24":"Automatic Sell"
},
"sharesTraded":{
"0":"20,200",
"1":"176,299",
"2":"8,053",
"7":"167,889",
"8":"13,250",
"9":"176,299",
"18":"96,735",
"19":"15,366",
"22":"25,000",
"24":"25,000"
}
}
print(pd.DataFrame.from_dict(sample_dict))
returns
Output:
lastDate transactionType sharesTraded
0 2022Q4 Sell 20,200
1 2022Q4 Automatic Sell 176,299
2 2022Q4 Automatic Sell 8,053
7 2022Q4 Automatic Sell 167,889
8 2022Q4 Sell 13,250
9 2022Q4 Automatic Sell 176,299
18 2022Q3 Automatic Sell 96,735
19 2022Q3 Automatic Sell 15,366
22 2022Q3 Automatic Sell 25,000
24 2022Q2 Automatic Sell 25,000
then a simple group_by should do the trick.
A:
Use a dictionary comprehension:
import json
my_json = """{
"lastDate":{
"0":"2022Q4",
"1":"2022Q4",
"2":"2022Q4",
"7":"2022Q4",
"8":"2022Q4",
"9":"2022Q4",
"18":"2022Q3",
"19":"2022Q3",
"22":"2022Q3",
"24":"2022Q2"
},
"transactionType":{
"0":"Sell",
"1":"Automatic Sell",
"2":"Automatic Sell",
"7":"Automatic Sell",
"8":"Sell",
"9":"Automatic Sell",
"18":"Automatic Sell",
"19":"Automatic Sell",
"22":"Automatic Sell",
"24":"Automatic Sell"
},
"sharesTraded":{
"0":"20,200",
"1":"176,299",
"2":"8,053",
"7":"167,889",
"8":"13,250",
"9":"176,299",
"18":"96,735",
"19":"15,366",
"22":"25,000",
"24":"25,000"
}
}"""
data = json.loads(my_json)
var = "24" #This corresponds to 2022 Q2 in your example
data = {k:{var: v[var]} for k, v in data.items()}
data = json.dumps(data, indent = 2)
print(data)
Output:
{
"lastDate": {
"24": "2022Q2"
},
"transactionType": {
"24": "Automatic Sell"
},
"sharesTraded": {
"24": "25,000"
}
}
A:
Thanks to @FrancoMilanese for the info on Pandas group_by here is the answer below:
import json
import pandas as pd
data = json.load(open("AAPL22data.json"))
df = pd.DataFrame.from_dict(data)
q2df = df.groupby('lastDate')
q2df.get_group('2022Q2') #change '2022q2' for others & assign to a different variable
| Assign data in JSON file to a variable based on condition python | I am trying to grab data from JSON file based on what quarter the dates represent. My goal is to assign the data to a variable so I should have Q1, Q2, Q3, Q4 variables holding the data inside. Below is the JSON:
{
"lastDate":{
"0":"2022Q4",
"1":"2022Q4",
"2":"2022Q4",
"7":"2022Q4",
"8":"2022Q4",
"9":"2022Q4",
"18":"2022Q3",
"19":"2022Q3",
"22":"2022Q3",
"24":"2022Q2"
},
"transactionType":{
"0":"Sell",
"1":"Automatic Sell",
"2":"Automatic Sell",
"7":"Automatic Sell",
"8":"Sell",
"9":"Automatic Sell",
"18":"Automatic Sell",
"19":"Automatic Sell",
"22":"Automatic Sell",
"24":"Automatic Sell"
},
"sharesTraded":{
"0":"20,200",
"1":"176,299",
"2":"8,053",
"7":"167,889",
"8":"13,250",
"9":"176,299",
"18":"96,735",
"19":"15,366",
"22":"25,000",
"24":"25,000"
}
}
Now if i try to use the following code:
import json
data = json.load(open("AAPL22data.json"))
Q2data = [item for item in data if '2022Q2' in data['lastDate']]
print(Q2data)
My ideal output should be:
{
"lastDate":{
"24":"2022Q2"
},
"transactionType":{
"24":"Automatic Sell"
},
"sharesTraded":{
"24":"25,000"
}
}
And then repeat the same structure for the other quarters. However, my current output gives me "[ ]"
| [
"With pandas you can read this nested dictionary a transform it to a table representation. Then the aggregation you are required becomes quite natural.\nimport pandas as pd \n\nsample_dict = {\n \"lastDate\":{\n \"0\":\"2022Q4\",\n \"1\":\"2022Q4\",\n \"2\":\"2022Q4\",\n \"7\":\"2022Q4\",\n \"8\":\"2022Q4\",\n \"9\":\"2022Q4\",\n \"18\":\"2022Q3\",\n \"19\":\"2022Q3\",\n \"22\":\"2022Q3\",\n \"24\":\"2022Q2\"\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n \"9\":\"Automatic Sell\",\n \"18\":\"Automatic Sell\",\n \"19\":\"Automatic Sell\",\n \"22\":\"Automatic Sell\",\n \"24\":\"Automatic Sell\"\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n \"9\":\"176,299\",\n \"18\":\"96,735\",\n \"19\":\"15,366\",\n \"22\":\"25,000\",\n \"24\":\"25,000\"\n }\n}\n\nprint(pd.DataFrame.from_dict(sample_dict))\n\nreturns\nOutput:\n\n lastDate transactionType sharesTraded\n0 2022Q4 Sell 20,200\n1 2022Q4 Automatic Sell 176,299\n2 2022Q4 Automatic Sell 8,053\n7 2022Q4 Automatic Sell 167,889\n8 2022Q4 Sell 13,250\n9 2022Q4 Automatic Sell 176,299\n18 2022Q3 Automatic Sell 96,735\n19 2022Q3 Automatic Sell 15,366\n22 2022Q3 Automatic Sell 25,000\n24 2022Q2 Automatic Sell 25,000\n\nthen a simple group_by should do the trick.\n",
"Use a dictionary comprehension:\nimport json\n\nmy_json = \"\"\"{\n \"lastDate\":{\n \"0\":\"2022Q4\",\n \"1\":\"2022Q4\",\n \"2\":\"2022Q4\",\n \"7\":\"2022Q4\",\n \"8\":\"2022Q4\",\n \"9\":\"2022Q4\",\n \"18\":\"2022Q3\",\n \"19\":\"2022Q3\",\n \"22\":\"2022Q3\",\n \"24\":\"2022Q2\"\n },\n \"transactionType\":{\n \"0\":\"Sell\",\n \"1\":\"Automatic Sell\",\n \"2\":\"Automatic Sell\",\n \"7\":\"Automatic Sell\",\n \"8\":\"Sell\",\n \"9\":\"Automatic Sell\",\n \"18\":\"Automatic Sell\",\n \"19\":\"Automatic Sell\",\n \"22\":\"Automatic Sell\",\n \"24\":\"Automatic Sell\"\n },\n \"sharesTraded\":{\n \"0\":\"20,200\",\n \"1\":\"176,299\",\n \"2\":\"8,053\",\n \"7\":\"167,889\",\n \"8\":\"13,250\",\n \"9\":\"176,299\",\n \"18\":\"96,735\",\n \"19\":\"15,366\",\n \"22\":\"25,000\",\n \"24\":\"25,000\"\n }\n}\"\"\"\n\ndata = json.loads(my_json)\n\nvar = \"24\" #This corresponds to 2022 Q2 in your example\n\ndata = {k:{var: v[var]} for k, v in data.items()}\ndata = json.dumps(data, indent = 2)\n\nprint(data)\n\nOutput:\n{\n \"lastDate\": {\n \"24\": \"2022Q2\"\n },\n \"transactionType\": {\n \"24\": \"Automatic Sell\"\n },\n \"sharesTraded\": {\n \"24\": \"25,000\"\n }\n}\n\n",
"Thanks to @FrancoMilanese for the info on Pandas group_by here is the answer below:\nimport json\nimport pandas as pd \n\ndata = json.load(open(\"AAPL22data.json\"))\n\ndf = pd.DataFrame.from_dict(data)\n\nq2df = df.groupby('lastDate')\n\nq2df.get_group('2022Q2') #change '2022q2' for others & assign to a different variable\n\n"
] | [
1,
1,
0
] | [] | [] | [
"for_loop",
"json",
"python"
] | stackoverflow_0074666206_for_loop_json_python.txt |
Q:
Why won't list memorize previous inputs and sum them?
With each iteration the list only presents the last appended input and not the sum of the last input + previous appended inputs.
def main_program():
n = []
n.append(int(input("insert:\n")))
print(sum(n))
while True:
main_program()
if input("Add another number? (Y/N):\n") == "N":
break
I'm trying to create a "snowball effect" for lack of a better description. I wanted the program to store each appended input and sum them all together.
A:
Define n just once.
def main_program():
n.append(int(input("insert:\n")))
print(sum(n))
n = []
while True:
main_program()
if input("Add another number? (Y/N):\n") == "N":
break
Passing the list as parameter in the function main_program also works, since lists are call-by-reference.
| Why won't list memorize previous inputs and sum them? | With each iteration the list only presents the last appended input and not the sum of the last input + previous appended inputs.
def main_program():
n = []
n.append(int(input("insert:\n")))
print(sum(n))
while True:
main_program()
if input("Add another number? (Y/N):\n") == "N":
break
I'm trying to create a "snowball effect" for lack of a better description. I wanted the program to store each appended input and sum them all together.
| [
"Define n just once.\ndef main_program():\n n.append(int(input(\"insert:\\n\")))\n print(sum(n))\n\nn = []\nwhile True:\n main_program()\n if input(\"Add another number? (Y/N):\\n\") == \"N\":\n break\n\nPassing the list as parameter in the function main_program also works, since lists are call-by-reference.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074669171_python_python_3.x.txt |
Q:
Tabula-py: specify parameters for tabula.io.build_options
I am trying to understand how the build_options function defined in tabula.io module and the java_options in function convert_into work.
To understand it I wrote my code with just the page options specified:
import tabula
options = tabula.io.build_options(pages="all")
dfs = tabula.io.convert_into('input.pdf',"output.csv",output_format="csv",java_options=options)
but I get this error:
Error from tabula-java:
Unrecognized option: --pages
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
What's the correct way to use the build_options function?
A:
java_options expects list of string.
tabula.convert_into('input.pdf',"output.csv",output_format="csv", pages="all")
You don't have to use build_options.
See also:
https://tabula-py.readthedocs.io/en/latest/tabula.html#tabula.io.convert_into
| Tabula-py: specify parameters for tabula.io.build_options | I am trying to understand how the build_options function defined in tabula.io module and the java_options in function convert_into work.
To understand it I wrote my code with just the page options specified:
import tabula
options = tabula.io.build_options(pages="all")
dfs = tabula.io.convert_into('input.pdf',"output.csv",output_format="csv",java_options=options)
but I get this error:
Error from tabula-java:
Unrecognized option: --pages
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
What's the correct way to use the build_options function?
| [
"java_options expects list of string.\ntabula.convert_into('input.pdf',\"output.csv\",output_format=\"csv\", pages=\"all\")\n\nYou don't have to use build_options.\nSee also:\nhttps://tabula-py.readthedocs.io/en/latest/tabula.html#tabula.io.convert_into\n"
] | [
0
] | [] | [] | [
"python",
"tabula_py"
] | stackoverflow_0072317873_python_tabula_py.txt |
Q:
Incompatible shapes Mean Squared Error Keras
I want to train a RNN with Keras, the shape for the X is (4413, 71, 19) while for y is (4413,2)
Code
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(Dense(32, activation='relu'))
model.add(Dropout(.2))
model.add(Dense(2, activation='softmax'))
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_squared_error'])
When I fit the model I got this error, seems that the loss function can't fit with this kind of data
Incompatible shapes: [64,2] vs. [64,71,2]
[[{{node mean_squared_error/SquaredDifference}}]] [Op:__inference_train_function_157671]
A:
Try setting the parameter return_sequences of the last LSTM layer to False:
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(LSTM(128, return_sequences=True))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(LSTM(128, return_sequences=False))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(Dense(32, activation='relu'))
model.add(Dropout(.2))
model.add(Dense(2, activation='linear'))
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_squared_error'])
I have also changed the activation function in the output layer to linear, since a softmax layer does not make much sense in your case. Also refer to this answer.
| Incompatible shapes Mean Squared Error Keras | I want to train a RNN with Keras, the shape for the X is (4413, 71, 19) while for y is (4413,2)
Code
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(Dense(32, activation='relu'))
model.add(Dropout(.2))
model.add(Dense(2, activation='softmax'))
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_squared_error'])
When I fit the model I got this error, seems that the loss function can't fit with this kind of data
Incompatible shapes: [64,2] vs. [64,71,2]
[[{{node mean_squared_error/SquaredDifference}}]] [Op:__inference_train_function_157671]
| [
"Try setting the parameter return_sequences of the last LSTM layer to False:\nmodel = Sequential()\nmodel.add(LSTM(128, return_sequences=True, input_shape=(None,19)))\nmodel.add(Dropout(.2))\nmodel.add(BatchNormalization())\n\nmodel.add(LSTM(128, return_sequences=True))\nmodel.add(Dropout(.2))\nmodel.add(BatchNormalization())\n\nmodel.add(LSTM(128, return_sequences=False))\nmodel.add(Dropout(.2))\nmodel.add(BatchNormalization())\n\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dropout(.2))\n\nmodel.add(Dense(2, activation='linear'))\n\nmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_squared_error'])\n\nI have also changed the activation function in the output layer to linear, since a softmax layer does not make much sense in your case. Also refer to this answer.\n"
] | [
1
] | [] | [] | [
"keras",
"lstm",
"python",
"tensorflow"
] | stackoverflow_0074669249_keras_lstm_python_tensorflow.txt |
Q:
Unable to load tables with "Load more" options in a website using Python
Need to scrape the full table from this site with "Load more" option.
As of now when I`m scraping , I only get the one that shows up by default on when loading the page.
import pandas as pd
import requests
from six.moves import urllib
URL2 = "https://www.mykhel.com/football/indian-super-league-player-stats-l750/"
header = {'Accept-Language': "en-US,en;q=0.9",
'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"
}
resp2 = requests.get(url=URL2, headers=header).text
tables2 = pd.read_html(resp2)
overview_table2= tables2[0]
overview_table2
Player Name
Team
Matches
Goals
Time Played
Unnamed: 5
0
Jorge Pereyra Diaz
Mumbai City
9
6
538 Mins
NaN
1
Cleiton Silva
SC East Bengal
8
5
707 Mins
NaN
2
Abdenasser El Khayati
Chennaiyin FC
5
4
231 Mins
NaN
3
Lallianzuala Chhangte
Mumbai City
9
4
737 Mins
NaN
4
Nandhakumar Sekar
Odisha
8
4
673 Mins
NaN
5
Ivan Kalyuzhnyi
Kerala Blasters
7
4
428 Mins
NaN
6
Bipin Singh
Mumbai City
9
4
806 Mins
NaN
7
Noah Sadaoui
Goa
8
4
489 Mins
NaN
8
Diego Mauricio
Odisha
8
3
526 Mins
NaN
9
Pedro Martin
Odisha
8
3
263 Mins
NaN
10
Dimitri Petratos
ATK Mohun Bagan
6
3
517 Mins
NaN
11
Petar Sliskovic
Chennaiyin FC
8
3
662 Mins
NaN
12
Holicharan Narzary
Hyderabad
9
3
705 Mins
NaN
13
Dimitrios Diamantakos
Kerala Blasters
7
3
529 Mins
NaN
14
Alberto Noguera
Mumbai City
9
3
371 Mins
NaN
15
Jerry Mawihmingthanga
Odisha
8
3
611 Mins
NaN
16
Hugo Boumous
ATK Mohun Bagan
7
2
580 Mins
NaN
17
Javi Hernandez
Bengaluru
6
2
397 Mins
NaN
18
Borja Herrera
Hyderabad
9
2
314 Mins
NaN
19
Mohammad Yasir
Hyderabad
9
2
777 Mins
NaN
20
Load More....
Load More....
Load More....
Load More....
Load More....
Load More....
But I need the full table , including the data under "Load more", please help.
A:
import requests
import pandas as pd
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'
}
def main(url):
params = {
"action": "stats",
"league_id": "750",
"limit": "300",
"offset": "0",
"part": "leagues",
"season_id": "2022",
"section": "football",
"stats_type": "player",
"tab": "overview"
}
r = requests.get(url, headers=headers, params=params)
soup = BeautifulSoup(r.text, 'lxml')
goal = [(x['title'], *[i.get_text(strip=True) for i in x.find_all_next('td', limit=4)])
for x in soup.select('a.player_link')]
df = pd.DataFrame(
goal, columns=['Name', 'Team', 'Matches', 'Goals', 'Time Played'])
print(df)
main('https://www.mykhel.com/src/index.php')
Output:
Name Team Matches Goals Time Played
0 Jorge Pereyra Diaz Mumbai City 9 6 538 Mins
1 Cleiton Silva SC East Bengal 8 5 707 Mins
2 Abdenasser El Khayati Chennaiyin FC 5 4 231 Mins
3 Lallianzuala Chhangte Mumbai City 9 4 737 Mins
4 Nandhakumar Sekar Odisha 8 4 673 Mins
.. ... ... ... ... ...
268 Sarthak Golui SC East Bengal 6 0 402 Mins
269 Ivan Gonzalez SC East Bengal 8 0 683 Mins
270 Michael Jakobsen NorthEast United 8 0 676 Mins
271 Pratik Chowdhary Jamshedpur FC 6 0 495 Mins
272 Chungnunga Lal SC East Bengal 8 0 720 Mins
[273 rows x 5 columns]
A:
This is a dynamically loaded page, so you can not parse all the contents without hitting a button.
Well… may be you can with XHR or smth like that, may be someone will contribute to the answers here.
I'll stick to working with dynamically loaded pages with Selenium browser automation suite.
Installation
To get started, you'll need to install selenium bindings:
pip install selenium
You seem to already have beautifulsoup, but for anyone who might come across this answer, we'll also need it and html5lib, we'll need them later to parse the table:
pip install html5lib BeautifulSoup4
Now, for selenium to work you'll need a driver installed for a browser of your choice. To get the drivers you may use Selenium Manager, Driver Management Software or download the drivers manually. The above mentioned options are something new, I have my manually downloaded drivers for ages, so I'll stick to them. I'll duplicate here the download links:
Browser
Link to driver download
Chrome:
https://sites.google.com/chromium.org/driver/
Edge:
https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox:
https://github.com/mozilla/geckodriver/releases
Safari:
https://webkit.org/blog/6900/webdriver-support-in-safari-10/
Opera:
https://github.com/operasoftware/operachromiumdriver/releases
You can use any browser, e.g. Brave browser, Yandex Browser, basically any Chromium based browser of your choice or even Tor browser
Anyway, it's a bit out of this answer scope, just keep in mind, for any browser and it's family you'll need a driver.
I'll stick with Firefox. Hence you need Firefox installed and driver placed somewhere. The best option would be to add this folder to PATH variable.
If you choose chromium, you'll have to strictly stick to Chrome browser version. As for Firefox, I have a pretty old geckodriver 0.29.1 and it works like a charm with the latest update.
Hands on
import pandas as pd
from selenium import webdriver
URL2 = "https://www.mykhel.com/football/indian-super-league-player-stats-l750/"
driver = webdriver.Firefox()
driver.get(URL2)
element = driver.find_element_by_xpath("//a[text()=' Load More.... ']")
while(element.is_displayed()):
driver.execute_script("arguments[0].click();", element)
table = driver.find_element_by_css_selector('table')
tables2 = pd.read_html(table.get_attribute('outerHTML'))
driver.close()
overview_table2 = tables2[0].dropna(how='all').dropna(axis='columns', how='all')
overview_table2.drop_duplicates().reset_index(drop=True)
overview_table2
We only need pandas for our resulting table and selenium for web automation.
URL2 — is the same variable you used
driver = webdriver.Firefox() — here we instantiate Firefox and the browser will get opened. This is where selenium magic will happen.
Note: If you decided to skip adding driver to a PATH variable, you can directly reference your here, e.g.:
webdriver.Firefox(r"C:\WebDriver\bin")
webdriver.Chrome(service=Service(executable_path="/path/to/chromedriver"))
driver.get(URL2) — open the desired page
element = driver.find_element_by_xpath("//a[text()=' Load More.... ']")
Using xpath selector we find a link that has the same text as your 20th row.
With that stored element we click it all the time till it disappears.
It would be more sensible and easy to just use element.click(), but it results in an error. More info on other stack overflow question.
Assign table variable with a corresponding element.
tables2 I left this weird variable name as is in your question.
Here we get outerHTML as innnerHTML would render contents of the <table> tag, but not the tag itself.
We should not forget to .close() our driver as we don't need it anymore.
As a result of html parsing there will be a list just like in question provided. I drop here the unnamed column and last empty row.
The resulting overview_table2 looks like:
Player Name
Team
Matches
Goals
Time Played
0
Jorge Pereyra Diaz
Mumbai City
9.0
6.0
538 Mins
1
Cleiton Silva
SC East Bengal
8.0
5.0
707 Mins
2
Abdenasser El Khayati
Chennaiyin FC
5.0
4.0
231 Mins
...
...
...
...
...
...
270
Michael Jakobsen
NorthEast United
8.0
0.0
676 Mins
271
Pratik Chowdhary
Jamshedpur FC
6.0
0.0
495 Mins
272
Chungnunga Lal
SC East Bengal
8.0
0.0
720 Mins
Side note
Job done. As some further improvement you may play with different browsers and try the headless mode, a mode when browser does not open on you desktop environment, but rather runs silently in the background.
| Unable to load tables with "Load more" options in a website using Python | Need to scrape the full table from this site with "Load more" option.
As of now when I`m scraping , I only get the one that shows up by default on when loading the page.
import pandas as pd
import requests
from six.moves import urllib
URL2 = "https://www.mykhel.com/football/indian-super-league-player-stats-l750/"
header = {'Accept-Language': "en-US,en;q=0.9",
'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"
}
resp2 = requests.get(url=URL2, headers=header).text
tables2 = pd.read_html(resp2)
overview_table2= tables2[0]
overview_table2
Player Name
Team
Matches
Goals
Time Played
Unnamed: 5
0
Jorge Pereyra Diaz
Mumbai City
9
6
538 Mins
NaN
1
Cleiton Silva
SC East Bengal
8
5
707 Mins
NaN
2
Abdenasser El Khayati
Chennaiyin FC
5
4
231 Mins
NaN
3
Lallianzuala Chhangte
Mumbai City
9
4
737 Mins
NaN
4
Nandhakumar Sekar
Odisha
8
4
673 Mins
NaN
5
Ivan Kalyuzhnyi
Kerala Blasters
7
4
428 Mins
NaN
6
Bipin Singh
Mumbai City
9
4
806 Mins
NaN
7
Noah Sadaoui
Goa
8
4
489 Mins
NaN
8
Diego Mauricio
Odisha
8
3
526 Mins
NaN
9
Pedro Martin
Odisha
8
3
263 Mins
NaN
10
Dimitri Petratos
ATK Mohun Bagan
6
3
517 Mins
NaN
11
Petar Sliskovic
Chennaiyin FC
8
3
662 Mins
NaN
12
Holicharan Narzary
Hyderabad
9
3
705 Mins
NaN
13
Dimitrios Diamantakos
Kerala Blasters
7
3
529 Mins
NaN
14
Alberto Noguera
Mumbai City
9
3
371 Mins
NaN
15
Jerry Mawihmingthanga
Odisha
8
3
611 Mins
NaN
16
Hugo Boumous
ATK Mohun Bagan
7
2
580 Mins
NaN
17
Javi Hernandez
Bengaluru
6
2
397 Mins
NaN
18
Borja Herrera
Hyderabad
9
2
314 Mins
NaN
19
Mohammad Yasir
Hyderabad
9
2
777 Mins
NaN
20
Load More....
Load More....
Load More....
Load More....
Load More....
Load More....
But I need the full table , including the data under "Load more", please help.
| [
"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\ndef main(url):\n params = {\n \"action\": \"stats\",\n \"league_id\": \"750\",\n \"limit\": \"300\",\n \"offset\": \"0\",\n \"part\": \"leagues\",\n \"season_id\": \"2022\",\n \"section\": \"football\",\n \"stats_type\": \"player\",\n \"tab\": \"overview\"\n }\n r = requests.get(url, headers=headers, params=params)\n soup = BeautifulSoup(r.text, 'lxml')\n goal = [(x['title'], *[i.get_text(strip=True) for i in x.find_all_next('td', limit=4)])\n for x in soup.select('a.player_link')]\n df = pd.DataFrame(\n goal, columns=['Name', 'Team', 'Matches', 'Goals', 'Time Played'])\n print(df)\n\n\nmain('https://www.mykhel.com/src/index.php')\n\nOutput:\n Name Team Matches Goals Time Played\n0 Jorge Pereyra Diaz Mumbai City 9 6 538 Mins\n1 Cleiton Silva SC East Bengal 8 5 707 Mins\n2 Abdenasser El Khayati Chennaiyin FC 5 4 231 Mins\n3 Lallianzuala Chhangte Mumbai City 9 4 737 Mins\n4 Nandhakumar Sekar Odisha 8 4 673 Mins\n.. ... ... ... ... ...\n268 Sarthak Golui SC East Bengal 6 0 402 Mins\n269 Ivan Gonzalez SC East Bengal 8 0 683 Mins\n270 Michael Jakobsen NorthEast United 8 0 676 Mins\n271 Pratik Chowdhary Jamshedpur FC 6 0 495 Mins\n272 Chungnunga Lal SC East Bengal 8 0 720 Mins\n\n[273 rows x 5 columns]\n\n",
"This is a dynamically loaded page, so you can not parse all the contents without hitting a button.\nWell… may be you can with XHR or smth like that, may be someone will contribute to the answers here.\nI'll stick to working with dynamically loaded pages with Selenium browser automation suite.\nInstallation\nTo get started, you'll need to install selenium bindings:\npip install selenium\n\nYou seem to already have beautifulsoup, but for anyone who might come across this answer, we'll also need it and html5lib, we'll need them later to parse the table:\npip install html5lib BeautifulSoup4\n\nNow, for selenium to work you'll need a driver installed for a browser of your choice. To get the drivers you may use Selenium Manager, Driver Management Software or download the drivers manually. The above mentioned options are something new, I have my manually downloaded drivers for ages, so I'll stick to them. I'll duplicate here the download links:\n\n\n\n\nBrowser\nLink to driver download\n\n\n\n\nChrome:\nhttps://sites.google.com/chromium.org/driver/\n\n\nEdge:\nhttps://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/\n\n\nFirefox:\nhttps://github.com/mozilla/geckodriver/releases\n\n\nSafari:\nhttps://webkit.org/blog/6900/webdriver-support-in-safari-10/\n\n\nOpera:\nhttps://github.com/operasoftware/operachromiumdriver/releases\n\n\n\n\nYou can use any browser, e.g. Brave browser, Yandex Browser, basically any Chromium based browser of your choice or even Tor browser \nAnyway, it's a bit out of this answer scope, just keep in mind, for any browser and it's family you'll need a driver.\nI'll stick with Firefox. Hence you need Firefox installed and driver placed somewhere. The best option would be to add this folder to PATH variable.\nIf you choose chromium, you'll have to strictly stick to Chrome browser version. As for Firefox, I have a pretty old geckodriver 0.29.1 and it works like a charm with the latest update.\nHands on\nimport pandas as pd\nfrom selenium import webdriver\n\nURL2 = \"https://www.mykhel.com/football/indian-super-league-player-stats-l750/\"\n\ndriver = webdriver.Firefox()\ndriver.get(URL2)\n\nelement = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\")\nwhile(element.is_displayed()):\n driver.execute_script(\"arguments[0].click();\", element)\n\ntable = driver.find_element_by_css_selector('table')\ntables2 = pd.read_html(table.get_attribute('outerHTML'))\ndriver.close()\n\noverview_table2 = tables2[0].dropna(how='all').dropna(axis='columns', how='all')\noverview_table2.drop_duplicates().reset_index(drop=True)\noverview_table2\n\n\nWe only need pandas for our resulting table and selenium for web automation.\nURL2 — is the same variable you used\ndriver = webdriver.Firefox() — here we instantiate Firefox and the browser will get opened. This is where selenium magic will happen.\nNote: If you decided to skip adding driver to a PATH variable, you can directly reference your here, e.g.:\n\nwebdriver.Firefox(r\"C:\\WebDriver\\bin\")\nwebdriver.Chrome(service=Service(executable_path=\"/path/to/chromedriver\"))\n\n\ndriver.get(URL2) — open the desired page\nelement = driver.find_element_by_xpath(\"//a[text()=' Load More.... ']\")\nUsing xpath selector we find a link that has the same text as your 20th row.\nWith that stored element we click it all the time till it disappears.\nIt would be more sensible and easy to just use element.click(), but it results in an error. More info on other stack overflow question.\nAssign table variable with a corresponding element.\ntables2 I left this weird variable name as is in your question.\nHere we get outerHTML as innnerHTML would render contents of the <table> tag, but not the tag itself.\nWe should not forget to .close() our driver as we don't need it anymore.\nAs a result of html parsing there will be a list just like in question provided. I drop here the unnamed column and last empty row.\n\nThe resulting overview_table2 looks like:\n\n\n\n\n\nPlayer Name\nTeam\nMatches\nGoals\nTime Played\n\n\n\n\n0\nJorge Pereyra Diaz\nMumbai City\n9.0\n6.0\n538 Mins\n\n\n1\nCleiton Silva\nSC East Bengal\n8.0\n5.0\n707 Mins\n\n\n2\nAbdenasser El Khayati\nChennaiyin FC\n5.0\n4.0\n231 Mins\n\n\n...\n...\n...\n...\n...\n...\n\n\n270\nMichael Jakobsen\nNorthEast United\n8.0\n0.0\n676 Mins\n\n\n271\nPratik Chowdhary\nJamshedpur FC\n6.0\n0.0\n495 Mins\n\n\n272\nChungnunga Lal\nSC East Bengal\n8.0\n0.0\n720 Mins\n\n\n\nSide note\nJob done. As some further improvement you may play with different browsers and try the headless mode, a mode when browser does not open on you desktop environment, but rather runs silently in the background.\n"
] | [
3,
0
] | [] | [] | [
"beautifulsoup",
"dataframe",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074668149_beautifulsoup_dataframe_pandas_python_web_scraping.txt |
Q:
How can i have two not arguments in an if statement
I want to check if the following value is not a digit and is not "a" or "b" but I'm met with a syntax error. It says it expect ":" after not in the second argument.
if not char.isdigit() and not in ('a', 'b'):
I don't know what I can try to fix this. I could nest the if statement but that leads to bad code and I know there must be some solution.
A:
The line should be:
if not char.isdigit() and char not in ('a', 'b'):
You have to declare what variable is not in ('a', 'b')
Furthermore, I would take a look at how to structure questions on StackOverflow.
| How can i have two not arguments in an if statement | I want to check if the following value is not a digit and is not "a" or "b" but I'm met with a syntax error. It says it expect ":" after not in the second argument.
if not char.isdigit() and not in ('a', 'b'):
I don't know what I can try to fix this. I could nest the if statement but that leads to bad code and I know there must be some solution.
| [
"The line should be:\nif not char.isdigit() and char not in ('a', 'b'):\n\nYou have to declare what variable is not in ('a', 'b')\nFurthermore, I would take a look at how to structure questions on StackOverflow.\n"
] | [
2
] | [] | [] | [
"python",
"python_3.x",
"string"
] | stackoverflow_0074669271_python_python_3.x_string.txt |
Q:
Create a weighted graph from an adjacency matrix in graph-tool, python interface
How should I create a graph using graph-tool in python, out of an adjacency matrix?
Assume we have adj matrix as the adjacency matrix.
What I do now is like this:
g = graph_tool.Graph(directed = False)
g.add_vertex(len(adj))
edge_weights = g.new_edge_property('double')
for i in range(adj.shape[0]):
for j in range(adj.shape[1]):
if i > j and adj[i,j] != 0:
e = g.add_edge(i, j)
edge_weights[e] = adj[i,j]
But it doesn't feel right, do we have any better solution for this?
(and I guess a proper tag for this would be graph-tool, but I can't add it, some kind person with enough privileges could make the tag?)
A:
Graph-tool now includes a function to add a list of edges to the graph. You can now do, for instance:
import graph_tool as gt
import numpy as np
g = gt.Graph(directed=False)
adj = np.random.randint(0, 2, (100, 100))
g.add_edge_list(np.transpose(adj.nonzero()))
A:
this is the extension of Tiago's answer for the weighted graph:
adj = numpy.random.randint(0, 10, (100, 100)) # a random directed graph
idx = adj.nonzero()
weights = adj[idx]
g = Graph()
g.add_edge_list(transpose(idx)))
#add weights as an edge propetyMap
ew = g.new_edge_property("double")
ew.a = weights
g.ep['edge_weight'] = ew
A:
This should be a comment to Tiago's answer, but I don't have enough reputation for that.
For the latest version (2.26) of graph_tool I believe there is a missing transpose there. The i,j entry of the adjacency matrix denotes the weight of the edge going from vertex j to vertex i, so it should be
g.add_edge_list(transpose(transpose(adj).nonzero()))
A:
import numpy as np
import graph_tool.all as gt
g = gt.Graph(directed=False)
adj = np.tril(adj)
g.add_edge_list(np.transpose(adj.nonzero()))
Without np.tril the adjacency matrix will contain entries with 2s instead one 1s because every edge is counted twice. Things like gt.num_edges() will be incorrect too.
| Create a weighted graph from an adjacency matrix in graph-tool, python interface | How should I create a graph using graph-tool in python, out of an adjacency matrix?
Assume we have adj matrix as the adjacency matrix.
What I do now is like this:
g = graph_tool.Graph(directed = False)
g.add_vertex(len(adj))
edge_weights = g.new_edge_property('double')
for i in range(adj.shape[0]):
for j in range(adj.shape[1]):
if i > j and adj[i,j] != 0:
e = g.add_edge(i, j)
edge_weights[e] = adj[i,j]
But it doesn't feel right, do we have any better solution for this?
(and I guess a proper tag for this would be graph-tool, but I can't add it, some kind person with enough privileges could make the tag?)
| [
"Graph-tool now includes a function to add a list of edges to the graph. You can now do, for instance:\nimport graph_tool as gt\nimport numpy as np\ng = gt.Graph(directed=False)\nadj = np.random.randint(0, 2, (100, 100))\ng.add_edge_list(np.transpose(adj.nonzero()))\n\n",
"this is the extension of Tiago's answer for the weighted graph:\nadj = numpy.random.randint(0, 10, (100, 100)) # a random directed graph\nidx = adj.nonzero()\nweights = adj[idx]\ng = Graph()\ng.add_edge_list(transpose(idx)))\n\n#add weights as an edge propetyMap\new = g.new_edge_property(\"double\")\new.a = weights \ng.ep['edge_weight'] = ew\n\n",
"This should be a comment to Tiago's answer, but I don't have enough reputation for that.\nFor the latest version (2.26) of graph_tool I believe there is a missing transpose there. The i,j entry of the adjacency matrix denotes the weight of the edge going from vertex j to vertex i, so it should be\ng.add_edge_list(transpose(transpose(adj).nonzero()))\n\n",
"import numpy as np\nimport graph_tool.all as gt\n\ng = gt.Graph(directed=False)\nadj = np.tril(adj)\ng.add_edge_list(np.transpose(adj.nonzero()))\n\nWithout np.tril the adjacency matrix will contain entries with 2s instead one 1s because every edge is counted twice. Things like gt.num_edges() will be incorrect too.\n"
] | [
13,
4,
2,
0
] | [] | [] | [
"graph",
"graph_tool",
"python"
] | stackoverflow_0023288661_graph_graph_tool_python.txt |
Q:
Append row to DataFrame in Pandas and putting it on bottom
I want to add a row to a multi-index dataframe and I want to group it in its outer index where the alphabetical order is important, i.e, I can't use df.sort_index().
Here is the problem.
Code:
import pandas as pd
import numpy as np
categories = {"A":["c", "b", "a"] , "B": ["a", "b", "c"], "C": ["a", "b", "d"] }
array = []
expected_fields = []
for key, value in categories.items():
array.extend([key]* len(value))
expected_fields.extend(value)
arrays = [array ,expected_fields]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.Series(np.random.randn(9), index=index)
df["A", "d"] = 2
print(df)
Output:
A c 0.887137
b -0.105262
a -0.180093
B a -0.687134
b -1.120895
c 2.398962
C a -2.226126
b -0.203238
d 0.036068
A d 2.000000 <------------
dtype: float64
Expected output:
A c 0.887137
b -0.105262
a -0.180093
d 2.000000 <--------------
B a -0.687134
b -1.120895
c 2.398962
C a -2.226126
b -0.203238
d 0.036068
dtype: float64
A:
df.loc[['A', 'B', 'C']]
output:
A c 0.887137
b -0.105262
a -0.180093
d 2.000000
B a -0.687134
b -1.120895
c 2.398962
C a -2.226126
b -0.203238
d 0.036068
dtype: float64
if you want get ['A', 'B', 'C'] by code, use following
idx0 = df.index.get_level_values(0).unique()
df.loc[idx0]
same result
| Append row to DataFrame in Pandas and putting it on bottom | I want to add a row to a multi-index dataframe and I want to group it in its outer index where the alphabetical order is important, i.e, I can't use df.sort_index().
Here is the problem.
Code:
import pandas as pd
import numpy as np
categories = {"A":["c", "b", "a"] , "B": ["a", "b", "c"], "C": ["a", "b", "d"] }
array = []
expected_fields = []
for key, value in categories.items():
array.extend([key]* len(value))
expected_fields.extend(value)
arrays = [array ,expected_fields]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.Series(np.random.randn(9), index=index)
df["A", "d"] = 2
print(df)
Output:
A c 0.887137
b -0.105262
a -0.180093
B a -0.687134
b -1.120895
c 2.398962
C a -2.226126
b -0.203238
d 0.036068
A d 2.000000 <------------
dtype: float64
Expected output:
A c 0.887137
b -0.105262
a -0.180093
d 2.000000 <--------------
B a -0.687134
b -1.120895
c 2.398962
C a -2.226126
b -0.203238
d 0.036068
dtype: float64
| [
"df.loc[['A', 'B', 'C']]\n\noutput:\nA c 0.887137\n b -0.105262\n a -0.180093\n d 2.000000\nB a -0.687134\n b -1.120895\n c 2.398962\nC a -2.226126\n b -0.203238\n d 0.036068\ndtype: float64\n\nif you want get ['A', 'B', 'C'] by code, use following\nidx0 = df.index.get_level_values(0).unique()\ndf.loc[idx0]\n\nsame result\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074669264_dataframe_pandas_python_python_2.7_python_3.x.txt |
Q:
When I append a path, python gives an error
I tried to add a directory path to sys.path, but it gives me an error:
import sys
sys.path.append("C:\Users\tamer\Desktop\code\python\modules")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
A:
This should do it:
sys.path.append("C:\\Users\\tamer\\Desktop\\code\\python\\modules")
A:
Another approach is to use raw string, basically r is prefixed.
For this use case it should be.
sys.path.append(r"C:\Users\tamer\Desktop\code\python\modules")
| When I append a path, python gives an error | I tried to add a directory path to sys.path, but it gives me an error:
import sys
sys.path.append("C:\Users\tamer\Desktop\code\python\modules")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
| [
"This should do it:\nsys.path.append(\"C:\\\\Users\\\\tamer\\\\Desktop\\\\code\\\\python\\\\modules\")\n",
"Another approach is to use raw string, basically r is prefixed.\nFor this use case it should be.\nsys.path.append(r\"C:\\Users\\tamer\\Desktop\\code\\python\\modules\")\n\n"
] | [
0,
0
] | [] | [] | [
"python",
"sys",
"sys.path",
"windows"
] | stackoverflow_0074667805_python_sys_sys.path_windows.txt |
Q:
Stable Diffusion (Wheel 'torch' located at ___ is invalid.)
I have been attempting to install stable diffusion and have run into this error that I have no idea how to fix. When attempting to run the webui-user i receive this message
venv "C:\Users\___\Desktop\AI\stable-diffusion-webui\venv\Scripts\Python.exe"
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)]
Commit hash: ce049c471b4a1d22f5a8fe8f527788edcf934eda
Installing torch and torchvision
Traceback (most recent call last):
File "C:\Users\___\Desktop\AI\stable-diffusion-webui\launch.py", line 293, in <module>
prepare_enviroment()
File "C:\Users\___\Desktop\AI\stable-diffusion-webui\launch.py", line 205, in prepare_enviroment
run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch")
File "C:\Users\___\Desktop\AI\stable-diffusion-webui\launch.py", line 49, in run
raise RuntimeError(message)
RuntimeError: Couldn't install torch.
Command: "C:\Users\___\Desktop\AI\stable-diffusion-webui\venv\Scripts\python.exe" -m pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113
Error code: 1
stdout: Looking in indexes: https://pypi.org/simple, https://download.pytorch.org/whl/cu113
Collecting torch==1.12.1+cu113
Downloading https://download.pytorch.org/whl/cu113/torch-1.12.1%2Bcu113-cp310-cp310-win_amd64.whl (2143.8 MB)
---- 0.2/2.1 GB 17.2 MB/s eta 0:01:51
stderr: ERROR: Wheel 'torch' located at C:\Users\___\AppData\Local\Temp\pip-unpack-qiio06a2\torch-1.12.1+cu113-cp310-cp310-win_amd64.whl is invalid.
I haven't really tried anything to fix this because I haven't seen many others being vocal with solutions with problem when attempting to install SD.
(I did notice it says amd in the file it says is invalid, and I personally own a nvidia gpu and amd cpu. If this file is for amd gpu users this may be the issue, but I am not sure)
[Also the method I followed was this "What I did so far was use chocolaty to install the dependencies of Python 3.10.6 and Git. Then utilized the "git clone" on the Automatic 1111 url. Downloaded my preferred weights ckpt file. Added them to the models folder. Then ran the webui-user and got the error seen in my post. I also had a pip error, but after running the update command I was prompted by the webui-user.bat it stopped having that error and left me with this wheel error. I followed a youtube video, but I pretty much followed the method that is shown on the Automatic 1111 website."]
| Stable Diffusion (Wheel 'torch' located at ___ is invalid.) | I have been attempting to install stable diffusion and have run into this error that I have no idea how to fix. When attempting to run the webui-user i receive this message
venv "C:\Users\___\Desktop\AI\stable-diffusion-webui\venv\Scripts\Python.exe"
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)]
Commit hash: ce049c471b4a1d22f5a8fe8f527788edcf934eda
Installing torch and torchvision
Traceback (most recent call last):
File "C:\Users\___\Desktop\AI\stable-diffusion-webui\launch.py", line 293, in <module>
prepare_enviroment()
File "C:\Users\___\Desktop\AI\stable-diffusion-webui\launch.py", line 205, in prepare_enviroment
run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch")
File "C:\Users\___\Desktop\AI\stable-diffusion-webui\launch.py", line 49, in run
raise RuntimeError(message)
RuntimeError: Couldn't install torch.
Command: "C:\Users\___\Desktop\AI\stable-diffusion-webui\venv\Scripts\python.exe" -m pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113
Error code: 1
stdout: Looking in indexes: https://pypi.org/simple, https://download.pytorch.org/whl/cu113
Collecting torch==1.12.1+cu113
Downloading https://download.pytorch.org/whl/cu113/torch-1.12.1%2Bcu113-cp310-cp310-win_amd64.whl (2143.8 MB)
---- 0.2/2.1 GB 17.2 MB/s eta 0:01:51
stderr: ERROR: Wheel 'torch' located at C:\Users\___\AppData\Local\Temp\pip-unpack-qiio06a2\torch-1.12.1+cu113-cp310-cp310-win_amd64.whl is invalid.
I haven't really tried anything to fix this because I haven't seen many others being vocal with solutions with problem when attempting to install SD.
(I did notice it says amd in the file it says is invalid, and I personally own a nvidia gpu and amd cpu. If this file is for amd gpu users this may be the issue, but I am not sure)
[Also the method I followed was this "What I did so far was use chocolaty to install the dependencies of Python 3.10.6 and Git. Then utilized the "git clone" on the Automatic 1111 url. Downloaded my preferred weights ckpt file. Added them to the models folder. Then ran the webui-user and got the error seen in my post. I also had a pip error, but after running the update command I was prompted by the webui-user.bat it stopped having that error and left me with this wheel error. I followed a youtube video, but I pretty much followed the method that is shown on the Automatic 1111 website."]
| [] | [] | [
"Automatic1111 is easier to install from scratch and has a nice user interface.\nYou'll have to provide the instructions you're following for us to help troubleshoot your particular method.\n"
] | [
-1
] | [
"python",
"stable_diffusion"
] | stackoverflow_0074665626_python_stable_diffusion.txt |
Q:
how to call a dictionary key that is inside another dict
Have a little problem with a simple function that need solving
would like to be able to edit a dict with the update() but the problem is that I want to update it using its value and not its key
here is my code:
contacts = {"Mohamed": {"name": "Mohamed Sayed", "number": "0123565665", "birthday": "24.11.1990", "address": "Ginnheim 60487"},
"Ahmed": {"name": "Ahmed Sayed", "number": "0123456789", "birthday": "06.06.1990", "address": "India"}}
def edit_contact():
user_input = input("Please enter the name of the contact you want to edit: ")
for k in contacts:
if user_input == contacts["Mohamed"]["name"]:
print(contacts)
A:
If they enter the first name, then the sub-dictionary is simply contacts[name]. You don't need to loop over the whole contacts dictionary.
def edit_contact():
name = input("Please enter the first name of the contact you want to edit: ")
if name in contacts:
print(contacts[name])
else:
print("I could not find that contact")
| how to call a dictionary key that is inside another dict | Have a little problem with a simple function that need solving
would like to be able to edit a dict with the update() but the problem is that I want to update it using its value and not its key
here is my code:
contacts = {"Mohamed": {"name": "Mohamed Sayed", "number": "0123565665", "birthday": "24.11.1990", "address": "Ginnheim 60487"},
"Ahmed": {"name": "Ahmed Sayed", "number": "0123456789", "birthday": "06.06.1990", "address": "India"}}
def edit_contact():
user_input = input("Please enter the name of the contact you want to edit: ")
for k in contacts:
if user_input == contacts["Mohamed"]["name"]:
print(contacts)
| [
"If they enter the first name, then the sub-dictionary is simply contacts[name]. You don't need to loop over the whole contacts dictionary.\ndef edit_contact():\n name = input(\"Please enter the first name of the contact you want to edit: \")\n if name in contacts:\n print(contacts[name])\n else:\n print(\"I could not find that contact\")\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074669223_dictionary_list_python.txt |
Q:
Postponing the release of an element from resource when the next queue is full
I used some inputs that I got from this forum and got quite far while using simpy for the first time in my life for university. Now my question remains:
I can see that the customer/entity goes through process0 and the process1_broker but gets stuck right after entering process1. It never comes out. What am I doing wrong? I followed the code from an earlier answer directly, where only 1 queue is in place (see the comment section for this).
class Entity(object):
pass
def process0(env, entity, process_0_res, process_1_q):
print(f' {env.now} customer {entity.id} is in system')
with process_0_res.request() as res_req:
yield res_req
yield env.timeout(0.5)
print(f'{env.now} customer {entity.id} is in queue 1')
yield process_1_q.put(entity)
def process1_broker(env, process_1_q, process_1_res):
while True:
# is resource available?
res_req = process_1_res.request()
yield res_req
# is customer available?
entity = yield process_1_q.get()
# save resource request to release later
entity.res_req = res_req
# start process
env.process(process1(env,entity,process_1_res, process_2_q))
def process1(env, entity, process_1_res, process_2_q):
print(f' {env.now} customer {entity.id} in process 1')
with process_1_res.request() as res_req:
yield res_req
yield env.timeout(2)
print(f' {env.now} customer {entity.id} done with process 1')
yield process_2_q.put(entity)
def process2_broker(env, process_2_q, process_2_res):
while True:
res_req = process_2_res.request()
yield res_req
entity = yield process_2_q.get()
entity.res_req = res_req
env.process(process2(env,entity,process_2_res, process_3_q))
def process2(env, entity, process_2_res, process_3_q):
print(f' {env.now} customer {entity.id} in process 2')
with process_2_res.request() as res_req:
yield res_req
yield env.timeout(np.random.exponential(mu[1]))
yield process_3_q.put(entity)
def process3_broker(env, process_3_q, process_3_res):
while True:
res_req = process_3_res.request()
yield res_req
entity = yield process_3_q.get()
entity.res_req = res_req
env.process(process3(env,entity,process_3_res, process_4_q))
def process3(env, entity, process_3_res, process_4_q):
print(f' {env.now} customer {entity.id} in process 3')
with process_3_res.request() as res_req:
yield res_req
yield env.timeout(np.random.exponential(mu[2]))
yield process_4_q.put(entity)
def process4_broker(env, process_4_q, process_4_res):
while True:
res_req = process_4_res.request()
yield res_req
entity = yield process_3_q.get()
entity.res_req = res_req
env.process(process4(env,entity,process_4_res))
def process4(env, entity, process_4_res, process_4_q):
print(f' {env.now} customer {entity.id} in process 4')
with process_4_res.request() as res_req:
yield res_req
yield env.timeout(np.random.exponential(mu[3]))
yield process_4_res.release(entity.res_req)
print(f' {env.now} customer {entity.id} leaves system')
def gen_entities(env, process_0_res, process_1_q):
next_id = 1
while True:
yield env.timeout(np.random.exponential(labda))
entity = Entity()
entity.id = next_id
next_id += 1
env.process(process0(env, entity, process_0_res, process_1_q))
env = simpy.Environment()
process_0_res = simpy.Resource(env, capacity = 1)
process_1_res = simpy.Resource(env, capacity = 1)
process_2_res = simpy.Resource(env, capacity = 1)
process_3_res = simpy.Resource(env, capacity = 1)
process_4_res = simpy.Resource(env, capacity = 1)
process_1_q = simpy.Store(env, capacity = 5)
process_2_q = simpy.Store(env, capacity = 4)
process_3_q = simpy.Store(env, capacity = 3)
process_4_q = simpy.Store(env, capacity = 2)
env.process(gen_entities(env, process_0_res, process_1_q))
env.process(process1_broker(env, process_1_q, process_1_res))
env.process(process2_broker(env, process_2_q, process_2_res))
env.process(process3_broker(env, process_3_q, process_3_res))
env.process(process4_broker(env, process_4_q, process_4_res))
env.run(100)
A:
I used a store with a capacity to act as a blocking queue
Process 1 will not release its process 1 resource until the entity can be put into the store. If the store is at capacity, it will block the put until process 2 pulls a entity from the store.
To manage the store, I have a broker process that matches entities in the store with process 2 resources. When a match is made process 2 starts.
"""
Demostrates one way to do a blocking queue
where a queue has a size limit and will
'block' arrivals whe the queue is at that limit
sim two processes were the first process has a unlimited queue
and second process with a limited blocking queue.
A entity will not releases its resource from the first process
until it can advance to the second process's queue
Uses a simpy store to queue entities for process 2
and a broker process to match entities from the store
with process 2 resources then starts process 2 when match is made
Programmer: Michael R. Gibbs
"""
import simpy
import random
class Entity(object):
"""
Quick class to track entities
dynamicly will add id, and resouce request
"""
pass
def process1(env, entity, process_1_res, process_2_q):
"""
First process with a unlimited queue
"""
print(f'{env.now} entity {entity.id} has arrived in process 1')
with process_1_res.request() as res_req:
print(f'{env.now} process 1 queue size {len(process_1_res.queue)}')
yield res_req
print(f'{env.now} entity {entity.id} has seized a process 1 resource')
yield env.timeout(random.uniform(1,5))
print(f'{env.now} entity {entity.id} has finished process 1')
# this put will block if the store is at compacity
yield process_2_q.put(entity)
print(f'{env.now} entity {entity.id} has advance to process 2 queue')
print(f'{env.now} process 1 queue size {len(process_1_res.queue)}')
def process2_broker(env, process_2_q, process_2_res):
"""
When a resouce for process 2 is available, will pull
and entity from the store beign uses at the process 2's
blocking queue
"""
while True:
print(f'{env.now} process 2 queue size {len(process_2_q.items)}')
# wait for a resouce to become avaliable
res_req = process_2_res.request()
yield res_req
# wait for a entity to be avaliable
entity = yield process_2_q.get()
# save the resouce request so we can release it later
entity.res_req = res_req
# start process 2, no yield here, start the next match imediatly
env.process(process2(env, entity, process_2_res))
def process2(env, entity, process_2_res):
"""
Process 2 where a entiy has already been matched with
a resouce in the broker
"""
print(f'{env.now} entity {entity.id} has started process 2')
yield env.timeout(random.uniform(1,10))
print(f'{env.now} entity {entity.id} has finished process 2')
# the resouce request was saved in the broker so it could be released now
process_2_res.release(entity.res_req)
def gen_entities(env, process_1_res, process_2_q):
"""
Generates a stream of entities to be processed
starting with process 1
"""
next_id = 1
while True:
yield env.timeout(random.uniform(1,3))
entity = Entity()
entity.id = next_id
next_id += 1
env.process(process1(env, entity, process_1_res, process_2_q))
# boot up
env = env = simpy.Environment()
# resouces for processes
process_1_res = simpy.Resource(env, capacity=3)
process_2_res = simpy.Resource(env, capacity=2)
# used as blocking queue for process 2
process_2_q = simpy.Store(env,capacity=5)
env.process(gen_entities(env, process_1_res, process_2_q))
env.process(process2_broker(env, process_2_q, process_2_res))
env.run(100)
| Postponing the release of an element from resource when the next queue is full | I used some inputs that I got from this forum and got quite far while using simpy for the first time in my life for university. Now my question remains:
I can see that the customer/entity goes through process0 and the process1_broker but gets stuck right after entering process1. It never comes out. What am I doing wrong? I followed the code from an earlier answer directly, where only 1 queue is in place (see the comment section for this).
class Entity(object):
pass
def process0(env, entity, process_0_res, process_1_q):
print(f' {env.now} customer {entity.id} is in system')
with process_0_res.request() as res_req:
yield res_req
yield env.timeout(0.5)
print(f'{env.now} customer {entity.id} is in queue 1')
yield process_1_q.put(entity)
def process1_broker(env, process_1_q, process_1_res):
while True:
# is resource available?
res_req = process_1_res.request()
yield res_req
# is customer available?
entity = yield process_1_q.get()
# save resource request to release later
entity.res_req = res_req
# start process
env.process(process1(env,entity,process_1_res, process_2_q))
def process1(env, entity, process_1_res, process_2_q):
print(f' {env.now} customer {entity.id} in process 1')
with process_1_res.request() as res_req:
yield res_req
yield env.timeout(2)
print(f' {env.now} customer {entity.id} done with process 1')
yield process_2_q.put(entity)
def process2_broker(env, process_2_q, process_2_res):
while True:
res_req = process_2_res.request()
yield res_req
entity = yield process_2_q.get()
entity.res_req = res_req
env.process(process2(env,entity,process_2_res, process_3_q))
def process2(env, entity, process_2_res, process_3_q):
print(f' {env.now} customer {entity.id} in process 2')
with process_2_res.request() as res_req:
yield res_req
yield env.timeout(np.random.exponential(mu[1]))
yield process_3_q.put(entity)
def process3_broker(env, process_3_q, process_3_res):
while True:
res_req = process_3_res.request()
yield res_req
entity = yield process_3_q.get()
entity.res_req = res_req
env.process(process3(env,entity,process_3_res, process_4_q))
def process3(env, entity, process_3_res, process_4_q):
print(f' {env.now} customer {entity.id} in process 3')
with process_3_res.request() as res_req:
yield res_req
yield env.timeout(np.random.exponential(mu[2]))
yield process_4_q.put(entity)
def process4_broker(env, process_4_q, process_4_res):
while True:
res_req = process_4_res.request()
yield res_req
entity = yield process_3_q.get()
entity.res_req = res_req
env.process(process4(env,entity,process_4_res))
def process4(env, entity, process_4_res, process_4_q):
print(f' {env.now} customer {entity.id} in process 4')
with process_4_res.request() as res_req:
yield res_req
yield env.timeout(np.random.exponential(mu[3]))
yield process_4_res.release(entity.res_req)
print(f' {env.now} customer {entity.id} leaves system')
def gen_entities(env, process_0_res, process_1_q):
next_id = 1
while True:
yield env.timeout(np.random.exponential(labda))
entity = Entity()
entity.id = next_id
next_id += 1
env.process(process0(env, entity, process_0_res, process_1_q))
env = simpy.Environment()
process_0_res = simpy.Resource(env, capacity = 1)
process_1_res = simpy.Resource(env, capacity = 1)
process_2_res = simpy.Resource(env, capacity = 1)
process_3_res = simpy.Resource(env, capacity = 1)
process_4_res = simpy.Resource(env, capacity = 1)
process_1_q = simpy.Store(env, capacity = 5)
process_2_q = simpy.Store(env, capacity = 4)
process_3_q = simpy.Store(env, capacity = 3)
process_4_q = simpy.Store(env, capacity = 2)
env.process(gen_entities(env, process_0_res, process_1_q))
env.process(process1_broker(env, process_1_q, process_1_res))
env.process(process2_broker(env, process_2_q, process_2_res))
env.process(process3_broker(env, process_3_q, process_3_res))
env.process(process4_broker(env, process_4_q, process_4_res))
env.run(100)
| [
"I used a store with a capacity to act as a blocking queue\nProcess 1 will not release its process 1 resource until the entity can be put into the store. If the store is at capacity, it will block the put until process 2 pulls a entity from the store.\nTo manage the store, I have a broker process that matches entities in the store with process 2 resources. When a match is made process 2 starts.\n\"\"\"\nDemostrates one way to do a blocking queue\nwhere a queue has a size limit and will\n'block' arrivals whe the queue is at that limit\n\nsim two processes were the first process has a unlimited queue\nand second process with a limited blocking queue.\n\nA entity will not releases its resource from the first process\nuntil it can advance to the second process's queue\n\nUses a simpy store to queue entities for process 2\nand a broker process to match entities from the store\nwith process 2 resources then starts process 2 when match is made\n\nProgrammer: Michael R. Gibbs\n\"\"\"\n\nimport simpy\nimport random\n\nclass Entity(object):\n \"\"\"\n Quick class to track entities\n dynamicly will add id, and resouce request\n \"\"\"\n pass\n\ndef process1(env, entity, process_1_res, process_2_q):\n \"\"\"\n First process with a unlimited queue\n \"\"\"\n print(f'{env.now} entity {entity.id} has arrived in process 1')\n\n with process_1_res.request() as res_req:\n print(f'{env.now} process 1 queue size {len(process_1_res.queue)}')\n \n yield res_req\n print(f'{env.now} entity {entity.id} has seized a process 1 resource')\n\n yield env.timeout(random.uniform(1,5))\n print(f'{env.now} entity {entity.id} has finished process 1')\n\n # this put will block if the store is at compacity\n yield process_2_q.put(entity)\n print(f'{env.now} entity {entity.id} has advance to process 2 queue')\n \n print(f'{env.now} process 1 queue size {len(process_1_res.queue)}')\n\ndef process2_broker(env, process_2_q, process_2_res):\n \"\"\"\n When a resouce for process 2 is available, will pull\n and entity from the store beign uses at the process 2's\n blocking queue\n \"\"\"\n\n while True:\n print(f'{env.now} process 2 queue size {len(process_2_q.items)}')\n\n # wait for a resouce to become avaliable\n res_req = process_2_res.request()\n yield res_req\n\n # wait for a entity to be avaliable\n entity = yield process_2_q.get() \n\n # save the resouce request so we can release it later\n entity.res_req = res_req \n\n # start process 2, no yield here, start the next match imediatly\n env.process(process2(env, entity, process_2_res))\n\ndef process2(env, entity, process_2_res):\n \"\"\"\n Process 2 where a entiy has already been matched with\n a resouce in the broker\n \"\"\"\n\n print(f'{env.now} entity {entity.id} has started process 2')\n\n yield env.timeout(random.uniform(1,10))\n\n print(f'{env.now} entity {entity.id} has finished process 2')\n\n # the resouce request was saved in the broker so it could be released now\n process_2_res.release(entity.res_req)\n\ndef gen_entities(env, process_1_res, process_2_q):\n \"\"\"\n Generates a stream of entities to be processed\n starting with process 1\n \"\"\"\n\n next_id = 1\n\n while True:\n yield env.timeout(random.uniform(1,3))\n\n entity = Entity()\n entity.id = next_id\n next_id += 1\n\n env.process(process1(env, entity, process_1_res, process_2_q))\n\n# boot up\nenv = env = simpy.Environment()\n\n# resouces for processes\nprocess_1_res = simpy.Resource(env, capacity=3)\nprocess_2_res = simpy.Resource(env, capacity=2)\n\n# used as blocking queue for process 2\nprocess_2_q = simpy.Store(env,capacity=5)\n\nenv.process(gen_entities(env, process_1_res, process_2_q))\nenv.process(process2_broker(env, process_2_q, process_2_res))\n\nenv.run(100)\n\n"
] | [
0
] | [] | [] | [
"python",
"simpy",
"while_loop"
] | stackoverflow_0074667274_python_simpy_while_loop.txt |
Q:
Split Pandas dataframe by a specific custom parameter
I have a sample pandas dataframe as below:
What I want to do is to write a function to split this dataframe by its time value. The function returns a list of dataframes.
I used the below function to split the dataframe.
def split_dataframe(df, chunk_size=20):
chunks = list()
num_chunks = len(df) // chunk_size + 1
for i in range(num_chunks):
chunks.append(df[i*chunk_size:(i+1)*chunk_size])
return chunks
However, this function splits the dataframe by its number of rows equally. In this case, it's 20 by default. What I want to achieve is to get dataframe every 3 seconds (or x seconds). For instance, get the first dataframe where we have rows in 300 and 303 seconds, then the next dataframe will be in 304 to 307 seconds, and so on. I am not sure how to accomplish this.
What I have done is create a new column that displays yes or no if the time is in the 3 seconds. But that did not help much.
Also, please note that I might have multiple ids, and time is always increasing. It could also be the same. Normally, time values are very precise and include decimals. I just cast those to int. So, in this case, the dataframes might not be the same size.
I would appreciate it if you could help me with that.
A:
With the following toy dataframe:
import pandas as pd
df = pd.DataFrame(
{
"id": [1, 1, 1, 2, 2, 3, 4, 4, 5, 5],
"sample_val": [10, 11, 10, 12, 22, 22, 23, 23, 24, 24],
"time": [300, 301, 301, 302, 302, 304, 311, 308, 309, 305],
}
)
Here is one way to do it:
N = 3
df = df.sort_values(by="time")
intervals = [[i, i + N] for i in range(df["time"].min(), df["time"].max(), N + 1)]
# [[300, 303], [304, 307], [308, 311]]
# Find rows that belong to the same interval
chunks = df.apply(
lambda x: [interval[0] <= x["time"] <= interval[1] for interval in intervals].index(
True
),
axis=1,
)
# Split df accordingly
dfs = [df_.reset_index(drop=True) for _, df_ in df.groupby(chunks)]
Then:
print(dfs[0])
# Output
id sample_val time
0 1 10 300
1 1 11 301
2 1 10 301
3 2 12 302
4 2 22 302
print(dfs[1])
# Output
id sample_val time
0 3 22 304
1 5 24 305
print(dfs[2])
# Output
id sample_val time
0 4 23 308
1 5 24 309
2 4 23 311
| Split Pandas dataframe by a specific custom parameter | I have a sample pandas dataframe as below:
What I want to do is to write a function to split this dataframe by its time value. The function returns a list of dataframes.
I used the below function to split the dataframe.
def split_dataframe(df, chunk_size=20):
chunks = list()
num_chunks = len(df) // chunk_size + 1
for i in range(num_chunks):
chunks.append(df[i*chunk_size:(i+1)*chunk_size])
return chunks
However, this function splits the dataframe by its number of rows equally. In this case, it's 20 by default. What I want to achieve is to get dataframe every 3 seconds (or x seconds). For instance, get the first dataframe where we have rows in 300 and 303 seconds, then the next dataframe will be in 304 to 307 seconds, and so on. I am not sure how to accomplish this.
What I have done is create a new column that displays yes or no if the time is in the 3 seconds. But that did not help much.
Also, please note that I might have multiple ids, and time is always increasing. It could also be the same. Normally, time values are very precise and include decimals. I just cast those to int. So, in this case, the dataframes might not be the same size.
I would appreciate it if you could help me with that.
| [
"With the following toy dataframe:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"id\": [1, 1, 1, 2, 2, 3, 4, 4, 5, 5],\n \"sample_val\": [10, 11, 10, 12, 22, 22, 23, 23, 24, 24],\n \"time\": [300, 301, 301, 302, 302, 304, 311, 308, 309, 305],\n }\n)\n\nHere is one way to do it:\nN = 3\n\ndf = df.sort_values(by=\"time\")\n\nintervals = [[i, i + N] for i in range(df[\"time\"].min(), df[\"time\"].max(), N + 1)]\n# [[300, 303], [304, 307], [308, 311]]\n\n# Find rows that belong to the same interval\nchunks = df.apply(\n lambda x: [interval[0] <= x[\"time\"] <= interval[1] for interval in intervals].index(\n True\n ),\n axis=1,\n)\n\n# Split df accordingly\ndfs = [df_.reset_index(drop=True) for _, df_ in df.groupby(chunks)]\n\nThen:\nprint(dfs[0])\n# Output\n id sample_val time\n0 1 10 300\n1 1 11 301\n2 1 10 301\n3 2 12 302\n4 2 22 302\n\nprint(dfs[1])\n# Output\n id sample_val time\n0 3 22 304\n1 5 24 305\n\nprint(dfs[2])\n# Output\n id sample_val time\n0 4 23 308\n1 5 24 309\n2 4 23 311\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074631375_dataframe_pandas_python.txt |
Q:
Splitting string, ignoring brackets including nested brackets
I would like to split a string at spaces (and colons), except inside curly brackets and rounded brackets. Similar questions have been asked, but the answers fail with nested brackets.
Here is an example of a string to split:
p1: I/out p2: (('mean', 5), 0.0, ('std', 2)) p3: 7 p4: {'name': 'check', 'value': 80.0}
The actual goal is to obtain a list of keys (p1, p2, p3 and p4) along with their values. When I try to split the string at spaces and colons, I can avoid splitting at spaces and colons inside the curly brackets. But I cannot avoid the splitting at some spaces inside the rounded brackets because of the nested brackets.
The closest I got is
[\s:]+(?=[^\{\(\)\}]*(?:[\{\(]|$))
which is fine except that it splits between (('mean', 5), and 0.0.
A:
You can use the following PCRE/Python PyPi regex compliant pattern:
(?:(\((?:[^()]++|(?1))*\))|(\{(?:[^{}]++|(?2))*})|[^\s:])+
See the regex demo.
It matches
(?: - start of a container non-capturing group:
(\((?:[^()]++|(?1))*\)) - Group 1: a substring between two nested round brackets
| - or
(\{(?:[^{}]++|(?2))*}) - Group 2: a substring between two nested braces
| - or
[^\s:] - a char other than whitespace and colon
)+ - one or more occurrences.
See the Python demo:
import regex
text = "p1: I/out p2: (('mean', 5), 0.0, ('std', 2)) p3: 7 p4: {'name': 'check', 'value': 80.0}"
pattern = r"(?:(\((?:[^()]++|(?1))*\))|(\{(?:[^{}]++|(?2))*})|[^\s:])+"
print( [x.group() for x in regex.finditer(pattern, text)] )
Output:
['p1', 'I/out', 'p2', "(('mean', 5), 0.0, ('std', 2))", 'p3', '7', 'p4', "{'name': 'check', 'value': 80.0}"]
| Splitting string, ignoring brackets including nested brackets | I would like to split a string at spaces (and colons), except inside curly brackets and rounded brackets. Similar questions have been asked, but the answers fail with nested brackets.
Here is an example of a string to split:
p1: I/out p2: (('mean', 5), 0.0, ('std', 2)) p3: 7 p4: {'name': 'check', 'value': 80.0}
The actual goal is to obtain a list of keys (p1, p2, p3 and p4) along with their values. When I try to split the string at spaces and colons, I can avoid splitting at spaces and colons inside the curly brackets. But I cannot avoid the splitting at some spaces inside the rounded brackets because of the nested brackets.
The closest I got is
[\s:]+(?=[^\{\(\)\}]*(?:[\{\(]|$))
which is fine except that it splits between (('mean', 5), and 0.0.
| [
"You can use the following PCRE/Python PyPi regex compliant pattern:\n(?:(\\((?:[^()]++|(?1))*\\))|(\\{(?:[^{}]++|(?2))*})|[^\\s:])+\n\nSee the regex demo.\nIt matches\n\n(?: - start of a container non-capturing group:\n\n(\\((?:[^()]++|(?1))*\\)) - Group 1: a substring between two nested round brackets\n| - or\n(\\{(?:[^{}]++|(?2))*}) - Group 2: a substring between two nested braces\n| - or\n[^\\s:] - a char other than whitespace and colon\n\n\n)+ - one or more occurrences.\n\nSee the Python demo:\nimport regex\ntext = \"p1: I/out p2: (('mean', 5), 0.0, ('std', 2)) p3: 7 p4: {'name': 'check', 'value': 80.0}\"\npattern = r\"(?:(\\((?:[^()]++|(?1))*\\))|(\\{(?:[^{}]++|(?2))*})|[^\\s:])+\"\nprint( [x.group() for x in regex.finditer(pattern, text)] )\n\nOutput:\n['p1', 'I/out', 'p2', \"(('mean', 5), 0.0, ('std', 2))\", 'p3', '7', 'p4', \"{'name': 'check', 'value': 80.0}\"]\n\n"
] | [
3
] | [] | [] | [
"python",
"regex",
"split"
] | stackoverflow_0074668806_python_regex_split.txt |
Q:
Python modules I've just installed in my virtual env, are not found
I'm using Ubuntu 20.04.5 LTS. Output of python3 --version command: Python 3.8.10
When I type pip in terminal and press TAB, it responds with the following options: pip, pip3, pip3.10 and pip3.8
But, when I use any of then with the --version flag, it all prints the same output, which is: pip 22.3.1 from /home/myuser/.local/lib/python3.8/site-packages/pip (python 3.8)
When I use "pip list" command, I can see the "virtualenv" package version(which is 20.17.0)
Then I create my virtual environment using this following command: python3 -m venv .env
Then I activate it using source .env/bin/activate command
Before installing the modules, I update virtual environment's pip, using the following command:
.env/bin/python3 -m pip install --upgrade pip
Also, I have a file called requirements.txt with the packages names I need in it:
wheel
numpy
matplotlib
sklearn
seaborn
So I install them using the following command:
.env/bin/pip install -r requirements.txt --no-cache-dir --use-pep517
Finally, I try to run my python program using ".env/bin/python kmeans3.py" command, it prints this error:
Traceback (most recent call last):
File "kmeans3.py", line 10, in <module>
from sklearn.cluster import KMeans
ModuleNotFoundError: No module named 'sklearn'
obs: This is the first 12 lines of the file:
"""
.env/bin/python3 -m pip install --upgrade pip
.env/bin/pip install -r requirements.txt --no-cache-dir --use-pep517
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import MinMaxScaler
A:
Looks ok to me.
If your environment is activated try to just run
python kmeans3.py
or
python3 kmeans3.py
A:
I don't know why is that, but I solved this problem installing "scikit-learn" package before install "sklearn"
| Python modules I've just installed in my virtual env, are not found | I'm using Ubuntu 20.04.5 LTS. Output of python3 --version command: Python 3.8.10
When I type pip in terminal and press TAB, it responds with the following options: pip, pip3, pip3.10 and pip3.8
But, when I use any of then with the --version flag, it all prints the same output, which is: pip 22.3.1 from /home/myuser/.local/lib/python3.8/site-packages/pip (python 3.8)
When I use "pip list" command, I can see the "virtualenv" package version(which is 20.17.0)
Then I create my virtual environment using this following command: python3 -m venv .env
Then I activate it using source .env/bin/activate command
Before installing the modules, I update virtual environment's pip, using the following command:
.env/bin/python3 -m pip install --upgrade pip
Also, I have a file called requirements.txt with the packages names I need in it:
wheel
numpy
matplotlib
sklearn
seaborn
So I install them using the following command:
.env/bin/pip install -r requirements.txt --no-cache-dir --use-pep517
Finally, I try to run my python program using ".env/bin/python kmeans3.py" command, it prints this error:
Traceback (most recent call last):
File "kmeans3.py", line 10, in <module>
from sklearn.cluster import KMeans
ModuleNotFoundError: No module named 'sklearn'
obs: This is the first 12 lines of the file:
"""
.env/bin/python3 -m pip install --upgrade pip
.env/bin/pip install -r requirements.txt --no-cache-dir --use-pep517
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import MinMaxScaler
| [
"Looks ok to me.\nIf your environment is activated try to just run\npython kmeans3.py\n\nor\npython3 kmeans3.py\n\n",
"I don't know why is that, but I solved this problem installing \"scikit-learn\" package before install \"sklearn\"\n"
] | [
0,
0
] | [] | [] | [
"pip",
"python",
"python_3.x",
"scikit_learn",
"virtualenv"
] | stackoverflow_0074632110_pip_python_python_3.x_scikit_learn_virtualenv.txt |
Q:
pow large numbers in Python
How can I raise large numbers to a power in python?
a = 62608558862573792084872798679396455703616395237802859621162736207631538899993
b = 93910650126758265671774994856253142403789359314618444886584691522424141933664
c = pow(a, b)
It is impossible to get an answer that way. Are there any ways to raise large numbers to a power to make it work?
A:
If you calculate the result to all digits, it has 10^78 digits. That's more than will fit into any RAM of any computer in the world today.
It is impossible to get an answer that way.
It will be impossible to get a precise answer for a long time, given that Earth only has ~10^50 atoms.
The number 62608558862573792084872798679396455703616395237802859621162736207631538899993 looks like a pseudo prime number (is has only 5 prime factors) as used in cryptography. Cryptography often works with modulo operations to limit the number of digits. You can use pow to do modulo math as well:
pow(base, exp, mod=None)
Return base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod).
| pow large numbers in Python | How can I raise large numbers to a power in python?
a = 62608558862573792084872798679396455703616395237802859621162736207631538899993
b = 93910650126758265671774994856253142403789359314618444886584691522424141933664
c = pow(a, b)
It is impossible to get an answer that way. Are there any ways to raise large numbers to a power to make it work?
| [
"If you calculate the result to all digits, it has 10^78 digits. That's more than will fit into any RAM of any computer in the world today.\n\nIt is impossible to get an answer that way.\n\nIt will be impossible to get a precise answer for a long time, given that Earth only has ~10^50 atoms.\nThe number 62608558862573792084872798679396455703616395237802859621162736207631538899993 looks like a pseudo prime number (is has only 5 prime factors) as used in cryptography. Cryptography often works with modulo operations to limit the number of digits. You can use pow to do modulo math as well:\n\npow(base, exp, mod=None)\nReturn base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod).\n\n"
] | [
3
] | [] | [] | [
"largenumber",
"pow",
"python"
] | stackoverflow_0074669402_largenumber_pow_python.txt |
Q:
User defined function through inputs in Python
I wish to create a custom calculator where the user defines two parameters and a function using a GUI and when they click on calculate it executes their user defined function passing the two parameters.
argument1 = IntSlider( … )
argument2 = IntSlider( … )
userDefinedFunction = TextArea( … )
calculateButton = Button ( … )
calculateButton.on_click(userDefinedFunction)
So that let’s say somebody defines :
argument1 = 3
argument2 = 4
userDefinedFunction = def udf(arg1,arg2): return arg1**2 + arg2**2
Would return 25 as 3*3 + 4*4 = 25.
A:
I'd probably go with something more limiting than a full function definition. Having the user create the function signature is going to add complications as you cannot eval it, you would have to exec it instead. Then finding out the method name would be complex, and it would allow the user to overwrite local variables, or do other imports, which might not be desirable.
An easier way could be to expect the user to complete the lambda method lambda arg1, arg2: <user code input>.
Note that eval and exec (or running any unvalidated user input as code for that matter) are dangerous. If the user is running this on their local machine only this is somewhat okay, but do not do this if the inputs are coming from external sources, like for example, a web server.
argument1 = 3
argument2 = 4
user_func_input = "arg1**2 + arg2**2"
user_func = eval(f"lambda arg1, arg2: {user_func_input}")
print(user_func(argument1, argument2))
25
A:
Using eval or exec for user input data is dangerous. Any valid syntax will be evaluated by the interpreter. The secure way is to verify if the operation is valid and then execute it.
There are plenty of algorithms to distinguish numbers from operators (search for infix notation).
To safely execute the operations, you could use the following functions
# For python 3.10 and above (with support for match statement)
def apply_function(argument1:int, argument2:int, function:str)->float:
match function:
case "add" | "sum"| "+":
return argument1 + argument2
case "sub" | "subtract" | "-":
return argument1 - argument2
case "mul" | "multiply" | "*" | "x" | "times":
return argument1 * argument2
case "div" | "divide" | "/":
return argument1 / argument2
case "pow" | "power" | "^"|"**":
return argument1 ** argument2
case _:
raise ValueError("Invalid function")
# For python 3.9 and below (without support for match statement)
def apply_function_v2(argument1:int, argument2:int, function:str)->float:
if function in ("add", "sum", "+"):
return argument1 + argument2
elif function in ("sub", "subtract", "-"):
return argument1 - argument2
elif function in ("mul", "multiply", "*", "x", "times"):
return argument1 * argument2
elif function in ("div", "divide", "/"):
return argument1 / argument2
elif function in ("pow", "power", "^", "**"):
return argument1 ** argument2
else:
raise ValueError("Invalid function")
| User defined function through inputs in Python | I wish to create a custom calculator where the user defines two parameters and a function using a GUI and when they click on calculate it executes their user defined function passing the two parameters.
argument1 = IntSlider( … )
argument2 = IntSlider( … )
userDefinedFunction = TextArea( … )
calculateButton = Button ( … )
calculateButton.on_click(userDefinedFunction)
So that let’s say somebody defines :
argument1 = 3
argument2 = 4
userDefinedFunction = def udf(arg1,arg2): return arg1**2 + arg2**2
Would return 25 as 3*3 + 4*4 = 25.
| [
"I'd probably go with something more limiting than a full function definition. Having the user create the function signature is going to add complications as you cannot eval it, you would have to exec it instead. Then finding out the method name would be complex, and it would allow the user to overwrite local variables, or do other imports, which might not be desirable.\nAn easier way could be to expect the user to complete the lambda method lambda arg1, arg2: <user code input>.\nNote that eval and exec (or running any unvalidated user input as code for that matter) are dangerous. If the user is running this on their local machine only this is somewhat okay, but do not do this if the inputs are coming from external sources, like for example, a web server.\nargument1 = 3\nargument2 = 4\nuser_func_input = \"arg1**2 + arg2**2\"\nuser_func = eval(f\"lambda arg1, arg2: {user_func_input}\")\n\nprint(user_func(argument1, argument2))\n\n25\n\n",
"Using eval or exec for user input data is dangerous. Any valid syntax will be evaluated by the interpreter. The secure way is to verify if the operation is valid and then execute it.\nThere are plenty of algorithms to distinguish numbers from operators (search for infix notation).\nTo safely execute the operations, you could use the following functions\n# For python 3.10 and above (with support for match statement)\ndef apply_function(argument1:int, argument2:int, function:str)->float:\n match function:\n case \"add\" | \"sum\"| \"+\":\n return argument1 + argument2\n case \"sub\" | \"subtract\" | \"-\":\n return argument1 - argument2\n case \"mul\" | \"multiply\" | \"*\" | \"x\" | \"times\":\n return argument1 * argument2\n case \"div\" | \"divide\" | \"/\":\n return argument1 / argument2\n case \"pow\" | \"power\" | \"^\"|\"**\":\n return argument1 ** argument2\n case _:\n raise ValueError(\"Invalid function\")\n\n# For python 3.9 and below (without support for match statement)\ndef apply_function_v2(argument1:int, argument2:int, function:str)->float:\n if function in (\"add\", \"sum\", \"+\"):\n return argument1 + argument2\n elif function in (\"sub\", \"subtract\", \"-\"):\n return argument1 - argument2\n elif function in (\"mul\", \"multiply\", \"*\", \"x\", \"times\"):\n return argument1 * argument2\n elif function in (\"div\", \"divide\", \"/\"):\n return argument1 / argument2\n elif function in (\"pow\", \"power\", \"^\", \"**\"):\n return argument1 ** argument2\n else:\n raise ValueError(\"Invalid function\")\n\n"
] | [
1,
1
] | [] | [] | [
"ipywidgets",
"panel_pyviz",
"python"
] | stackoverflow_0074668885_ipywidgets_panel_pyviz_python.txt |
Q:
Python function about chemical formulas
I have a CSV file that contains chemical matter names and some info.What I need to do is add new columns and write their formulas, molecular weights and count H,C,N,O,S atom numbers in each formula.I am stuck with the counting atom numbers part.I have the function related it but I don't know how to merge it and make code work.
import pandas as pd
import urllib.request
import copy
import re
df = pd.read_csv('AminoAcids.csv')
def countAtoms(string, dict={}):
curDict = copy.copy(dict)
atoms = re.findall("[A-Z]{1}[a-z]*[0-9]*", string)
for j in atoms:
atomGroups = re.match('([A-Z]{1}[a-z]*)([0-9]*)', j)
atom = atomGroups.group(1)
number = atomGroups.group(2)
try :
curDict[atom] = curDict[atom] + int(number)
except KeyError:
try :
curDict[atom] = int(number)
except ValueError:
curDict[atom] = 1
except ValueError:
curDict[atom] = curDict[atom] + 1
return curDict
df["Formula"] = ['C3H7NO2', 'C6H14N4O2 ','C4H8N2O3','C4H7NO4 ',
'C3H7NO2S ','C5H9NO4','C5H10N2O3','C2H5NO2 ','C6H9N3O2',
'C6H13NO2','C6H13NO2','C6H14N2O2 ','C5H11NO2S ','C9H11NO2',
'C5H9NO2 ','C3H7NO3','C4H9NO3 ','C11H12N2O2 ','C9H11NO3 ','C5H11NO2']
df["Molecular Weight"] = ['89.09','174.2','132.12',
'133.1','121.16','147.13','146.14','75.07','155.15',
'131.17','131.17','146.19','149.21','165.19','115.13',
'105.09','119.12','204.22','181.19','117.15']
df["H"] = 0
df["C"] = 0
df["N"] = 0
df["O"] = 0
df["S"] = 0
df.to_csv("AminoAcids.csv", index=False)
print(df.to_string())
A:
If I understand correctly, you should be able to use str.extract here:
df["H"] = df["Formula"].str.extract(r'H(\d+)')
df["C"] = df["Formula"].str.extract(r'C(\d+)')
df["N"] = df["Formula"].str.extract(r'N(\d+)')
df["O"] = df["Formula"].str.extract(r'O(\d+)')
df["S"] = df["Formula"].str.extract(r'S(\d+)')
A:
here is another approach with similar result:
df.join(df['Formula'].str.findall('([A-Z])(\d*)').map(dict).apply(pd.Series).replace('', 1))
>>>
'''
Formula Molecular Weight C H N O S
0 C3H7NO2 89.09 3 7 1 2 NaN
1 C6H14N4O2 174.2 6 14 4 2 NaN
2 C4H8N2O3 132.12 4 8 2 3 NaN
3 C4H7NO4 133.1 4 7 1 4 NaN
4 C3H7NO2S 121.16 3 7 1 2 1.0
5 C5H9NO4 147.13 5 9 1 4 NaN
6 C5H10N2O3 146.14 5 10 2 3 NaN
7 C2H5NO2 75.07 2 5 1 2 NaN
8 C6H9N3O2 155.15 6 9 3 2 NaN
9 C6H13NO2 131.17 6 13 1 2 NaN
10 C6H13NO2 131.17 6 13 1 2 NaN
11 C6H14N2O2 146.19 6 14 2 2 NaN
12 C5H11NO2S 149.21 5 11 1 2 1.0
13 C9H11NO2 165.19 9 11 1 2 NaN
14 C5H9NO2 115.13 5 9 1 2 NaN
15 C3H7NO3 105.09 3 7 1 3 NaN
16 C4H9NO3 119.12 4 9 1 3 NaN
17 C11H12N2O2 204.22 11 12 2 2 NaN
18 C9H11NO3 181.19 9 11 1 3 NaN
19 C5H11NO2 117.15 5 11 1 2 NaN
| Python function about chemical formulas | I have a CSV file that contains chemical matter names and some info.What I need to do is add new columns and write their formulas, molecular weights and count H,C,N,O,S atom numbers in each formula.I am stuck with the counting atom numbers part.I have the function related it but I don't know how to merge it and make code work.
import pandas as pd
import urllib.request
import copy
import re
df = pd.read_csv('AminoAcids.csv')
def countAtoms(string, dict={}):
curDict = copy.copy(dict)
atoms = re.findall("[A-Z]{1}[a-z]*[0-9]*", string)
for j in atoms:
atomGroups = re.match('([A-Z]{1}[a-z]*)([0-9]*)', j)
atom = atomGroups.group(1)
number = atomGroups.group(2)
try :
curDict[atom] = curDict[atom] + int(number)
except KeyError:
try :
curDict[atom] = int(number)
except ValueError:
curDict[atom] = 1
except ValueError:
curDict[atom] = curDict[atom] + 1
return curDict
df["Formula"] = ['C3H7NO2', 'C6H14N4O2 ','C4H8N2O3','C4H7NO4 ',
'C3H7NO2S ','C5H9NO4','C5H10N2O3','C2H5NO2 ','C6H9N3O2',
'C6H13NO2','C6H13NO2','C6H14N2O2 ','C5H11NO2S ','C9H11NO2',
'C5H9NO2 ','C3H7NO3','C4H9NO3 ','C11H12N2O2 ','C9H11NO3 ','C5H11NO2']
df["Molecular Weight"] = ['89.09','174.2','132.12',
'133.1','121.16','147.13','146.14','75.07','155.15',
'131.17','131.17','146.19','149.21','165.19','115.13',
'105.09','119.12','204.22','181.19','117.15']
df["H"] = 0
df["C"] = 0
df["N"] = 0
df["O"] = 0
df["S"] = 0
df.to_csv("AminoAcids.csv", index=False)
print(df.to_string())
| [
"If I understand correctly, you should be able to use str.extract here:\ndf[\"H\"] = df[\"Formula\"].str.extract(r'H(\\d+)')\ndf[\"C\"] = df[\"Formula\"].str.extract(r'C(\\d+)')\ndf[\"N\"] = df[\"Formula\"].str.extract(r'N(\\d+)')\ndf[\"O\"] = df[\"Formula\"].str.extract(r'O(\\d+)')\ndf[\"S\"] = df[\"Formula\"].str.extract(r'S(\\d+)')\n\n",
"here is another approach with similar result:\ndf.join(df['Formula'].str.findall('([A-Z])(\\d*)').map(dict).apply(pd.Series).replace('', 1))\n\n>>>\n'''\n Formula Molecular Weight C H N O S\n0 C3H7NO2 89.09 3 7 1 2 NaN\n1 C6H14N4O2 174.2 6 14 4 2 NaN\n2 C4H8N2O3 132.12 4 8 2 3 NaN\n3 C4H7NO4 133.1 4 7 1 4 NaN\n4 C3H7NO2S 121.16 3 7 1 2 1.0\n5 C5H9NO4 147.13 5 9 1 4 NaN\n6 C5H10N2O3 146.14 5 10 2 3 NaN\n7 C2H5NO2 75.07 2 5 1 2 NaN\n8 C6H9N3O2 155.15 6 9 3 2 NaN\n9 C6H13NO2 131.17 6 13 1 2 NaN\n10 C6H13NO2 131.17 6 13 1 2 NaN\n11 C6H14N2O2 146.19 6 14 2 2 NaN\n12 C5H11NO2S 149.21 5 11 1 2 1.0\n13 C9H11NO2 165.19 9 11 1 2 NaN\n14 C5H9NO2 115.13 5 9 1 2 NaN\n15 C3H7NO3 105.09 3 7 1 3 NaN\n16 C4H9NO3 119.12 4 9 1 3 NaN\n17 C11H12N2O2 204.22 11 12 2 2 NaN\n18 C9H11NO3 181.19 9 11 1 3 NaN\n19 C5H11NO2 117.15 5 11 1 2 NaN\n\n"
] | [
1,
1
] | [] | [] | [
"chemistry",
"csv",
"python",
"python_3.x"
] | stackoverflow_0074668631_chemistry_csv_python_python_3.x.txt |
Q:
Python: Extract keywords from string
Hey Guys I am searching for a fast/efficient way to extract keywords (defined in a list) from a String (in a Dataframe) without being case sensitive or dependent on " " chars:
keys = ['I', 'love', 'Cookies']
String from df= "xxxxxxxxIxx xx cookies"
result should by either ['I'] or ['I', 'Cookies']
I am currently using f"({'|'.join(keys)}) which is case sensitive. What would you recommend for long strings in even longer dataframes :)
Thanks in advance
A:
Working code as per your inputs:
my_str ="xxxxxxxixxx xx cookhes"
my_list = ["I", "love", "Cookies"]
if any(substring.casefold() in my_str.casefold() for substring in my_list):
print('Contains element')
else:
print('Not contain any element.')
More info on the following answer from StackOverflow:
Case insensitive 'in'
| Python: Extract keywords from string | Hey Guys I am searching for a fast/efficient way to extract keywords (defined in a list) from a String (in a Dataframe) without being case sensitive or dependent on " " chars:
keys = ['I', 'love', 'Cookies']
String from df= "xxxxxxxxIxx xx cookies"
result should by either ['I'] or ['I', 'Cookies']
I am currently using f"({'|'.join(keys)}) which is case sensitive. What would you recommend for long strings in even longer dataframes :)
Thanks in advance
| [
"Working code as per your inputs:\nmy_str =\"xxxxxxxixxx xx cookhes\"\nmy_list = [\"I\", \"love\", \"Cookies\"]\nif any(substring.casefold() in my_str.casefold() for substring in my_list):\n print('Contains element')\nelse:\n print('Not contain any element.')\n\nMore info on the following answer from StackOverflow:\nCase insensitive 'in'\n"
] | [
0
] | [] | [] | [
"dataframe",
"python",
"string",
"substring"
] | stackoverflow_0074669279_dataframe_python_string_substring.txt |
Q:
hi why does my else in while loop is not working?
I wanted to select two numbers and when I run the program it will start form the lower one and will print me numbers one after one till the big number.
the loop in the while is working but the else doesnt work...
num1= int(input('enter first number'))
num2= int (input('enter second number'))
while num1 > num2 :
print(num2)
num2= num2 + 1
else:
print(num1)
num1 = num1 + 1
I wanted to select two numbers and when I run the program it will start form the lower one and will print me numbers one after one till the big number.
the loop in the while is working but the else doesnt work...
| hi why does my else in while loop is not working? | I wanted to select two numbers and when I run the program it will start form the lower one and will print me numbers one after one till the big number.
the loop in the while is working but the else doesnt work...
num1= int(input('enter first number'))
num2= int (input('enter second number'))
while num1 > num2 :
print(num2)
num2= num2 + 1
else:
print(num1)
num1 = num1 + 1
I wanted to select two numbers and when I run the program it will start form the lower one and will print me numbers one after one till the big number.
the loop in the while is working but the else doesnt work...
| [] | [] | [
"You haven't written If statement in your code that,s why its not working\n"
] | [
-1
] | [
"python",
"while_loop"
] | stackoverflow_0074669439_python_while_loop.txt |
Q:
Trying to get historical data for multiple securities using python and IB API - df not clearing between loops
I'm trying to get historical data for several products through the IB API, and store each product in a dataframe (which I need to save in separate csv files).
This is my code, the main issue is that the dataframe isn't clearing between loops, when moving onto the second loop the df contains data for 2 products, the third for 3. I'm not sure where / how to clear the df.
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
import pandas as pd
import threading
import time
class IBapi(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.data = []
def historicalData(self, reqId, bar):
self.data.append([bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume])
def error(self, reqId, errorCode, errorString):
print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)
def historicalDataEnd(self, reqId: int, start: str, end: str):
print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
self.df = pd.DataFrame(self.data)
def run_loop():
app.run()
app = IBapi()
#Create contract object
ES_contract = Contract()
ES_contract.symbol = 'ES'
ES_contract.secType = 'FUT'
ES_contract.exchange = 'GLOBEX'
ES_contract.lastTradeDateOrContractMonth = '202209'
#Create contract object
VIX_contract = Contract()
VIX_contract.symbol = 'VIX'
VIX_contract.secType = 'IND'
VIX_contract.exchange = 'CBOE'
VIX_contract.currency = 'USD'
#Create contract object
DAX_contract = Contract()
DAX_contract.symbol = 'DAX'
DAX_contract.secType = 'FUT'
DAX_contract.exchange = 'EUREX'
DAX_contract.currency = 'EUR'
DAX_contract.lastTradeDateOrContractMonth = '202209'
DAX_contract.multiplier = '25'
products={'ES': ES_contract, 'VIX': VIX_contract, 'DAX': DAX_contract}
nid=1
app.connect('127.0.0.1', 4001, 123)
#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()
time.sleep(1) #Sleep interval to allow time for connection to server
def fetchdata_function(name,nid):
df=pd.DataFrame()
#Request historical candles
app.reqHistoricalData(nid, products[name], '', '1 W', '5 mins', 'TRADES', 0, 2, False, [])
time.sleep(10) #sleep to allow enough time for data to be returned
df = pd.DataFrame(app.data, columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume'])
df['Date'] = pd.to_datetime(df['Date'],unit='s')
df=df.set_index('Date')
df.to_csv('1week'+str(name)+'5min.csv')
print(df)
names=['ES', 'DAX', 'VIX']
for name in names:
fetchdata_function(name,nid)
nid=nid+1
app.disconnect()
A:
create a dictionary and append the app.data as a key value pair in the historicaldata callback. Then you can access them separately - in fact converting a dict to multi-level dataframe is also possible
| Trying to get historical data for multiple securities using python and IB API - df not clearing between loops | I'm trying to get historical data for several products through the IB API, and store each product in a dataframe (which I need to save in separate csv files).
This is my code, the main issue is that the dataframe isn't clearing between loops, when moving onto the second loop the df contains data for 2 products, the third for 3. I'm not sure where / how to clear the df.
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
import pandas as pd
import threading
import time
class IBapi(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.data = []
def historicalData(self, reqId, bar):
self.data.append([bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume])
def error(self, reqId, errorCode, errorString):
print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)
def historicalDataEnd(self, reqId: int, start: str, end: str):
print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
self.df = pd.DataFrame(self.data)
def run_loop():
app.run()
app = IBapi()
#Create contract object
ES_contract = Contract()
ES_contract.symbol = 'ES'
ES_contract.secType = 'FUT'
ES_contract.exchange = 'GLOBEX'
ES_contract.lastTradeDateOrContractMonth = '202209'
#Create contract object
VIX_contract = Contract()
VIX_contract.symbol = 'VIX'
VIX_contract.secType = 'IND'
VIX_contract.exchange = 'CBOE'
VIX_contract.currency = 'USD'
#Create contract object
DAX_contract = Contract()
DAX_contract.symbol = 'DAX'
DAX_contract.secType = 'FUT'
DAX_contract.exchange = 'EUREX'
DAX_contract.currency = 'EUR'
DAX_contract.lastTradeDateOrContractMonth = '202209'
DAX_contract.multiplier = '25'
products={'ES': ES_contract, 'VIX': VIX_contract, 'DAX': DAX_contract}
nid=1
app.connect('127.0.0.1', 4001, 123)
#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()
time.sleep(1) #Sleep interval to allow time for connection to server
def fetchdata_function(name,nid):
df=pd.DataFrame()
#Request historical candles
app.reqHistoricalData(nid, products[name], '', '1 W', '5 mins', 'TRADES', 0, 2, False, [])
time.sleep(10) #sleep to allow enough time for data to be returned
df = pd.DataFrame(app.data, columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume'])
df['Date'] = pd.to_datetime(df['Date'],unit='s')
df=df.set_index('Date')
df.to_csv('1week'+str(name)+'5min.csv')
print(df)
names=['ES', 'DAX', 'VIX']
for name in names:
fetchdata_function(name,nid)
nid=nid+1
app.disconnect()
| [
"create a dictionary and append the app.data as a key value pair in the historicaldata callback. Then you can access them separately - in fact converting a dict to multi-level dataframe is also possible\n"
] | [
0
] | [] | [] | [
"ib_api",
"interactive_brokers",
"pandas",
"python",
"tws"
] | stackoverflow_0073211491_ib_api_interactive_brokers_pandas_python_tws.txt |
Q:
Create a link to a specific word count position such as bookmark in docx
How this project works:
Searches external docx / OCR data for a keyword
Builds a context of 100 words surrounding the keyword
Builds a docx to store the passage with a hyperlink posted under each completed search
What is missing:
A way to link to the passage to its source from the external document in Word, so you can just use a hyperlink to it, but the problem is the OCR docx files read have no headings to bookmark a run, and I could not create them with long OCR, so it is not manageable from the aspect of going in to the docx file one by one reading gibberish at times.
So Word needs to be able to store the solution in the document where the passage is printed in the new file. This hyperlink code works... I need something more than what I have here to find the passage locations on its source, unless MS Word will not support such a specific function as finding the indexed word position of the passage? Can I build a macro and call it in python to make a link and run its position using the index?
Hyperlinking/bookmark code post ref:
def add_hyperlink(paragraph, text, url):
# This gets access to the document.xml.rels file and gets a new relation id value
part = paragraph.part
r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
# Create the w:hyperlink tag and add needed values
hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )
# Create a w:r element and a new w:rPr element
new_run = docx.oxml.shared.OxmlElement('w:r')
rPr = docx.oxml.shared.OxmlElement('w:rPr')
# Join all the xml elements together add the required text to the w:r element
new_run.append(rPr)
new_run.text = text
hyperlink.append(new_run)
# Create a new Run object and add the hyperlink into it
r = paragraph.add_run()
r._r.append(hyperlink)
# A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
# Delete this if using a template that has the hyperlink style in it
r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
r.font.underline = True
return hyperlink
def extract_surround_words(text, keyword, n):
'''
text : input text
keyword : the search keyword we are looking
n : number of words around the keyword
'''
# extracting all the words from text
words = re.findall(r'\w+', text)
passage = []
passageText = ''
saveIndex = []
passagePos = []
indexVal = ''
document = Document()
document.add_heading("The keyword searched is: " + searchKeyword + ", WORD COUNT: " + str(len(text)) + "\n", 0)
# iterate through all the words
for index, word in enumerate(words):
# check if search keyword matches
if word == keyword and len(words) > 0:
saveIndex.append(str(index-n))
# fetch left side words and right
passage = words[index - n: index] #start text run
passage.append(keyword)
passage += words[index + 1: index + n + 1] #end of run
passagePos = "\nWORD COUNT POSITION: " + str(saveIndex.pop() + "\n")
bookmark = add_bookmark(index, passagePos)
print(str(passagePos))
for wd in passage:
passageText += ' ' + wd
parag = document.add_paragraph(passageText)
add_hyperlink(parag, passagePos, os.path.join(path, file))
passage.append("\n\n")
document.save(os.path.join(output_path, out_file_doc))
return passageText
A:
To build a system that searches for a keyword in external documents, extracts a context of 100 words surrounding the keyword, and creates a new document with hyperlinks to the passages in the original document. The problem you are facing is that the OCR documents do not have headings or bookmarks, so it is difficult to create hyperlinks to specific passages in the original document.
One solution to this problem could be to use a macro in Microsoft Word to create the hyperlinks and store them in the new document. You can write a macro in Visual Basic for Applications (VBA) that takes the keyword, context, and file path of the original document as input and returns the position of the keyword in the original document. This macro can then be called from your Python script using the python-docx library, which allows you to run VBA macros and interact with Microsoft Word documents.
Here is an example of how you could write the macro and call it from your Python script:
VBA macro (save as CreateHyperlink.bas):
Sub CreateHyperlink(keyword As String, context As String, filePath As String)
' Open the original document
Dim originalDoc As Document
Set originalDoc = Documents.Open(filePath)
' Search for the keyword in the original document
Dim keywordRange As Range
Set keywordRange = originalDoc.Range.Find(keyword)
' Get the position of the keyword in the original document
Dim keywordPos As Long
keywordPos = keywordRange.Start
' Close the original document
originalDoc.Close
' Return the keyword position to the calling Python script
ThisDocument.VBProject.VBComponents("ThisDocument")._
CodeModule.AddFromString "keywordPos = " & keywordPos
End Sub
Python script:
# Import the required libraries
from docx import Document
from docx.enum.vba import MsoModuleType
from docx.vba.module import Module
# Open the new document
document = Document()
# Add the VBA macro to the new document
vba_filename = 'CreateHyperlink.bas'
with open(vba_filename, 'rb') as f:
vba_bin = f.read()
document.add_vba_binary(vba_bin)
# Call the VBA macro from the Python script
document.vba_modules['ThisDocument']._modules[0]._methods[0].Run(
keyword='keyword',
context='context',
filePath='filePath',
)
# Get the keyword position returned by the VBA macro
keywordPos = document.vba_modules['ThisDocument']._modules[0]._attributes['keywordPos']
# Use the keyword position to create a hyperlink to the original passage
paragraph = document.add_paragraph(context)
document.add_hyperlink(paragraph, keywordPos, filePath)
# Save the new document
document.save('new_document.docx')
| Create a link to a specific word count position such as bookmark in docx | How this project works:
Searches external docx / OCR data for a keyword
Builds a context of 100 words surrounding the keyword
Builds a docx to store the passage with a hyperlink posted under each completed search
What is missing:
A way to link to the passage to its source from the external document in Word, so you can just use a hyperlink to it, but the problem is the OCR docx files read have no headings to bookmark a run, and I could not create them with long OCR, so it is not manageable from the aspect of going in to the docx file one by one reading gibberish at times.
So Word needs to be able to store the solution in the document where the passage is printed in the new file. This hyperlink code works... I need something more than what I have here to find the passage locations on its source, unless MS Word will not support such a specific function as finding the indexed word position of the passage? Can I build a macro and call it in python to make a link and run its position using the index?
Hyperlinking/bookmark code post ref:
def add_hyperlink(paragraph, text, url):
# This gets access to the document.xml.rels file and gets a new relation id value
part = paragraph.part
r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
# Create the w:hyperlink tag and add needed values
hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )
# Create a w:r element and a new w:rPr element
new_run = docx.oxml.shared.OxmlElement('w:r')
rPr = docx.oxml.shared.OxmlElement('w:rPr')
# Join all the xml elements together add the required text to the w:r element
new_run.append(rPr)
new_run.text = text
hyperlink.append(new_run)
# Create a new Run object and add the hyperlink into it
r = paragraph.add_run()
r._r.append(hyperlink)
# A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
# Delete this if using a template that has the hyperlink style in it
r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
r.font.underline = True
return hyperlink
def extract_surround_words(text, keyword, n):
'''
text : input text
keyword : the search keyword we are looking
n : number of words around the keyword
'''
# extracting all the words from text
words = re.findall(r'\w+', text)
passage = []
passageText = ''
saveIndex = []
passagePos = []
indexVal = ''
document = Document()
document.add_heading("The keyword searched is: " + searchKeyword + ", WORD COUNT: " + str(len(text)) + "\n", 0)
# iterate through all the words
for index, word in enumerate(words):
# check if search keyword matches
if word == keyword and len(words) > 0:
saveIndex.append(str(index-n))
# fetch left side words and right
passage = words[index - n: index] #start text run
passage.append(keyword)
passage += words[index + 1: index + n + 1] #end of run
passagePos = "\nWORD COUNT POSITION: " + str(saveIndex.pop() + "\n")
bookmark = add_bookmark(index, passagePos)
print(str(passagePos))
for wd in passage:
passageText += ' ' + wd
parag = document.add_paragraph(passageText)
add_hyperlink(parag, passagePos, os.path.join(path, file))
passage.append("\n\n")
document.save(os.path.join(output_path, out_file_doc))
return passageText
| [
"To build a system that searches for a keyword in external documents, extracts a context of 100 words surrounding the keyword, and creates a new document with hyperlinks to the passages in the original document. The problem you are facing is that the OCR documents do not have headings or bookmarks, so it is difficult to create hyperlinks to specific passages in the original document.\nOne solution to this problem could be to use a macro in Microsoft Word to create the hyperlinks and store them in the new document. You can write a macro in Visual Basic for Applications (VBA) that takes the keyword, context, and file path of the original document as input and returns the position of the keyword in the original document. This macro can then be called from your Python script using the python-docx library, which allows you to run VBA macros and interact with Microsoft Word documents.\nHere is an example of how you could write the macro and call it from your Python script:\nVBA macro (save as CreateHyperlink.bas):\nSub CreateHyperlink(keyword As String, context As String, filePath As String)\n ' Open the original document\n Dim originalDoc As Document\n Set originalDoc = Documents.Open(filePath)\n\n ' Search for the keyword in the original document\n Dim keywordRange As Range\n Set keywordRange = originalDoc.Range.Find(keyword)\n\n ' Get the position of the keyword in the original document\n Dim keywordPos As Long\n keywordPos = keywordRange.Start\n\n ' Close the original document\n originalDoc.Close\n\n ' Return the keyword position to the calling Python script\n ThisDocument.VBProject.VBComponents(\"ThisDocument\")._\n CodeModule.AddFromString \"keywordPos = \" & keywordPos\nEnd Sub\n\nPython script:\n# Import the required libraries\nfrom docx import Document\nfrom docx.enum.vba import MsoModuleType\nfrom docx.vba.module import Module\n\n# Open the new document\ndocument = Document()\n\n# Add the VBA macro to the new document\nvba_filename = 'CreateHyperlink.bas'\nwith open(vba_filename, 'rb') as f:\n vba_bin = f.read()\ndocument.add_vba_binary(vba_bin)\n\n# Call the VBA macro from the Python script\ndocument.vba_modules['ThisDocument']._modules[0]._methods[0].Run(\n keyword='keyword',\n context='context',\n filePath='filePath',\n)\n\n# Get the keyword position returned by the VBA macro\nkeywordPos = document.vba_modules['ThisDocument']._modules[0]._attributes['keywordPos']\n\n# Use the keyword position to create a hyperlink to the original passage\nparagraph = document.add_paragraph(context)\ndocument.add_hyperlink(paragraph, keywordPos, filePath)\n\n# Save the new document\ndocument.save('new_document.docx')\n\n"
] | [
0
] | [] | [] | [
"hyperlink",
"ms_word",
"python"
] | stackoverflow_0074669471_hyperlink_ms_word_python.txt |
Q:
Is it possible in Python to call a child from parent class without initialize the child?
I want to know if is it possible to create a parent class to handle some common logic, but have some specific logic in child classes and run it without initialize the child as it's in abstraction.
For example:
class Person:
def __init__(self, fname, lname, country):
self.firstname = fname
self.lastname = lname
self.country = country
if country == "US":
# Call class UnitedStates(Person)
else if country == "CA":
# Call class Canada(Person)
def printCountry(self):
print(self.firstname + " " + self.lastname + " is from " + self.country)
class UnitedStates(Person):
def __init__(self):
super().country="United States"
pass
class Canada(Person):
def __init__(self):
super().country="Canada"
pass
x = Person("John", "Doe", "US")
x.printCountry()
y = Person("Jane", "Doe", "CA")
y.printCountry()
So in x I have "John Doe is from United States" and in y I have "Jane Doe is from Canada".
The reason I need that come from a high complex logic and that's the easiest way to deal, so that sample is a dummy version of what I need, otherwise I'll need to find the best way for a "work around".
Thanks in advance.
| Is it possible in Python to call a child from parent class without initialize the child? | I want to know if is it possible to create a parent class to handle some common logic, but have some specific logic in child classes and run it without initialize the child as it's in abstraction.
For example:
class Person:
def __init__(self, fname, lname, country):
self.firstname = fname
self.lastname = lname
self.country = country
if country == "US":
# Call class UnitedStates(Person)
else if country == "CA":
# Call class Canada(Person)
def printCountry(self):
print(self.firstname + " " + self.lastname + " is from " + self.country)
class UnitedStates(Person):
def __init__(self):
super().country="United States"
pass
class Canada(Person):
def __init__(self):
super().country="Canada"
pass
x = Person("John", "Doe", "US")
x.printCountry()
y = Person("Jane", "Doe", "CA")
y.printCountry()
So in x I have "John Doe is from United States" and in y I have "Jane Doe is from Canada".
The reason I need that come from a high complex logic and that's the easiest way to deal, so that sample is a dummy version of what I need, otherwise I'll need to find the best way for a "work around".
Thanks in advance.
| [] | [] | [
"Yes, it is possible to create a parent class that has some common logic and child classes that have specific logic, and to call the child class methods without initializing an instance of the child class. However, the code you have provided will not work as you expect it to because it contains some errors and logical issues.\nHere is one way you could modify your code to achieve the behavior you want:\nclass Person:\n def __init__(self, fname, lname, country):\n self.firstname = fname\n self.lastname = lname\n self.country = country\n\n # Call the appropriate child class based on the country\n if country == \"US\":\n self.us = UnitedStates()\n else if country == \"CA\":\n self.ca = Canada()\n\n def printCountry(self):\n print(self.firstname + \" \" + self.lastname + \" is from \" + self.country)\n\nclass UnitedStates(Person):\n def __init__(self):\n super().__init__()\n self.country = \"United States\"\n\nclass Canada(Person):\n def __init__(self):\n super().__init__()\n self.country = \"Canada\"\n\n# Create an instance of the Person class and call the printCountry method\nx = Person(\"John\", \"Doe\", \"US\")\nx.printCountry()\n\n# Create another instance of the Person class and call the printCountry method\ny = Person(\"Jane\", \"Doe\", \"CA\")\ny.printCountry()\n\nIn this code, the Person class has a constructor method that takes three arguments: the first name, last name, and country of a person. Based on the country, it creates an instance of the appropriate child class (UnitedStates or Canada) and assigns it to the us or ca attribute of the Person instance. The printCountry method of the Person class then prints a message using the firstname, lastname, and country attributes of the Person instance.\nThe UnitedStates and Canada child classes each have a constructor method that calls the init method of the parent Person class, and then sets the country attribute to the appropriate value.\nWhen you create an instance of the Person class and call the printCountry method, the appropriate child class is called and the country attribute is set to the correct value before the message is printed.\n"
] | [
-1
] | [
"abstract_class",
"class_hierarchy",
"python",
"python_3.x"
] | stackoverflow_0074669535_abstract_class_class_hierarchy_python_python_3.x.txt |
Q:
Plotting Scatter plot with different lines
Please I am trying to plot a scatter plot as shown in the attached image.
I have tried the below code but it is not working. This is in python by the way.
hours = [n / 3600 for n in seconds]
fig, ax = plt.subplots(figsize=(8, 6))
## Your code here
ax.plot(hours, fish_counts, marker="x")
ax.set_xlabel("Hours since low tide")
ax.set_ylabel("Jellyfish entering bay over 15 minutes")
ax.legend()[![enter image description here][1]][1]
Attached image is how the output should look. Thank you.
[1]: https://i.stack.imgur.com/5KQiz.png
A:
To plot a scatter plot with the data you provided, you can use the scatter method instead of the plot method. Here is an example of how you could do this:
# import the necessary packages
import matplotlib.pyplot as plt
# define the data
hours = [n / 3600 for n in seconds]
fish_counts = [10, 12, 8, 11, 9, 15, 20, 22, 19, 25]
# create a figure and an axes
fig, ax = plt.subplots(figsize=(8, 6))
# plot the data as a scatter plot
ax.scatter(hours, fish_counts, marker="x")
# set the x-axis label
ax.set_xlabel("Hours since low tide")
# set the y-axis label
ax.set_ylabel("Jellyfish entering bay over 15 minutes")
# show the legend
ax.legend()
# show the plot
plt.show()
This code will create a scatter plot with the hours and fish_counts data, using the x marker to represent the data points. The x-axis will be labeled "Hours since low tide" and the y-axis will be labeled "Jellyfish entering bay over 15 minutes".
In this example, the scatter method takes the hours and fish_counts arrays as the first and second arguments, respectively. The marker argument is set to "x" to use the x marker for the data points.
You can also customize the appearance of the scatter plot by setting additional arguments to the scatter method. For example, you can use the color argument to set the color of the data points, or the s argument to set the size of the markers. Here is an example of how you could use these arguments:
# create a figure and an axes
fig, ax = plt.subplots(figsize=(8, 6))
# plot the data as a scatter plot with customized colors and marker sizes
ax.scatter(hours, fish_counts, marker="x", color="green", s=100)
# set the x-axis label
ax.set_xlabel("Hours since low tide")
# set the y-axis label
ax.set_ylabel("Jellyfish entering bay over 15 minutes")
# show the legend
ax.legend()
# show the plot
plt.show()
A:
To create a scatter plot in Python with the data and format shown in the image, you can use the following code:
hours = [n / 3600 for n in seconds]
fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(hours, fish_counts, marker="x", color="red")
ax.set_xlabel("Hours since low tide")
ax.set_ylabel("Jellyfish entering bay over 15 minutes")
ax.legend()
The key difference between this code and the code you provided is that it uses the scatter() method to create the scatter plot, instead of the plot() method. The scatter() method allows you to specify the marker style and color for the data points, which is necessary to match the format of the scatter plot in the image.
By using this code, you should be able to create a scatter plot that matches the format shown in the image.
A:
To add lines to your scatter plot, you can use the ax.plot() method. The first argument to this method should be the x-coordinates of the points on the line, and the second argument should be the y-coordinates of the points on the line. Here is an example:
# Set up the plot
fig, ax = plt.subplots(figsize=(8, 6))
# Add the scatter plot
ax.scatter(hours, fish_counts, marker="x")
# Add the lines
ax.plot([0, 24], [200, 200], color="green")
ax.plot([0, 24], [300, 300], color="orange")
ax.plot([0, 24], [400, 400], color="green")
# Add the axes labels
ax.set_xlabel("Hours since low tide")
ax.set_ylabel("Jellyfish entering bay over 15 minutes")
# Show the plot
plt.show()
In this code, we use ax.plot() to add three lines to the plot, each with different color and y-coordinate values. You can adjust the x-coordinates of the lines to position them as desired on the plot. You can also adjust the colors of the lines by passing a different color value to the color argument of ax.plot(). You can specify colors by their name (e.g. "green") or by their hex code (e.g. "#00ff00").
| Plotting Scatter plot with different lines | Please I am trying to plot a scatter plot as shown in the attached image.
I have tried the below code but it is not working. This is in python by the way.
hours = [n / 3600 for n in seconds]
fig, ax = plt.subplots(figsize=(8, 6))
## Your code here
ax.plot(hours, fish_counts, marker="x")
ax.set_xlabel("Hours since low tide")
ax.set_ylabel("Jellyfish entering bay over 15 minutes")
ax.legend()[![enter image description here][1]][1]
Attached image is how the output should look. Thank you.
[1]: https://i.stack.imgur.com/5KQiz.png
| [
"To plot a scatter plot with the data you provided, you can use the scatter method instead of the plot method. Here is an example of how you could do this:\n# import the necessary packages\nimport matplotlib.pyplot as plt\n\n# define the data\nhours = [n / 3600 for n in seconds]\nfish_counts = [10, 12, 8, 11, 9, 15, 20, 22, 19, 25]\n\n# create a figure and an axes\nfig, ax = plt.subplots(figsize=(8, 6))\n\n# plot the data as a scatter plot\nax.scatter(hours, fish_counts, marker=\"x\")\n\n# set the x-axis label\nax.set_xlabel(\"Hours since low tide\")\n\n# set the y-axis label\nax.set_ylabel(\"Jellyfish entering bay over 15 minutes\")\n\n# show the legend\nax.legend()\n\n# show the plot\nplt.show()\n\nThis code will create a scatter plot with the hours and fish_counts data, using the x marker to represent the data points. The x-axis will be labeled \"Hours since low tide\" and the y-axis will be labeled \"Jellyfish entering bay over 15 minutes\".\nIn this example, the scatter method takes the hours and fish_counts arrays as the first and second arguments, respectively. The marker argument is set to \"x\" to use the x marker for the data points.\nYou can also customize the appearance of the scatter plot by setting additional arguments to the scatter method. For example, you can use the color argument to set the color of the data points, or the s argument to set the size of the markers. Here is an example of how you could use these arguments:\n# create a figure and an axes\nfig, ax = plt.subplots(figsize=(8, 6))\n\n# plot the data as a scatter plot with customized colors and marker sizes\nax.scatter(hours, fish_counts, marker=\"x\", color=\"green\", s=100)\n\n# set the x-axis label\nax.set_xlabel(\"Hours since low tide\")\n\n# set the y-axis label\nax.set_ylabel(\"Jellyfish entering bay over 15 minutes\")\n\n# show the legend\nax.legend()\n\n# show the plot\nplt.show()\n\n",
"To create a scatter plot in Python with the data and format shown in the image, you can use the following code:\nhours = [n / 3600 for n in seconds]\nfig, ax = plt.subplots(figsize=(8, 6))\nax.scatter(hours, fish_counts, marker=\"x\", color=\"red\")\nax.set_xlabel(\"Hours since low tide\")\nax.set_ylabel(\"Jellyfish entering bay over 15 minutes\")\nax.legend()\n\nThe key difference between this code and the code you provided is that it uses the scatter() method to create the scatter plot, instead of the plot() method. The scatter() method allows you to specify the marker style and color for the data points, which is necessary to match the format of the scatter plot in the image.\nBy using this code, you should be able to create a scatter plot that matches the format shown in the image.\n",
"To add lines to your scatter plot, you can use the ax.plot() method. The first argument to this method should be the x-coordinates of the points on the line, and the second argument should be the y-coordinates of the points on the line. Here is an example:\n# Set up the plot\nfig, ax = plt.subplots(figsize=(8, 6))\n\n# Add the scatter plot\nax.scatter(hours, fish_counts, marker=\"x\")\n\n# Add the lines\nax.plot([0, 24], [200, 200], color=\"green\")\nax.plot([0, 24], [300, 300], color=\"orange\")\nax.plot([0, 24], [400, 400], color=\"green\")\n\n# Add the axes labels\nax.set_xlabel(\"Hours since low tide\")\nax.set_ylabel(\"Jellyfish entering bay over 15 minutes\")\n\n# Show the plot\nplt.show()\n\nIn this code, we use ax.plot() to add three lines to the plot, each with different color and y-coordinate values. You can adjust the x-coordinates of the lines to position them as desired on the plot. You can also adjust the colors of the lines by passing a different color value to the color argument of ax.plot(). You can specify colors by their name (e.g. \"green\") or by their hex code (e.g. \"#00ff00\").\n"
] | [
0,
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074668688_matplotlib_python.txt |
Q:
Django - How do you create several model instances at the same time because they are connected
I want to create a user profile and the user profile has a location (address). I need to create the profile first and location second, and then match the profile and the location using a third model called ProfileLocation. I want to do this using one api call, because all the data comes from one form and the location depends on the profile.
There is a location model that has OneToOne fields for Country, State and City. The countries, states and cities will have the database tables populated before the time. There is an extra model called ProfileLocation that links the profile to the location. So I have to create all of them at once and struggling with what the best way to do it is. Also what type of DRF view do I use for the endpoint? I need to understand the logic please and I cannot find an example on the net.
Do I need to create a custom function based view and run the data through the existing serializers? In that case how can I bundle the incoming data for each specific serializer?
This is all very new to me
Locations model.py:
from django.db import models
from django_extensions.db.fields import AutoSlugField
class Country(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country_code = models.CharField(max_length=5)
dial_code = models.CharField(max_length=5)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "country"
verbose_name_plural = "countries"
db_table = "countries"
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class State(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country = models.OneToOneField(Country, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField("date post was created", auto_now_add=True)
updated_at = models.DateTimeField("date post was updated", auto_now=True)
class Meta:
verbose_name = "state"
verbose_name_plural = "states"
db_table = "states"
unique_together = ["country", "name"]
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class City(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country = models.OneToOneField(Country, on_delete=models.CASCADE, default=None)
state = models.OneToOneField(State, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField("date post was created", auto_now_add=True)
updated_at = models.DateTimeField("date post was updated", auto_now=True)
class Meta:
verbose_name = "city"
verbose_name_plural = "cities"
db_table = "cities"
unique_together = ["country", "state", "name"]
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class Location(models.Model):
name = models.CharField(max_length=50, default=None)
slug = AutoSlugField(populate_from=["name"])
street = models.CharField(max_length=100)
additional = models.CharField(max_length=100)
country = models.OneToOneField(State, on_delete=models.CASCADE, related_name="countries")
state = models.OneToOneField(State, on_delete=models.CASCADE, related_name="states")
city = models.OneToOneField(City, on_delete=models.CASCADE, related_name="cities")
zip = models.CharField(max_length=30)
phone = models.CharField(max_length=15)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at")
class Meta:
verbose_name = "location"
verbose_name_plural = "locations"
db_table = "locations"
ordering = ["zip"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
This is my Location models.py:
from django.db import models
from django_extensions.db.fields import AutoSlugField
class Country(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country_code = models.CharField(max_length=5)
dial_code = models.CharField(max_length=5)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "country"
verbose_name_plural = "countries"
db_table = "countries"
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class State(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country = models.OneToOneField(Country, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField("date post was created", auto_now_add=True)
updated_at = models.DateTimeField("date post was updated", auto_now=True)
class Meta:
verbose_name = "state"
verbose_name_plural = "states"
db_table = "states"
unique_together = ["country", "name"]
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class City(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country = models.OneToOneField(Country, on_delete=models.CASCADE, default=None)
state = models.OneToOneField(State, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField("date post was created", auto_now_add=True)
updated_at = models.DateTimeField("date post was updated", auto_now=True)
class Meta:
verbose_name = "city"
verbose_name_plural = "cities"
db_table = "cities"
unique_together = ["country", "state", "name"]
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class Location(models.Model):
name = models.CharField(max_length=50, default=None)
slug = AutoSlugField(populate_from=["name"])
street = models.CharField(max_length=100)
additional = models.CharField(max_length=100)
country = models.OneToOneField(State, on_delete=models.CASCADE, related_name="countries")
state = models.OneToOneField(State, on_delete=models.CASCADE, related_name="states")
city = models.OneToOneField(City, on_delete=models.CASCADE, related_name="cities")
zip = models.CharField(max_length=30)
phone = models.CharField(max_length=15)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at")
class Meta:
verbose_name = "location"
verbose_name_plural = "locations"
db_table = "locations"
ordering = ["zip"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
Here are the Location serializers which are ordinary modelserializers:
from rest_framework import serializers
from .models import *
from profiles.models import ProfileLocation
class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = [
"id",
"name",
"country_code",
"dial_code",
"created_at",
"updated_at",
]
class StateSerializer(serializers.ModelSerializer):
class Meta:
model = State
fields = [
"id",
"name",
"country",
"created_at",
"updated_at",
]
class CitySerializer(serializers.ModelSerializer):
class Meta:
model = City
fields = [
"id",
"name",
"country",
"state",
"created_at",
"updated_at",
]
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = [
"name",
"street",
"additional",
"zip",
"city",
"phone",
"created_at",
"updated_at",
]
class ProfileLocationSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ProfileLocation
fields =[
"location"
"profile"
]
and the profile serializer:
from rest_framework import serializers
from .models import *
from locations.serializers import ProfileLocationSerializer
class ProfileSerializer(serializers.ModelSerializer):
location = ProfileLocationSerializer()
class Meta:
model = Profile
fields = [
"background",
"photo",
"first_name",
"middle_name",
"last_name",
"birthdate",
"gender",
"bio",
"languages",
"is_verified",
"verification",
"location",
"website",
"user",
"created_at",
"updated_at",
]
def create(self, validated_data):
new_profile = Profile.objects.create(**validated_data)
return new_profile
This view creates the profile without any problems but excludes the location obviously.
class ProfileViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated]
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
Thank you in advance
A:
your procedure is perfect, just need to override the create method of the serializer
def create(self, validated_data):
# for better understand print or log the validated_data
location_data = validated_data.pop('location') # all location data will be poped from the validated data as a dict
# create a location object
location_obj = Location.objects.create(**location_data)
location_obj.save()
# then add the location object in profile obj
new_profile = Profile.objects.create(**validated_data, location=location_ojb)
new_profile.save()
return new_profile
please go through the official doc
| Django - How do you create several model instances at the same time because they are connected | I want to create a user profile and the user profile has a location (address). I need to create the profile first and location second, and then match the profile and the location using a third model called ProfileLocation. I want to do this using one api call, because all the data comes from one form and the location depends on the profile.
There is a location model that has OneToOne fields for Country, State and City. The countries, states and cities will have the database tables populated before the time. There is an extra model called ProfileLocation that links the profile to the location. So I have to create all of them at once and struggling with what the best way to do it is. Also what type of DRF view do I use for the endpoint? I need to understand the logic please and I cannot find an example on the net.
Do I need to create a custom function based view and run the data through the existing serializers? In that case how can I bundle the incoming data for each specific serializer?
This is all very new to me
Locations model.py:
from django.db import models
from django_extensions.db.fields import AutoSlugField
class Country(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country_code = models.CharField(max_length=5)
dial_code = models.CharField(max_length=5)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "country"
verbose_name_plural = "countries"
db_table = "countries"
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class State(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country = models.OneToOneField(Country, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField("date post was created", auto_now_add=True)
updated_at = models.DateTimeField("date post was updated", auto_now=True)
class Meta:
verbose_name = "state"
verbose_name_plural = "states"
db_table = "states"
unique_together = ["country", "name"]
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class City(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country = models.OneToOneField(Country, on_delete=models.CASCADE, default=None)
state = models.OneToOneField(State, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField("date post was created", auto_now_add=True)
updated_at = models.DateTimeField("date post was updated", auto_now=True)
class Meta:
verbose_name = "city"
verbose_name_plural = "cities"
db_table = "cities"
unique_together = ["country", "state", "name"]
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class Location(models.Model):
name = models.CharField(max_length=50, default=None)
slug = AutoSlugField(populate_from=["name"])
street = models.CharField(max_length=100)
additional = models.CharField(max_length=100)
country = models.OneToOneField(State, on_delete=models.CASCADE, related_name="countries")
state = models.OneToOneField(State, on_delete=models.CASCADE, related_name="states")
city = models.OneToOneField(City, on_delete=models.CASCADE, related_name="cities")
zip = models.CharField(max_length=30)
phone = models.CharField(max_length=15)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at")
class Meta:
verbose_name = "location"
verbose_name_plural = "locations"
db_table = "locations"
ordering = ["zip"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
This is my Location models.py:
from django.db import models
from django_extensions.db.fields import AutoSlugField
class Country(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country_code = models.CharField(max_length=5)
dial_code = models.CharField(max_length=5)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "country"
verbose_name_plural = "countries"
db_table = "countries"
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class State(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country = models.OneToOneField(Country, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField("date post was created", auto_now_add=True)
updated_at = models.DateTimeField("date post was updated", auto_now=True)
class Meta:
verbose_name = "state"
verbose_name_plural = "states"
db_table = "states"
unique_together = ["country", "name"]
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class City(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(populate_from=["name"])
country = models.OneToOneField(Country, on_delete=models.CASCADE, default=None)
state = models.OneToOneField(State, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField("date post was created", auto_now_add=True)
updated_at = models.DateTimeField("date post was updated", auto_now=True)
class Meta:
verbose_name = "city"
verbose_name_plural = "cities"
db_table = "cities"
unique_together = ["country", "state", "name"]
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
class Location(models.Model):
name = models.CharField(max_length=50, default=None)
slug = AutoSlugField(populate_from=["name"])
street = models.CharField(max_length=100)
additional = models.CharField(max_length=100)
country = models.OneToOneField(State, on_delete=models.CASCADE, related_name="countries")
state = models.OneToOneField(State, on_delete=models.CASCADE, related_name="states")
city = models.OneToOneField(City, on_delete=models.CASCADE, related_name="cities")
zip = models.CharField(max_length=30)
phone = models.CharField(max_length=15)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at")
class Meta:
verbose_name = "location"
verbose_name_plural = "locations"
db_table = "locations"
ordering = ["zip"]
def __str__(self):
return self.name
def get_absolute_url(self):
return self.slug
Here are the Location serializers which are ordinary modelserializers:
from rest_framework import serializers
from .models import *
from profiles.models import ProfileLocation
class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = [
"id",
"name",
"country_code",
"dial_code",
"created_at",
"updated_at",
]
class StateSerializer(serializers.ModelSerializer):
class Meta:
model = State
fields = [
"id",
"name",
"country",
"created_at",
"updated_at",
]
class CitySerializer(serializers.ModelSerializer):
class Meta:
model = City
fields = [
"id",
"name",
"country",
"state",
"created_at",
"updated_at",
]
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = [
"name",
"street",
"additional",
"zip",
"city",
"phone",
"created_at",
"updated_at",
]
class ProfileLocationSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ProfileLocation
fields =[
"location"
"profile"
]
and the profile serializer:
from rest_framework import serializers
from .models import *
from locations.serializers import ProfileLocationSerializer
class ProfileSerializer(serializers.ModelSerializer):
location = ProfileLocationSerializer()
class Meta:
model = Profile
fields = [
"background",
"photo",
"first_name",
"middle_name",
"last_name",
"birthdate",
"gender",
"bio",
"languages",
"is_verified",
"verification",
"location",
"website",
"user",
"created_at",
"updated_at",
]
def create(self, validated_data):
new_profile = Profile.objects.create(**validated_data)
return new_profile
This view creates the profile without any problems but excludes the location obviously.
class ProfileViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated]
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
Thank you in advance
| [
"your procedure is perfect, just need to override the create method of the serializer\ndef create(self, validated_data):\n # for better understand print or log the validated_data\n location_data = validated_data.pop('location') # all location data will be poped from the validated data as a dict\n # create a location object\n location_obj = Location.objects.create(**location_data)\n location_obj.save()\n # then add the location object in profile obj\n new_profile = Profile.objects.create(**validated_data, location=location_ojb)\n new_profile.save()\n return new_profile\n\nplease go through the official doc\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074668588_django_django_rest_framework_python.txt |
Q:
discord.py interaction error message not working
I'm trying to make an error handler with a command and it gives the user an ephermal message saying Invalid language but I get the following traceback (Below the code). I might be doing something wrong in the interaction argument (I'm new to the whole interaction thing and I'm trying it out)
@client.hybrid_command(name = "translate", with_app_command=True, description="Google translate a message to a language", aliases=["tr"])
@commands.guild_only()
async def translate(ctx, interaction: discord.Interaction, language, *, message):
language = language.lower()
if language not in googletrans.LANGUAGES and language not in googletrans.LANGCODES:
await interaction.response.send_message("Invalid Language. Try Again.", ephemeral=True)
Traceback (most recent call last):
File "/home/container/main.py", line 400, in <module>
async def translate(ctx, interaction: discord.Interaction, language, *, message):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 289, in decorator
result = hybrid_command(name=name, *args, with_app_command=with_app_command, **kwargs)(func)
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/hybrid.py", line 888, in decorator
return HybridCommand(func, name=name, with_app_command=with_app_command, **attrs) # type: ignore # ???
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/hybrid.py", line 509, in __init__
HybridAppCommand(self) if self.with_app_command else None
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/hybrid.py", line 306, in __init__
super().__init__(
File "/home/container/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 677, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/container/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 393, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "/home/container/.local/lib/python3.9/site-packages/discord/app_commands/transformers.py", line 828, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
File "/home/container/.local/lib/python3.9/site-packages/discord/app_commands/transformers.py", line 787, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
sys:1: RuntimeWarning: coroutine 'Command.__call__' was never awaited
A:
You cannot have both ctx and interaction in hybrid command callback, you can only have ctx, which is a Context object.
You can fix this by removing the interaction from the callback argument.
async def translate(ctx, language, *, message):
| discord.py interaction error message not working | I'm trying to make an error handler with a command and it gives the user an ephermal message saying Invalid language but I get the following traceback (Below the code). I might be doing something wrong in the interaction argument (I'm new to the whole interaction thing and I'm trying it out)
@client.hybrid_command(name = "translate", with_app_command=True, description="Google translate a message to a language", aliases=["tr"])
@commands.guild_only()
async def translate(ctx, interaction: discord.Interaction, language, *, message):
language = language.lower()
if language not in googletrans.LANGUAGES and language not in googletrans.LANGCODES:
await interaction.response.send_message("Invalid Language. Try Again.", ephemeral=True)
Traceback (most recent call last):
File "/home/container/main.py", line 400, in <module>
async def translate(ctx, interaction: discord.Interaction, language, *, message):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 289, in decorator
result = hybrid_command(name=name, *args, with_app_command=with_app_command, **kwargs)(func)
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/hybrid.py", line 888, in decorator
return HybridCommand(func, name=name, with_app_command=with_app_command, **attrs) # type: ignore # ???
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/hybrid.py", line 509, in __init__
HybridAppCommand(self) if self.with_app_command else None
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/hybrid.py", line 306, in __init__
super().__init__(
File "/home/container/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 677, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/container/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 393, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "/home/container/.local/lib/python3.9/site-packages/discord/app_commands/transformers.py", line 828, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
File "/home/container/.local/lib/python3.9/site-packages/discord/app_commands/transformers.py", line 787, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
sys:1: RuntimeWarning: coroutine 'Command.__call__' was never awaited
| [
"You cannot have both ctx and interaction in hybrid command callback, you can only have ctx, which is a Context object.\nYou can fix this by removing the interaction from the callback argument.\nasync def translate(ctx, language, *, message):\n\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074669450_discord_discord.py_python.txt |
Q:
giving precedence to arithmetic operators in python3
I am implementing a simple arithmetic calculation on a server which includes add, sub, mul and Div, for the simplicity purposes no other operations are being done and also no parentheses "()" to change the precedence. The input I will have for the client is something like "1-2.1+3.6*5+10/2"(no dot product, 2.1 or 3.6 is a floating number). I have created a function to send the operands and operators but at a time I can send udp message of 1 computation in the format of (num1,op,num2)
import struct
import socket
ip = "127.0.0.1"
port = 11200
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) #creating socket
print("Do Ctrl+c to exit the program !!")
def sendRecv( num1, op, num2):
#sending udp message with num1,op and num
#receiving udp message with the result as res
res = s.recieve()
return res
sendRecv(in1, in_op, in2)
I was able to split the operators and operands using the regular split and separated them like
str = ['1', '-', '2.1', '+', '3.6', '*', '5', '+', '10', '/', '2']
since the multiplication and the division takes precedence over addition and subtraction (3.6, *, 5) should be sent first followed by the division, I am trying to write a while loop with while(len(str>0)), I am trying to understand how I can send multiplication first, store the intermediate result in the list itself and do a recurring function till all the computations are sent through message. I am not allowed to perform ny operation on client side, I can only send values to "SendRecv()". Any suggestions or ideas on how to proceed will be helpful.
Thanks in advance
A:
Recursively split the expression according to operator precedence:
def do_calc(num1, op, num2):
# Stub to represent the server call that performs one operation.
# Note that actually using eval() in your backend is REALLY BAD.
expr = f"{num1} {op} {num2}"
res = str(eval(expr))
print(expr, "=", res)
return res
def calc_loop(tokens):
if len(tokens) == 1:
return tokens[0]
if len(tokens) == 3:
return do_calc(*tokens)
for ops in "-+", "/*":
if any(op in tokens for op in ops):
op_idx = max(tokens.index(op) for op in ops if op in tokens)
return calc_loop([
calc_loop(tokens[:op_idx]),
tokens[op_idx],
calc_loop(tokens[op_idx+1:]),
])
expr = ['1', '-', '2.1', '+', '3.6', '*', '5', '+', '10', '/', '2']
print(' '.join(expr), '=', calc_loop(expr))
prints:
1 - 2.1 = -1.1
3.6 * 5 = 18.0
10 / 2 = 5.0
18.0 + 5.0 = 23.0
-1.1 + 23.0 = 21.9
1 - 2.1 + 3.6 * 5 + 10 / 2 = 21.9
A:
Arrange to process only specific operands in a given pass. Make multiple passes, each with different sets of operators. Splice in the answers as they happen.
def doWork(lst, ops):
lst = list(lst)
idx = 0
while idx < len(lst):
if lst[i] in ops:
lst[idx-1:idx+2] = sendRecv(*lst[idx-1:idx+2])
else:
idx += 1
return lst
results = doWork(str, '*/')
results = doWork(results, '+-')
results = results[0]
A:
A typical use case for the classic shunting yard algorithm :
# operators and their precedences
ops = { '*': 2, '/': 2, '+': 1, '-': 1,}
# evaluate a stream of tokens
def evaluate(tokens):
vstack = []
ostack = []
def step():
v2 = vstack.pop()
v1 = vstack.pop()
op = ostack.pop()
vstack.append(sendRecv(v1, op, v2))
for tok in tokens:
if tok in ops:
if ostack and ops[ostack[-1]] >= ops[tok]:
step()
ostack.append(tok)
else:
vstack.append(tok)
while ostack:
step()
return vstack.pop()
# simulate the conversation with the server
def sendRecv(v1, op, v2):
res = eval(f'{v1} {op} {v2}')
return res
s = '3 + 4 * 2 + 3 / 5 + 6'
print(eval(s))
print(evaluate(s.split()))
| giving precedence to arithmetic operators in python3 | I am implementing a simple arithmetic calculation on a server which includes add, sub, mul and Div, for the simplicity purposes no other operations are being done and also no parentheses "()" to change the precedence. The input I will have for the client is something like "1-2.1+3.6*5+10/2"(no dot product, 2.1 or 3.6 is a floating number). I have created a function to send the operands and operators but at a time I can send udp message of 1 computation in the format of (num1,op,num2)
import struct
import socket
ip = "127.0.0.1"
port = 11200
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) #creating socket
print("Do Ctrl+c to exit the program !!")
def sendRecv( num1, op, num2):
#sending udp message with num1,op and num
#receiving udp message with the result as res
res = s.recieve()
return res
sendRecv(in1, in_op, in2)
I was able to split the operators and operands using the regular split and separated them like
str = ['1', '-', '2.1', '+', '3.6', '*', '5', '+', '10', '/', '2']
since the multiplication and the division takes precedence over addition and subtraction (3.6, *, 5) should be sent first followed by the division, I am trying to write a while loop with while(len(str>0)), I am trying to understand how I can send multiplication first, store the intermediate result in the list itself and do a recurring function till all the computations are sent through message. I am not allowed to perform ny operation on client side, I can only send values to "SendRecv()". Any suggestions or ideas on how to proceed will be helpful.
Thanks in advance
| [
"Recursively split the expression according to operator precedence:\ndef do_calc(num1, op, num2):\n # Stub to represent the server call that performs one operation.\n # Note that actually using eval() in your backend is REALLY BAD.\n expr = f\"{num1} {op} {num2}\" \n res = str(eval(expr))\n print(expr, \"=\", res)\n return res\n\ndef calc_loop(tokens):\n if len(tokens) == 1:\n return tokens[0]\n if len(tokens) == 3:\n return do_calc(*tokens)\n for ops in \"-+\", \"/*\":\n if any(op in tokens for op in ops):\n op_idx = max(tokens.index(op) for op in ops if op in tokens)\n return calc_loop([\n calc_loop(tokens[:op_idx]),\n tokens[op_idx],\n calc_loop(tokens[op_idx+1:]),\n ])\n\nexpr = ['1', '-', '2.1', '+', '3.6', '*', '5', '+', '10', '/', '2']\nprint(' '.join(expr), '=', calc_loop(expr))\n\nprints:\n1 - 2.1 = -1.1\n3.6 * 5 = 18.0\n10 / 2 = 5.0\n18.0 + 5.0 = 23.0\n-1.1 + 23.0 = 21.9\n1 - 2.1 + 3.6 * 5 + 10 / 2 = 21.9\n\n",
"Arrange to process only specific operands in a given pass. Make multiple passes, each with different sets of operators. Splice in the answers as they happen.\ndef doWork(lst, ops):\n lst = list(lst)\n idx = 0\n while idx < len(lst):\n if lst[i] in ops:\n lst[idx-1:idx+2] = sendRecv(*lst[idx-1:idx+2])\n else:\n idx += 1\n return lst\n\nresults = doWork(str, '*/')\nresults = doWork(results, '+-')\nresults = results[0]\n\n\n",
"A typical use case for the classic shunting yard algorithm :\n# operators and their precedences\nops = { '*': 2, '/': 2, '+': 1, '-': 1,}\n\n# evaluate a stream of tokens\ndef evaluate(tokens):\n vstack = []\n ostack = []\n\n def step():\n v2 = vstack.pop()\n v1 = vstack.pop()\n op = ostack.pop()\n vstack.append(sendRecv(v1, op, v2))\n\n for tok in tokens:\n if tok in ops:\n if ostack and ops[ostack[-1]] >= ops[tok]:\n step()\n ostack.append(tok)\n else:\n vstack.append(tok)\n\n while ostack:\n step()\n\n return vstack.pop()\n\n# simulate the conversation with the server\ndef sendRecv(v1, op, v2):\n res = eval(f'{v1} {op} {v2}')\n return res\n\ns = '3 + 4 * 2 + 3 / 5 + 6'\n\nprint(eval(s))\nprint(evaluate(s.split()))\n\n"
] | [
1,
1,
1
] | [] | [] | [
"list",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074668808_list_python_python_3.x_sorting.txt |
Q:
python sql table with paramter to json
Good Day!
I am trying to conver sql query into json with python, but getting an error when try to use sql query with a paramater:
sql syntax error: incorrect syntax near "%"
it works ok without setting paramater
My db is hana and module is hdbcli
my code
def db(db_name="xxx"):
return dbapi.connect(address=db_name, port="xx", user="xx", password="123")
def query_db(query, args=(), one=False):
cur = db().cursor()
cur.execute(query, args)
r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
cur.connection.close()
return (r[0] if r else None) if one else r
def test(request):
my_query = query_db("select bname, name_text from addrs where num=%s", (100,))
return JsonResponse(my_query, safe=False)
urlpatterns = [
path('s4d/', test),
]
thanks
A:
hana with hdbdcli uses :placeholder for prepared statements
some mpre infrmation can be found
my_query = query_db("select bname, name_text from addrs where num=:num", {"num": 100})
you use for two parameter
where id=:id and c2= :c2
{"id": id, "c2": c2}
| python sql table with paramter to json | Good Day!
I am trying to conver sql query into json with python, but getting an error when try to use sql query with a paramater:
sql syntax error: incorrect syntax near "%"
it works ok without setting paramater
My db is hana and module is hdbcli
my code
def db(db_name="xxx"):
return dbapi.connect(address=db_name, port="xx", user="xx", password="123")
def query_db(query, args=(), one=False):
cur = db().cursor()
cur.execute(query, args)
r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
cur.connection.close()
return (r[0] if r else None) if one else r
def test(request):
my_query = query_db("select bname, name_text from addrs where num=%s", (100,))
return JsonResponse(my_query, safe=False)
urlpatterns = [
path('s4d/', test),
]
thanks
| [
"hana with hdbdcli uses :placeholder for prepared statements\nsome mpre infrmation can be found\nmy_query = query_db(\"select bname, name_text from addrs where num=:num\", {\"num\": 100})\n\nyou use for two parameter\nwhere id=:id and c2= :c2\n{\"id\": id, \"c2\": c2}\n\n"
] | [
0
] | [] | [] | [
"django",
"hana",
"json",
"python",
"sql"
] | stackoverflow_0074669302_django_hana_json_python_sql.txt |
Q:
Discord py 2.0 interaction option
Discord 2.0 Py\
@bot.tree.command()
@app_commands.describe(amount="Please give amount")
async def clear(interaction: discord.Interaction, amount: int):
await interaction.response.send_message(f"You clean {amount} message", ephemeral=True)
await interaction.channel.purge(limit=amount)
Hello this is my code. All good, but i want do this command an option. So i mean command can non required ? Can user give a empty argument ?
A:
You can make the option not required by setting a default value for it, and the library will make it optional for you.
# set the default value for the "amount" argument to 1; if the user doesn't input the option, the argument will be 1.
async def clear(interaction: discord.Interaction, amount: int = 1):
You can look at the official example here.
| Discord py 2.0 interaction option | Discord 2.0 Py\
@bot.tree.command()
@app_commands.describe(amount="Please give amount")
async def clear(interaction: discord.Interaction, amount: int):
await interaction.response.send_message(f"You clean {amount} message", ephemeral=True)
await interaction.channel.purge(limit=amount)
Hello this is my code. All good, but i want do this command an option. So i mean command can non required ? Can user give a empty argument ?
| [
"You can make the option not required by setting a default value for it, and the library will make it optional for you.\n# set the default value for the \"amount\" argument to 1; if the user doesn't input the option, the argument will be 1.\nasync def clear(interaction: discord.Interaction, amount: int = 1):\n\nYou can look at the official example here.\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074669206_discord_discord.py_python.txt |
Q:
Visual Studio Code Jupyter not recognising conda kernel
I created a new conda environment named 'ct' and installed Python 3.10.6, Jupyter Lab, matplotlib and numpy. Also the ipykernel is installed.
VS Code lets me select Python 3.10.6 from 'ct' as interpreter without issues.
VS Code select interpreter
But I cannot choose 'ct' as kernel as VS Code only suggests the 'base' kernel from conda. 'base' does not have the desired packages installed which leads to the following error when running this code:
import matplotlib as mat
print(mat.__version__)
error:
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Untitled-1.ipynb Cell 1 in <cell line: 1>()
----> 1 import matplotlib as mat
2 print(mat.__version__)
ModuleNotFoundError: No module named 'matplotlib'
This is actually totally fine but I don't get why the 'ct' kernel is not showing up in the list when trying to change the kernel.
Cannot choose kernel
Also when running jupyter lab in browser from 'ct' environment everything is working as should.
When listing all installed packages in 'ct' in the VS Code terminal all packages show up.
Restarting VS Code and trying with other new conda environments does not help the issue.
Did I somehow miss something?
A:
What finally worked out for me was closing VS Code entirely, recreating the environment and creating a new blank notebook in VS Code. Now the kernel shows up and is surprisingly available for all new and old notebooks.
I also found this option in the Jupyter settings in VS Code: https://i.stack.imgur.com/rcJU6.png
I haven't tried it yet, but it might be helpful to someone experiencing similar issues.
Also Zac's solution above might be super helpful. Thank you for sharing!
A:
Switching to the "pre-release" version of the Jupyter extension immediately solved this problem for me.
A:
I solved this issue by opening the directory in VS Code, instead of only the .ipynb file.
A:
Obviously, this is not a universal problem.
You can read the docs and recreate the conda environment.
This may also be related to the fact that your conda environment is not activated. Use the command conda activate ct to activate it.
A:
Try this conda install -n meta_ai ipykernel --update-deps --force-reinstall
Somehow it solved my problems.
If it still can't solve your problem, try also opening the directory in VS Code, instead of only the .ipynb file.
A:
Try this conda install -n meta_ai ipykernel --update-deps --force-reinstall Somehow it solved my problems. If it still can't solve your problem, try also opening the directory in VS Code, instead of only the .ipynb file.
| Visual Studio Code Jupyter not recognising conda kernel | I created a new conda environment named 'ct' and installed Python 3.10.6, Jupyter Lab, matplotlib and numpy. Also the ipykernel is installed.
VS Code lets me select Python 3.10.6 from 'ct' as interpreter without issues.
VS Code select interpreter
But I cannot choose 'ct' as kernel as VS Code only suggests the 'base' kernel from conda. 'base' does not have the desired packages installed which leads to the following error when running this code:
import matplotlib as mat
print(mat.__version__)
error:
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Untitled-1.ipynb Cell 1 in <cell line: 1>()
----> 1 import matplotlib as mat
2 print(mat.__version__)
ModuleNotFoundError: No module named 'matplotlib'
This is actually totally fine but I don't get why the 'ct' kernel is not showing up in the list when trying to change the kernel.
Cannot choose kernel
Also when running jupyter lab in browser from 'ct' environment everything is working as should.
When listing all installed packages in 'ct' in the VS Code terminal all packages show up.
Restarting VS Code and trying with other new conda environments does not help the issue.
Did I somehow miss something?
| [
"What finally worked out for me was closing VS Code entirely, recreating the environment and creating a new blank notebook in VS Code. Now the kernel shows up and is surprisingly available for all new and old notebooks.\nI also found this option in the Jupyter settings in VS Code: https://i.stack.imgur.com/rcJU6.png\nI haven't tried it yet, but it might be helpful to someone experiencing similar issues.\nAlso Zac's solution above might be super helpful. Thank you for sharing!\n",
"Switching to the \"pre-release\" version of the Jupyter extension immediately solved this problem for me.\n",
"I solved this issue by opening the directory in VS Code, instead of only the .ipynb file.\n",
"\nObviously, this is not a universal problem.\nYou can read the docs and recreate the conda environment.\nThis may also be related to the fact that your conda environment is not activated. Use the command conda activate ct to activate it.\n",
"Try this conda install -n meta_ai ipykernel --update-deps --force-reinstall\nSomehow it solved my problems.\nIf it still can't solve your problem, try also opening the directory in VS Code, instead of only the .ipynb file.\n",
"Try this conda install -n meta_ai ipykernel --update-deps --force-reinstall Somehow it solved my problems. If it still can't solve your problem, try also opening the directory in VS Code, instead of only the .ipynb file.\n"
] | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"conda",
"jupyter",
"kernel",
"python",
"visual_studio_code"
] | stackoverflow_0074028297_conda_jupyter_kernel_python_visual_studio_code.txt |
Q:
Change model representation in Flask-Admin without modifying model
I have a model with a __repr__ method, which is used for display in Flask-Admin. I want to display a different value, but don't want to change the model. I found this answer, but that still requires modifying the model. How can I specify a separate representation for Flask-Admin?
class MyModel(db.Model):
data = db.Column(db.Integer)
def __repr__(self):
return '<MyModel: data=%s>' % self.data
Update
File: models.py
class Parent(db.Model):
__tablename__ = "parent"
id = db.Column(db.Integer, primary_key=True)
p_name = db.Column(db.Text)
children = db.relationship('Child', backref='child', lazy='dynamic')
def __repr__(self):
return '<Parent: name=%s' % self.p_name
class Child(db.Model):
__tablename__ = "child"
id = db.Column(db.Integer, primary_key=True)
c_name = db.Column(db.Text)
parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
File: admin.py
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from app import app, db
from models import Parent, Child
admin = Admin(app, 'My App')
admin.add_view(ModelView(Parent, db.session))
admin.add_view(ModelView(Child, db.session))
When I try to create or edit "child" through admin panel, I see representation from "Parent" class. I suppose it is because of relationship and I don't know how to redefine the representation for admin panel only.
A:
The following answers have helped me to solve my issue:
How to tell flask-admin to use alternative representation when displaying Foreign Key Fields?
Flask-admin, editing relationship giving me object representation of Foreign Key object
Flask-Admin Many-to-Many field display
The cause was in that I tried to replace __repr__ with __unicode__ instead just add __unicode__ method.
But if anybody knows solution without modifying models, let me know and I'll add it here.
A:
You could subclass the model:
class MyNewModel(MyModel):
def __repr__(self):
return '<MyModel: DATA IS %d!>' % self.data
and then use MyNewModel instead of MyModel.
A:
I have the same problem and I've found this solve:
class Child(Parent):
def __repr__(self):
return '<Child: name=%s' % self.p_name
setattr(Parent, '__repr__', Child.__repr__)
It overloads Parent.__repr__, but now you can not to change SQLA model.
| Change model representation in Flask-Admin without modifying model | I have a model with a __repr__ method, which is used for display in Flask-Admin. I want to display a different value, but don't want to change the model. I found this answer, but that still requires modifying the model. How can I specify a separate representation for Flask-Admin?
class MyModel(db.Model):
data = db.Column(db.Integer)
def __repr__(self):
return '<MyModel: data=%s>' % self.data
Update
File: models.py
class Parent(db.Model):
__tablename__ = "parent"
id = db.Column(db.Integer, primary_key=True)
p_name = db.Column(db.Text)
children = db.relationship('Child', backref='child', lazy='dynamic')
def __repr__(self):
return '<Parent: name=%s' % self.p_name
class Child(db.Model):
__tablename__ = "child"
id = db.Column(db.Integer, primary_key=True)
c_name = db.Column(db.Text)
parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
File: admin.py
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from app import app, db
from models import Parent, Child
admin = Admin(app, 'My App')
admin.add_view(ModelView(Parent, db.session))
admin.add_view(ModelView(Child, db.session))
When I try to create or edit "child" through admin panel, I see representation from "Parent" class. I suppose it is because of relationship and I don't know how to redefine the representation for admin panel only.
| [
"The following answers have helped me to solve my issue:\n\nHow to tell flask-admin to use alternative representation when displaying Foreign Key Fields?\nFlask-admin, editing relationship giving me object representation of Foreign Key object\nFlask-Admin Many-to-Many field display\n\nThe cause was in that I tried to replace __repr__ with __unicode__ instead just add __unicode__ method.\nBut if anybody knows solution without modifying models, let me know and I'll add it here.\n",
"You could subclass the model:\nclass MyNewModel(MyModel):\n def __repr__(self):\n return '<MyModel: DATA IS %d!>' % self.data\n\nand then use MyNewModel instead of MyModel.\n",
"I have the same problem and I've found this solve:\nclass Child(Parent):\ndef __repr__(self):\n return '<Child: name=%s' % self.p_name\n\nsetattr(Parent, '__repr__', Child.__repr__)\n\nIt overloads Parent.__repr__, but now you can not to change SQLA model.\n"
] | [
1,
0,
0
] | [] | [] | [
"flask",
"flask_admin",
"python"
] | stackoverflow_0037031399_flask_flask_admin_python.txt |
Q:
Python Quandl giving me error
So I have a bit of code in python which tries to get home prices from zillow. I am following the documentation exactly but I still get errors. The code:
import quandl
quandl.ApiConfig.api_key = "I have a key here in the code"
data = quandl.get("http://www.quandl.com/api/v3/datasets/ZILL/S00022_A.csv", returns="numpy")
This, however, returns:
raise ValueError(Message.ERROR_COLUMN_INDEX_TYPE % dataset)
ValueError: The column index must be expressed as an integer for http://www.quandl.com/api/v3/datasets/ZILL/S00022_A.csv.
What does this mean and how do I fix it? Thanks in advance.
A:
The code quandl.get() goes with the installed csv file and not an URL. So please import a dataset code and try to import it in your code by
quandl.get('WIKI/GOOGL')
Here, I have imported a dataset for stock prediction of Google
| Python Quandl giving me error | So I have a bit of code in python which tries to get home prices from zillow. I am following the documentation exactly but I still get errors. The code:
import quandl
quandl.ApiConfig.api_key = "I have a key here in the code"
data = quandl.get("http://www.quandl.com/api/v3/datasets/ZILL/S00022_A.csv", returns="numpy")
This, however, returns:
raise ValueError(Message.ERROR_COLUMN_INDEX_TYPE % dataset)
ValueError: The column index must be expressed as an integer for http://www.quandl.com/api/v3/datasets/ZILL/S00022_A.csv.
What does this mean and how do I fix it? Thanks in advance.
| [
"The code quandl.get() goes with the installed csv file and not an URL. So please import a dataset code and try to import it in your code by\nquandl.get('WIKI/GOOGL')\n\nHere, I have imported a dataset for stock prediction of Google\n"
] | [
0
] | [] | [] | [
"database",
"python",
"python_3.x",
"quandl",
"zillow"
] | stackoverflow_0046900561_database_python_python_3.x_quandl_zillow.txt |
Q:
How to show category names from a mysql database table in the dropdown list of django form
I am working on a article management platform webapp using django. I have created a registration form using the django form where I want to show category names from the category table.
This is the code to create category table where I have two column. One is cid which is ID and another one is category_name. Here the category name will be for example: Technology, Software engineering, Medicine etc.
blog.models.py
from django.db import models
# Create your models here.
class Category(models.Model):
cid = models.AutoField(primary_key=True, blank=True)
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name
The cid is a foreign key for users table because each user must select a category name from the specialization field to register an account in this app. As I am using built-in user model, so I have
added the cid as a foreign key in the user table as given below.
users/model.py
from django.db import models
from blog.models import Category
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
cid = models.ForeignKey(Category, on_delete=models.CASCADE)
in the forms.py file I have added the email and specialization field to display them in the registration form like below. However, I am not sure if the category code part is okay or not. could you please look into it?
users/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from blog.models import Category
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
category = Category()
cid = forms.CharField(label='Specialization', widget=forms.Select(choices=category.category_name))
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'cid']
This is register.html file:
register.html file
{% extends "users/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
{{ form| crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
I want to show the category names here in the specialization dropdown list which will be come from the cateogry table but those category names are not showing in the dropdown list.
Registration page UI
I am not understanding how to solve this problem. Could anyone help me out to solve this problem. What will be the coding part to solve this.
I tried to add category names in the specialization dropdown list but I failed.I want anyone to solve this problem
A:
First of all, category needs to be a field, not a class. Use ModelChoiceField for this.
| How to show category names from a mysql database table in the dropdown list of django form | I am working on a article management platform webapp using django. I have created a registration form using the django form where I want to show category names from the category table.
This is the code to create category table where I have two column. One is cid which is ID and another one is category_name. Here the category name will be for example: Technology, Software engineering, Medicine etc.
blog.models.py
from django.db import models
# Create your models here.
class Category(models.Model):
cid = models.AutoField(primary_key=True, blank=True)
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name
The cid is a foreign key for users table because each user must select a category name from the specialization field to register an account in this app. As I am using built-in user model, so I have
added the cid as a foreign key in the user table as given below.
users/model.py
from django.db import models
from blog.models import Category
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
cid = models.ForeignKey(Category, on_delete=models.CASCADE)
in the forms.py file I have added the email and specialization field to display them in the registration form like below. However, I am not sure if the category code part is okay or not. could you please look into it?
users/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from blog.models import Category
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
category = Category()
cid = forms.CharField(label='Specialization', widget=forms.Select(choices=category.category_name))
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'cid']
This is register.html file:
register.html file
{% extends "users/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
{{ form| crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
I want to show the category names here in the specialization dropdown list which will be come from the cateogry table but those category names are not showing in the dropdown list.
Registration page UI
I am not understanding how to solve this problem. Could anyone help me out to solve this problem. What will be the coding part to solve this.
I tried to add category names in the specialization dropdown list but I failed.I want anyone to solve this problem
| [
"First of all, category needs to be a field, not a class. Use ModelChoiceField for this.\n"
] | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"mysql",
"python"
] | stackoverflow_0074669516_django_django_forms_django_models_mysql_python.txt |
Q:
Error While Using Multiprocessing Library in Python
I am getting an error on Python when using the Multiprocessing library.
I have a list of 18,000 ids to collect via a GET from an external API (function update_events()) and then save each json file to blob storage in Azure . This would take a long time in a single-threaded environment so I decided to use a thread pool.
import logging
LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)
logging.getLogger(__name__).setLevel(logging.DEBUG)
import json
from Multiprocessing import Pool
def update_events(id:int):
try:
events = get_events(id) ### This is a GET to an external API
file_name = str(id) + '.json'
upsert_obj(file_name,'events',json.dumps(events))
except Exception:
LOGGER.error("Unable to write " + file_name + " to events folder")
### This command writes the file to Azure Blob Storage
def upsert_obj(file_name: str, container_name: str, sb_data: dict):
try:
blob_client = blob_service_client.get_blob_client(
container=PATH+"/"+str(container_name), blob=file_name)
blob_client.upload_blob(sb_data, overwrite=True)
LOGGER.info("Successfully upsert " +
file_name + " to " + container_name)
except Exception as e:
LOGGER.error(e)
## This is the multithreaded function
def get_data_multithreaded(new_ids:list):
with Pool(60) as p:
p.map(update_events,new_ids)
def collect_data(new_events_ids):
LOGGER.info('Starting collection...')
start_time = time.time()
get_data(new_events_ids)
LOGGER.info("--- %s seconds ---" % (time.time() - start_time))
So I open jupyter-notebook and type the following:
new_ids= [1234,4567,6789] # just an example, many more ids in reality
collect_data [new_ids]
And it works for the most part. However, at some point during the collection I hit an error:
UnboundLocalError: local variable 'file_name' referenced before assignment
As this is multi-threaded, I'm not very sure how or if I have error handled correctly. I'm also not sure if the error is coming from update_events() or upsert_obj(). As far as I know we are not hitting any rate limits on the API.
A:
Thanks @Axe319 for the solution, it looks like I need to initialize file_name before everything else, as in here:
def update_events(id:int):
try:
### Initialize first to ensure it's defined for error log
file_name = str(id) + '.json'
### If get_events errors out now, Exception will log properly
events = get_events(id)
upsert_obj(file_name,'events',json.dumps(events))
except Exception:
LOGGER.error("Unable to write " + file_name + " to events folder")
I can confirm this fixed the initial issue after writing the logs to a text file. The multithreaded approach confused me at first but I think I understand now.
| Error While Using Multiprocessing Library in Python | I am getting an error on Python when using the Multiprocessing library.
I have a list of 18,000 ids to collect via a GET from an external API (function update_events()) and then save each json file to blob storage in Azure . This would take a long time in a single-threaded environment so I decided to use a thread pool.
import logging
LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)
logging.getLogger(__name__).setLevel(logging.DEBUG)
import json
from Multiprocessing import Pool
def update_events(id:int):
try:
events = get_events(id) ### This is a GET to an external API
file_name = str(id) + '.json'
upsert_obj(file_name,'events',json.dumps(events))
except Exception:
LOGGER.error("Unable to write " + file_name + " to events folder")
### This command writes the file to Azure Blob Storage
def upsert_obj(file_name: str, container_name: str, sb_data: dict):
try:
blob_client = blob_service_client.get_blob_client(
container=PATH+"/"+str(container_name), blob=file_name)
blob_client.upload_blob(sb_data, overwrite=True)
LOGGER.info("Successfully upsert " +
file_name + " to " + container_name)
except Exception as e:
LOGGER.error(e)
## This is the multithreaded function
def get_data_multithreaded(new_ids:list):
with Pool(60) as p:
p.map(update_events,new_ids)
def collect_data(new_events_ids):
LOGGER.info('Starting collection...')
start_time = time.time()
get_data(new_events_ids)
LOGGER.info("--- %s seconds ---" % (time.time() - start_time))
So I open jupyter-notebook and type the following:
new_ids= [1234,4567,6789] # just an example, many more ids in reality
collect_data [new_ids]
And it works for the most part. However, at some point during the collection I hit an error:
UnboundLocalError: local variable 'file_name' referenced before assignment
As this is multi-threaded, I'm not very sure how or if I have error handled correctly. I'm also not sure if the error is coming from update_events() or upsert_obj(). As far as I know we are not hitting any rate limits on the API.
| [
"Thanks @Axe319 for the solution, it looks like I need to initialize file_name before everything else, as in here:\ndef update_events(id:int):\n try: \n ### Initialize first to ensure it's defined for error log\n file_name = str(id) + '.json' \n\n ### If get_events errors out now, Exception will log properly\n events = get_events(id) \n\n upsert_obj(file_name,'events',json.dumps(events))\n except Exception:\n LOGGER.error(\"Unable to write \" + file_name + \" to events folder\") \n\nI can confirm this fixed the initial issue after writing the logs to a text file. The multithreaded approach confused me at first but I think I understand now.\n"
] | [
1
] | [] | [] | [
"concurrency",
"multithreading",
"python",
"python_logging",
"python_multiprocessing"
] | stackoverflow_0074659662_concurrency_multithreading_python_python_logging_python_multiprocessing.txt |
Q:
input unicode character string ('u+2022') and output character
I have a Python program that uses a dictionary with Unicode number strings in it, then prints out the actual character. My code looks like this:
unicodeChars = {'bullet': 'u+2022'}
print(chr(unicodeChars['bullet']))
But I am receiving the following error:
TypeError: 'str' object cannot be interpreted as an integer
Can I solve this somehow?
A:
Take a look at the Unicode HOWTO. You will see that you really are looking for this instead:
unicodeChars = {'bullet': '\u2022'}
print(unicodeChars['bullet'])
| input unicode character string ('u+2022') and output character | I have a Python program that uses a dictionary with Unicode number strings in it, then prints out the actual character. My code looks like this:
unicodeChars = {'bullet': 'u+2022'}
print(chr(unicodeChars['bullet']))
But I am receiving the following error:
TypeError: 'str' object cannot be interpreted as an integer
Can I solve this somehow?
| [
"Take a look at the Unicode HOWTO. You will see that you really are looking for this instead:\nunicodeChars = {'bullet': '\\u2022'}\nprint(unicodeChars['bullet'])\n\n"
] | [
0
] | [] | [] | [
"list",
"python",
"python_3.x",
"python_unicode"
] | stackoverflow_0074669668_list_python_python_3.x_python_unicode.txt |
Q:
Adding new points to point cloud in real time - Open3D
I am using Open3D to visualize point clouds in Python. Essentially, what I want to do is add another point to the point cloud programmatically and then render it in real time.
This is what I have so far. I could not find any solution to this.
In the code below, I show one possible solution, but it is not effective. The points get added and a new window is opened as soon as the first one is closed. This is not what I want. I want it to dynamically show new points, without closing and opening again. As well as the fact that a new variable is created, which I think can be problematic when working with larger and larger data sets
import open3d as o3d
import numpy as np
#Create two random points
randomPoints = np.random.rand(2, 3)
pointSet = o3d.geometry.PointCloud()
pointSet.points = o3d.utility.Vector3dVector(randomPoints)
#Visualize the two random points
o3d.visualization.draw_geometries([pointSet])
#Here I want to add more points to the pointSet
#This solution does not work effective
#Create another random set
p1 = np.random.rand(3, 3)
p2 = np.concatenate((pointSet.points, p1), axis=0)
pointSet2 = o3d.geometry.PointCloud()
pointSet2.points = o3d.utility.Vector3dVector(p2)
o3d.visualization.draw_geometries([pointSet2])
Is there any possible solution to this?
If not, what other libraries can I look at that has the ability to render new incoming points in real time.
A:
In below page, it explains how to update visualizer without close the window.
http://www.open3d.org/docs/release/tutorial/visualization/non_blocking_visualization.html
Code may look like below:
// set up an new empty pcd
// init visualizer
// for loop :
//add new points into pcd
//visualizer update as sample code
//done
A:
New points can be added and visualized interactively to a PointCloud by extending PointCloud.points with the new coordinates.
This is because when we use numpy arrays, we need to create a Vector3dVector isntance which has the convenient method extend implemented. From the docs:
extend(*args, **kwargs)
Overloaded function.
extend(self: open3d.cpu.pybind.utility.Vector3dVector, L:
open3d.cpu.pybind.utility.Vector3dVector) -> None
Extend the list by appending all the items in the given list
extend(self: open3d.cpu.pybind.utility.Vector3dVector, L: Iterable) ->
None
Extend the list by appending all the items in the given list
So we can use different object instances e.g. ndarrays, Vector3dVector, lists etc.
A toy example and its result:
import open3d as o3d
import numpy as np
import time
# create visualizer and window.
vis = o3d.visualization.Visualizer()
vis.create_window(height=480, width=640)
# initialize pointcloud instance.
pcd = o3d.geometry.PointCloud()
# *optionally* add initial points
points = np.random.rand(10, 3)
pcd.points = o3d.utility.Vector3dVector(points)
# include it in the visualizer before non-blocking visualization.
vis.add_geometry(pcd)
# to add new points each dt secs.
dt = 0.01
# number of points that will be added
n_new = 10
previous_t = time.time()
# run non-blocking visualization.
# To exit, press 'q' or click the 'x' of the window.
keep_running = True
while keep_running:
if time.time() - previous_t > dt:
# Options (uncomment each to try them out):
# 1) extend with ndarrays.
pcd.points.extend(np.random.rand(n_new, 3))
# 2) extend with Vector3dVector instances.
# pcd.points.extend(
# o3d.utility.Vector3dVector(np.random.rand(n_new, 3)))
# 3) other iterables, e.g
# pcd.points.extend(np.random.rand(n_new, 3).tolist())
vis.update_geometry(pcd)
previous_t = time.time()
keep_running = vis.poll_events()
vis.update_renderer()
vis.destroy_window()
Why not create an updated geometry and remove the old one?
For completeness, other (which I believe to be not better) alternative approach could consist on the following steps:
Remove the current PointCloud
concatenate the new points as in the OP's question
Create new Pointcloud and add it to the visualizer.
This yields worse perfomance and barely allows interaction with the visualization.
To see this, let's have a look to the following comparison, with the same settings (code below). Both versions run the same time (~10 secs).
Using extend
Removing and creating PointCloud
✔️ Allows interaction
❌ Difficult interaction
Mean execution time (for adding points): 0.590 ms
Mean execution time (for adding points): 1.550 ms
Code to reproduce:
import open3d as o3d
import numpy as np
import time
# Global settings.
dt = 3e-2 # to add new points each dt secs.
t_total = 10 # total time to run this script.
n_new = 10 # number of points that will be added each iteration.
#---
# 1st, using extend. Run non-blocking visualization.
# create visualizer and window.
vis = o3d.visualization.Visualizer()
vis.create_window(height=480, width=640)
# initialize pointcloud instance.
pcd = o3d.geometry.PointCloud()
# *optionally* add initial points
points = np.random.rand(10, 3)
pcd.points = o3d.utility.Vector3dVector(points)
# include it in the visualizer before non-blocking visualization.
vis.add_geometry(pcd)
exec_times = []
current_t = time.time()
t0 = current_t
while current_t - t0 < t_total:
previous_t = time.time()
while current_t - previous_t < dt:
s = time.time()
# Options (uncomment each to try it out):
# 1) extend with ndarrays.
pcd.points.extend(np.random.rand(n_new, 3))
# 2) extend with Vector3dVector instances.
# pcd.points.extend(
# o3d.utility.Vector3dVector(np.random.rand(n_new, 3)))
# 3) other iterables, e.g
# pcd.points.extend(np.random.rand(n_new, 3).tolist())
vis.update_geometry(pcd)
current_t = time.time()
exec_times.append(time.time() - s)
vis.poll_events()
vis.update_renderer()
print(f"Using extend\t\t\t# Points: {len(pcd.points)},\n"
f"\t\t\t\t\t\tMean execution time:{np.mean(exec_times):.5f}")
vis.destroy_window()
# ---
# 2nd, using remove + create + add PointCloud. Run non-blocking visualization.
# create visualizer and window.
vis = o3d.visualization.Visualizer()
vis.create_window(height=480, width=640)
# initialize pointcloud instance.
pcd = o3d.geometry.PointCloud()
points = np.random.rand(10, 3)
pcd.points = o3d.utility.Vector3dVector(points)
vis.add_geometry(pcd)
exec_times = []
current_t = time.time()
t0 = current_t
previous_t = current_t
while current_t - t0 < t_total:
previous_t = time.time()
while current_t - previous_t < dt:
s = time.time()
# remove, create and add new geometry.
vis.remove_geometry(pcd)
pcd = o3d.geometry.PointCloud()
points = np.concatenate((points, np.random.rand(n_new, 3)))
pcd.points = o3d.utility.Vector3dVector(points)
vis.add_geometry(pcd)
current_t = time.time()
exec_times.append(time.time() - s)
current_t = time.time()
vis.poll_events()
vis.update_renderer()
print(f"Without using extend\t# Points: {len(pcd.points)},\n"
f"\t\t\t\t\t\tMean execution time:{np.mean(exec_times):.5f}")
vis.destroy_window()
| Adding new points to point cloud in real time - Open3D | I am using Open3D to visualize point clouds in Python. Essentially, what I want to do is add another point to the point cloud programmatically and then render it in real time.
This is what I have so far. I could not find any solution to this.
In the code below, I show one possible solution, but it is not effective. The points get added and a new window is opened as soon as the first one is closed. This is not what I want. I want it to dynamically show new points, without closing and opening again. As well as the fact that a new variable is created, which I think can be problematic when working with larger and larger data sets
import open3d as o3d
import numpy as np
#Create two random points
randomPoints = np.random.rand(2, 3)
pointSet = o3d.geometry.PointCloud()
pointSet.points = o3d.utility.Vector3dVector(randomPoints)
#Visualize the two random points
o3d.visualization.draw_geometries([pointSet])
#Here I want to add more points to the pointSet
#This solution does not work effective
#Create another random set
p1 = np.random.rand(3, 3)
p2 = np.concatenate((pointSet.points, p1), axis=0)
pointSet2 = o3d.geometry.PointCloud()
pointSet2.points = o3d.utility.Vector3dVector(p2)
o3d.visualization.draw_geometries([pointSet2])
Is there any possible solution to this?
If not, what other libraries can I look at that has the ability to render new incoming points in real time.
| [
"In below page, it explains how to update visualizer without close the window.\nhttp://www.open3d.org/docs/release/tutorial/visualization/non_blocking_visualization.html\nCode may look like below:\n// set up an new empty pcd\n// init visualizer\n// for loop :\n//add new points into pcd\n\n//visualizer update as sample code\n\n//done\n",
"New points can be added and visualized interactively to a PointCloud by extending PointCloud.points with the new coordinates.\nThis is because when we use numpy arrays, we need to create a Vector3dVector isntance which has the convenient method extend implemented. From the docs:\n\nextend(*args, **kwargs)\nOverloaded function.\n\nextend(self: open3d.cpu.pybind.utility.Vector3dVector, L:\nopen3d.cpu.pybind.utility.Vector3dVector) -> None\n\nExtend the list by appending all the items in the given list\n\nextend(self: open3d.cpu.pybind.utility.Vector3dVector, L: Iterable) ->\nNone\n\nExtend the list by appending all the items in the given list\n\nSo we can use different object instances e.g. ndarrays, Vector3dVector, lists etc.\nA toy example and its result:\n\nimport open3d as o3d\nimport numpy as np\nimport time\n\n\n# create visualizer and window.\nvis = o3d.visualization.Visualizer()\nvis.create_window(height=480, width=640)\n\n# initialize pointcloud instance.\npcd = o3d.geometry.PointCloud()\n# *optionally* add initial points\npoints = np.random.rand(10, 3)\npcd.points = o3d.utility.Vector3dVector(points)\n\n# include it in the visualizer before non-blocking visualization.\nvis.add_geometry(pcd)\n\n# to add new points each dt secs.\ndt = 0.01\n# number of points that will be added\nn_new = 10\n\nprevious_t = time.time()\n\n# run non-blocking visualization. \n# To exit, press 'q' or click the 'x' of the window.\nkeep_running = True\nwhile keep_running:\n \n if time.time() - previous_t > dt:\n # Options (uncomment each to try them out):\n # 1) extend with ndarrays.\n pcd.points.extend(np.random.rand(n_new, 3))\n \n # 2) extend with Vector3dVector instances.\n # pcd.points.extend(\n # o3d.utility.Vector3dVector(np.random.rand(n_new, 3)))\n \n # 3) other iterables, e.g\n # pcd.points.extend(np.random.rand(n_new, 3).tolist())\n \n vis.update_geometry(pcd)\n previous_t = time.time()\n\n keep_running = vis.poll_events()\n vis.update_renderer()\n\nvis.destroy_window()\n\n\nWhy not create an updated geometry and remove the old one?\nFor completeness, other (which I believe to be not better) alternative approach could consist on the following steps:\n\nRemove the current PointCloud\nconcatenate the new points as in the OP's question\nCreate new Pointcloud and add it to the visualizer.\n\nThis yields worse perfomance and barely allows interaction with the visualization.\nTo see this, let's have a look to the following comparison, with the same settings (code below). Both versions run the same time (~10 secs).\n\n\n\n\nUsing extend\nRemoving and creating PointCloud\n\n\n\n\n✔️ Allows interaction\n❌ Difficult interaction\n\n\n\n\n\n\nMean execution time (for adding points): 0.590 ms\nMean execution time (for adding points): 1.550 ms\n\n\n\n\nCode to reproduce:\nimport open3d as o3d\nimport numpy as np\nimport time\n\n# Global settings.\ndt = 3e-2 # to add new points each dt secs.\nt_total = 10 # total time to run this script.\nn_new = 10 # number of points that will be added each iteration.\n\n#---\n# 1st, using extend. Run non-blocking visualization.\n\n# create visualizer and window.\nvis = o3d.visualization.Visualizer()\nvis.create_window(height=480, width=640)\n\n# initialize pointcloud instance.\npcd = o3d.geometry.PointCloud()\n# *optionally* add initial points\npoints = np.random.rand(10, 3)\npcd.points = o3d.utility.Vector3dVector(points)\n# include it in the visualizer before non-blocking visualization.\nvis.add_geometry(pcd)\n\nexec_times = []\n\ncurrent_t = time.time()\nt0 = current_t\n\nwhile current_t - t0 < t_total:\n\n previous_t = time.time()\n\n while current_t - previous_t < dt:\n s = time.time()\n\n # Options (uncomment each to try it out):\n # 1) extend with ndarrays.\n pcd.points.extend(np.random.rand(n_new, 3))\n\n # 2) extend with Vector3dVector instances.\n # pcd.points.extend(\n # o3d.utility.Vector3dVector(np.random.rand(n_new, 3)))\n\n # 3) other iterables, e.g\n # pcd.points.extend(np.random.rand(n_new, 3).tolist())\n\n vis.update_geometry(pcd)\n\n current_t = time.time()\n exec_times.append(time.time() - s)\n\n vis.poll_events()\n vis.update_renderer()\n\nprint(f\"Using extend\\t\\t\\t# Points: {len(pcd.points)},\\n\"\n f\"\\t\\t\\t\\t\\t\\tMean execution time:{np.mean(exec_times):.5f}\")\n\nvis.destroy_window()\n\n# ---\n# 2nd, using remove + create + add PointCloud. Run non-blocking visualization.\n\n# create visualizer and window.\nvis = o3d.visualization.Visualizer()\nvis.create_window(height=480, width=640)\n\n# initialize pointcloud instance.\npcd = o3d.geometry.PointCloud()\npoints = np.random.rand(10, 3)\npcd.points = o3d.utility.Vector3dVector(points)\nvis.add_geometry(pcd)\n\nexec_times = []\n\ncurrent_t = time.time()\nt0 = current_t\nprevious_t = current_t\n\nwhile current_t - t0 < t_total:\n\n previous_t = time.time()\n\n while current_t - previous_t < dt:\n s = time.time()\n\n # remove, create and add new geometry.\n vis.remove_geometry(pcd)\n pcd = o3d.geometry.PointCloud()\n points = np.concatenate((points, np.random.rand(n_new, 3)))\n pcd.points = o3d.utility.Vector3dVector(points)\n vis.add_geometry(pcd)\n\n current_t = time.time()\n exec_times.append(time.time() - s)\n\n current_t = time.time()\n\n vis.poll_events()\n vis.update_renderer()\n\nprint(f\"Without using extend\\t# Points: {len(pcd.points)},\\n\"\n f\"\\t\\t\\t\\t\\t\\tMean execution time:{np.mean(exec_times):.5f}\")\n\nvis.destroy_window()\n\n"
] | [
0,
0
] | [] | [] | [
"numpy",
"open3d",
"python"
] | stackoverflow_0065774814_numpy_open3d_python.txt |
Q:
how do I overwrite text I've already written to the console?
I am trying to get this to
Read the text from screen #Working
Output the text #Working
Delete Output #Not working
Replace with Output every 5 second. #Not working as depended on prior
Can someone help?
I am trying to get this algo to read the screen every 5 seconds, but it seems to only do it once.
Any suggestions?
import time
import cv2
import mss
import numpy
import pytesseract
import matplotlib.pyplot as plt
import io
import pandas as pd
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
with mss.mss() as mss_instance:
mon = mss_instance.monitors[0]
screenshot = mss_instance.grab(mon)
with mss.mss() as sct:
while True:
im = numpy.asarray(sct.grab(mon))
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
text = pytesseract.image_to_string(im)
plt.show()
print(text)
time.sleep(5) # One screenshot per 5 seconds
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
continue
A:
So, your question really is "how to I overwrite text I've already written to the console?" There are two ways.
If there is only one line of text, just write a carriage return at the end instead of a newline. For example:
print(text, end='\r')
If there are multiple lines of text, you can clear the screen before writing:
os.system('cls')
print(text)
Note that "cls" is specifically for Windows, which is what you are using. If you intend this to be used on other operating systems, you would need something like:
if sys.platform == 'win32':
os.system('cls')
else:
os.system('clear')
| how do I overwrite text I've already written to the console? | I am trying to get this to
Read the text from screen #Working
Output the text #Working
Delete Output #Not working
Replace with Output every 5 second. #Not working as depended on prior
Can someone help?
I am trying to get this algo to read the screen every 5 seconds, but it seems to only do it once.
Any suggestions?
import time
import cv2
import mss
import numpy
import pytesseract
import matplotlib.pyplot as plt
import io
import pandas as pd
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
with mss.mss() as mss_instance:
mon = mss_instance.monitors[0]
screenshot = mss_instance.grab(mon)
with mss.mss() as sct:
while True:
im = numpy.asarray(sct.grab(mon))
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
text = pytesseract.image_to_string(im)
plt.show()
print(text)
time.sleep(5) # One screenshot per 5 seconds
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
continue
| [
"So, your question really is \"how to I overwrite text I've already written to the console?\" There are two ways.\nIf there is only one line of text, just write a carriage return at the end instead of a newline. For example:\n print(text, end='\\r')\n\nIf there are multiple lines of text, you can clear the screen before writing:\n os.system('cls')\n print(text)\n\nNote that \"cls\" is specifically for Windows, which is what you are using. If you intend this to be used on other operating systems, you would need something like:\n if sys.platform == 'win32':\n os.system('cls')\n else:\n os.system('clear')\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074646615_python.txt |
Q:
Snake Algorithm (active contour) in python
Find contour on the right side of the chest image as indicated with red circle and by using Python and scikit-image package for the image below
this is the image i have to process
to make it like this result:
the result must be like this
I don't know a lot of python thats why I need to know what I have to do
A:
To find the contour on the right side of the chest image, you can use the find_contours function from the scikit-image package. This function takes an image as input and returns a list of all the contours in the image.
Here is an example of how you can use this function to find the contour on the right side of the chest image:
from skimage import io
from skimage.color import rgb2gray
from skimage.filters import threshold_otsu
from skimage.measure import find_contours
# Load the image
image = io.imread('chest_image.png')
# Convert the image to grayscale
gray_image = rgb2gray(image)
# Apply thresholding to the image using Otsu's method
threshold = threshold_otsu(gray_image)
binary_image = gray_image > threshold
# Find the contours in the binary image
contours = find_contours(binary_image, 0.8)
# Select the contour on the right side of the chest
right_side_contour = contours[0]
# Plot the contour on the image
plt.imshow(image, cmap='gray')
plt.plot(right_side_contour[:, 1], right_side_contour[:, 0], linewidth=2)
plt.show()
This code will first load the chest image and convert it to grayscale. Then it will apply thresholding to the image using Otsu's method, which will create a binary image with the chest region being white and the background being black. Finally, it will use the find_contours function to find the contours in the binary image, select the contour on the right side of the chest, and plot it on the image.
You can further refine this code to select the contour on the right side of the chest more accurately, depending on the specific details of your image. For example, you can use the coordinates of the red circle in the image to determine which contour is the one on the right side of the chest.
| Snake Algorithm (active contour) in python | Find contour on the right side of the chest image as indicated with red circle and by using Python and scikit-image package for the image below
this is the image i have to process
to make it like this result:
the result must be like this
I don't know a lot of python thats why I need to know what I have to do
| [
"To find the contour on the right side of the chest image, you can use the find_contours function from the scikit-image package. This function takes an image as input and returns a list of all the contours in the image.\nHere is an example of how you can use this function to find the contour on the right side of the chest image:\nfrom skimage import io\nfrom skimage.color import rgb2gray\nfrom skimage.filters import threshold_otsu\nfrom skimage.measure import find_contours\n\n# Load the image\nimage = io.imread('chest_image.png')\n\n# Convert the image to grayscale\ngray_image = rgb2gray(image)\n\n# Apply thresholding to the image using Otsu's method\nthreshold = threshold_otsu(gray_image)\nbinary_image = gray_image > threshold\n\n# Find the contours in the binary image\ncontours = find_contours(binary_image, 0.8)\n\n# Select the contour on the right side of the chest\nright_side_contour = contours[0]\n\n# Plot the contour on the image\nplt.imshow(image, cmap='gray')\nplt.plot(right_side_contour[:, 1], right_side_contour[:, 0], linewidth=2)\nplt.show()\n\nThis code will first load the chest image and convert it to grayscale. Then it will apply thresholding to the image using Otsu's method, which will create a binary image with the chest region being white and the background being black. Finally, it will use the find_contours function to find the contours in the binary image, select the contour on the right side of the chest, and plot it on the image.\nYou can further refine this code to select the contour on the right side of the chest more accurately, depending on the specific details of your image. For example, you can use the coordinates of the red circle in the image to determine which contour is the one on the right side of the chest.\n"
] | [
1
] | [] | [] | [
"computer_vision",
"image_processing",
"python"
] | stackoverflow_0074669771_computer_vision_image_processing_python.txt |
Q:
How to find a random number in python
I have a random number and I want to create a bot that find it automatically but I'm stuck. Can you help me pls
I have these two variables:
a = random.randint(0,50)
b = 50
I want to make the bot find a using b.
I tried this but it's too long to make:
if b != a:
b = statistics.mean(0,b)
if b > a:
b = statistics.mean(0,b)
elif b < a:
min = b
b = statistics.mean(min,50)
elif b == a:
"GG"
A:
import random
a = random.randint(0,50)
b = 50
i = b//2
while b!=a:
if b<a:
b+=i
elif b>a:
b-=i
if i>1:
i//=2
print(a,b)
| How to find a random number in python | I have a random number and I want to create a bot that find it automatically but I'm stuck. Can you help me pls
I have these two variables:
a = random.randint(0,50)
b = 50
I want to make the bot find a using b.
I tried this but it's too long to make:
if b != a:
b = statistics.mean(0,b)
if b > a:
b = statistics.mean(0,b)
elif b < a:
min = b
b = statistics.mean(min,50)
elif b == a:
"GG"
| [
"import random\na = random.randint(0,50)\nb = 50\ni = b//2\nwhile b!=a:\n if b<a:\n b+=i\n elif b>a:\n b-=i \n if i>1:\n i//=2\nprint(a,b)\n\n"
] | [
2
] | [] | [] | [
"bots",
"python",
"random"
] | stackoverflow_0074669751_bots_python_random.txt |
Q:
A Python program to print the longest consecutive chain of words of the same length from a sentence
I got tasked with writing a Python script that would output the longest chain of consecutive words of the same length from a sentence. For example, if the input is "To be or not to be", the output should be "To, be, or".
text = input("Enter text: ")
words = text.replace(",", " ").replace(".", " ").split()
x = 0
same = []
same.append(words[x])
for i in words:
if len(words[x]) == len(words[x+1]):
same.append(words[x+1])
x += 1
elif len(words[x]) != len(words[x+1]):
same = []
x += 1
else:
print("No consecutive words of the same length")
print(words)
print("Longest chain of words with similar length: ", same)
In order to turn the string input into a list of words and to get rid of any punctuation, I used the replace() and split() methods. The first word of this list would then get appended to a new list called "same", which would hold the words with the same length. A for-loop would then compare the lengths of the words one by one, and either append them to this list if their lengths match, or clear the list if they don't.
if len(words[x]) == len(words[x+1]):
~~~~~^^^^^
IndexError: list index out of range
This is the problem I keep getting, and I just can't understand why the index is out of range.
I will be very grateful for any help with solving this issue and fixing the program. Thank you in advance.
A:
using groupby you can get the result as
from itertools import groupby
string = "To be or not to be"
sol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))
print(sol)
# 'To, be, or'
A:
len() function takes a string as an argument, for instance here in this code according to me first you have to convert the words variable into a list then it might work.
Thank You !!!
| A Python program to print the longest consecutive chain of words of the same length from a sentence | I got tasked with writing a Python script that would output the longest chain of consecutive words of the same length from a sentence. For example, if the input is "To be or not to be", the output should be "To, be, or".
text = input("Enter text: ")
words = text.replace(",", " ").replace(".", " ").split()
x = 0
same = []
same.append(words[x])
for i in words:
if len(words[x]) == len(words[x+1]):
same.append(words[x+1])
x += 1
elif len(words[x]) != len(words[x+1]):
same = []
x += 1
else:
print("No consecutive words of the same length")
print(words)
print("Longest chain of words with similar length: ", same)
In order to turn the string input into a list of words and to get rid of any punctuation, I used the replace() and split() methods. The first word of this list would then get appended to a new list called "same", which would hold the words with the same length. A for-loop would then compare the lengths of the words one by one, and either append them to this list if their lengths match, or clear the list if they don't.
if len(words[x]) == len(words[x+1]):
~~~~~^^^^^
IndexError: list index out of range
This is the problem I keep getting, and I just can't understand why the index is out of range.
I will be very grateful for any help with solving this issue and fixing the program. Thank you in advance.
| [
"using groupby you can get the result as\nfrom itertools import groupby\nstring = \"To be or not to be\"\nsol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))\nprint(sol)\n# 'To, be, or'\n\n",
"len() function takes a string as an argument, for instance here in this code according to me first you have to convert the words variable into a list then it might work.\nThank You !!!\n"
] | [
2,
0
] | [] | [] | [
"for_loop",
"list",
"python",
"string"
] | stackoverflow_0074669723_for_loop_list_python_string.txt |
Q:
Can't open label file. (This can be normal only if you use MSCOCO) YoloV4
I'm working with YoloV4 model object detection. I'm trying to train the custom dataset but I'm constantly getting this error line:
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Training file paths don't seem to match but I can't figure out how to fix that problem. I'm struggling for hours.
The command I'm trying to run the training process with:
!./darknet detector train data/obj.data cfg/custom-yolov4-detector.cfg yolov4.conv.137 -dont_show
And the train files and directories:
%cd /content/darknet/
%cp {dataset.location}/train/_classes.txt data/obj.names
%mkdir -p data/obj
#copy image and labels
%cp {dataset.location}/train/*.jpg data/obj/
%cp {dataset.location}/valid/*.jpg data/obj/
%cp {dataset.location}/train/*.txt data/obj/
%cp {dataset.location}/valid/*.txt data/obj/
with open('data/obj.data', 'w') as out:
out.write('classes = 2\n')
out.write('train = data/train.txt\n')
out.write('valid = data/valid.txt\n')
out.write('names = data/obj.names\n')
out.write('backup = backup/')
#write train file (just the image list)
import os
with open('data/train.txt', 'w') as out:
for img in [f for f in os.listdir(dataset.location + '/train') if f.endswith('jpg')]:
out.write('data/obj/' + img + '\n')
#write the valid file (just the image list)
import os
with open('data/valid.txt', 'w') as out:
for img in [f for f in os.listdir(dataset.location + '/valid') if f.endswith('jpg')]:
out.write('data/obj/' + img + '\n')
A:
Make sure that your labels(annotations) and the training image names are the same. If there is a difference between labels and image names, then it will cause this particular error. I had the same error when working with annotation files. For me, it happened when I had to convert from .png to .jpg and that changed the filename in the process.
| Can't open label file. (This can be normal only if you use MSCOCO) YoloV4 | I'm working with YoloV4 model object detection. I'm trying to train the custom dataset but I'm constantly getting this error line:
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Training file paths don't seem to match but I can't figure out how to fix that problem. I'm struggling for hours.
The command I'm trying to run the training process with:
!./darknet detector train data/obj.data cfg/custom-yolov4-detector.cfg yolov4.conv.137 -dont_show
And the train files and directories:
%cd /content/darknet/
%cp {dataset.location}/train/_classes.txt data/obj.names
%mkdir -p data/obj
#copy image and labels
%cp {dataset.location}/train/*.jpg data/obj/
%cp {dataset.location}/valid/*.jpg data/obj/
%cp {dataset.location}/train/*.txt data/obj/
%cp {dataset.location}/valid/*.txt data/obj/
with open('data/obj.data', 'w') as out:
out.write('classes = 2\n')
out.write('train = data/train.txt\n')
out.write('valid = data/valid.txt\n')
out.write('names = data/obj.names\n')
out.write('backup = backup/')
#write train file (just the image list)
import os
with open('data/train.txt', 'w') as out:
for img in [f for f in os.listdir(dataset.location + '/train') if f.endswith('jpg')]:
out.write('data/obj/' + img + '\n')
#write the valid file (just the image list)
import os
with open('data/valid.txt', 'w') as out:
for img in [f for f in os.listdir(dataset.location + '/valid') if f.endswith('jpg')]:
out.write('data/obj/' + img + '\n')
| [
"Make sure that your labels(annotations) and the training image names are the same. If there is a difference between labels and image names, then it will cause this particular error. I had the same error when working with annotation files. For me, it happened when I had to convert from .png to .jpg and that changed the filename in the process.\n"
] | [
0
] | [] | [] | [
"google_colaboratory",
"neural_network",
"python"
] | stackoverflow_0073652439_google_colaboratory_neural_network_python.txt |
Q:
Parenthesis in a recursive way (Python)
def paren(s, cnt=0):
if s == '':
return True
if s[0] == '(':
return paren(s[1:], cnt + 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
return cnt == 0
So this code works for all cases if there is the same number of "(" and ")".
But for example it doesn't work for "))(( ".
how can I modify the code for this to work that for every opening bracket there is a closing one, then it returns True.
A:
def paren(s):
_s = s.replace('()','')
if not _s:
return True
elif _s==s:
return False
return paren(_s)
print(paren(')()('))
A:
Check if at any point c < 0, and fix the return for when s == ''
def paren(s, cnt=0):
if c < 0: return False
elif s == '': return c == 0
elif s[0] == '(':
return paren(s[1:], cnt + 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
# here, there's a non-parentheses character. I'll assume you want to ignore these
# if they're impossible, just remove this line
return parent(s[1:], cnt)
A:
To check that for every opening bracket there is a closing bracket, you can simply check if the final value of cnt is 0. If it is, then it means that there was an equal number of opening and closing brackets, so the string is balanced. Here is one way you could modify the code to do this:
def paren(s, cnt=0):
if s == '':
# If the string is empty, return True if the count is 0,
# otherwise return False
return cnt == 0
if s[0] == '(':
# If the first character is an opening bracket, increment the count
return paren(s[1:], cnt + 1)
elif s[0] == ')':
# If the first character is a closing bracket, decrement the count
return paren(s[1:], cnt - 1)
# If the first character is neither an opening nor closing bracket,
# just recurse on the rest of the string
return paren(s[1:], cnt)
This code should work for the example you gave, "))(( ". When it reaches the first closing bracket, cnt will be decremented to -1. When it reaches the next closing bracket, cnt will be decremented again to -2. When it reaches the first opening bracket, cnt will be incremented to -1. Finally, when it reaches the last opening bracket, cnt will be incremented again to 0. When the string is empty, cnt will be 0, so the function will return True.
| Parenthesis in a recursive way (Python) | def paren(s, cnt=0):
if s == '':
return True
if s[0] == '(':
return paren(s[1:], cnt + 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
return cnt == 0
So this code works for all cases if there is the same number of "(" and ")".
But for example it doesn't work for "))(( ".
how can I modify the code for this to work that for every opening bracket there is a closing one, then it returns True.
| [
"def paren(s):\n _s = s.replace('()','')\n if not _s:\n return True\n elif _s==s:\n return False\n return paren(_s)\n\nprint(paren(')()('))\n\n",
"Check if at any point c < 0, and fix the return for when s == ''\ndef paren(s, cnt=0):\n if c < 0: return False\n elif s == '': return c == 0\n elif s[0] == '(':\n return paren(s[1:], cnt + 1)\n elif s[0] == ')':\n return paren(s[1:], cnt - 1)\n # here, there's a non-parentheses character. I'll assume you want to ignore these\n # if they're impossible, just remove this line\n return parent(s[1:], cnt)\n\n",
"To check that for every opening bracket there is a closing bracket, you can simply check if the final value of cnt is 0. If it is, then it means that there was an equal number of opening and closing brackets, so the string is balanced. Here is one way you could modify the code to do this:\ndef paren(s, cnt=0):\nif s == '':\n # If the string is empty, return True if the count is 0,\n # otherwise return False\n return cnt == 0\nif s[0] == '(':\n # If the first character is an opening bracket, increment the count\n return paren(s[1:], cnt + 1)\nelif s[0] == ')':\n # If the first character is a closing bracket, decrement the count\n return paren(s[1:], cnt - 1)\n# If the first character is neither an opening nor closing bracket,\n# just recurse on the rest of the string\nreturn paren(s[1:], cnt)\n\nThis code should work for the example you gave, \"))(( \". When it reaches the first closing bracket, cnt will be decremented to -1. When it reaches the next closing bracket, cnt will be decremented again to -2. When it reaches the first opening bracket, cnt will be incremented to -1. Finally, when it reaches the last opening bracket, cnt will be incremented again to 0. When the string is empty, cnt will be 0, so the function will return True.\n"
] | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074669803_python_python_3.x.txt |
Q:
Implementing an interface in python
I am pretty new to Python and couldn't understand the origin of this problem.
I'm trying to implement an interface, I have downloaded the zope.interface package, and imported it in my file like this
import zope.interface
Now when I write
class MyInterface(zope.interface.Interface)
I get this error:
"message": "Inheriting 'zope.interface.Interface', which is not a class."
but when I do
class MyInterface(zope.interface.interface.InterfaceClass):
it works fine.
I don't understand the difference.
A:
I am new to python too, but I will try to help using the little knowledge I have.
Actually I tested your code, and it works for me, it doesn't give me that error message. But concerning the difference between both statements, I wrote the following code to figure out the difference:
import zope.interface
class MyInterface(zope.interface.Interface):
pass
print(type(MyInterface))
class MyInterface1(zope.interface.interface.InterfaceClass):
pass
print(type(MyInterface1))
class TestClass:
pass
print(type(TestClass))
This code gave me this output:
<class 'zope.interface.interface.InterfaceClass'>
<class 'type'>
<class 'type'>
So to answer your question about the difference between the two statements, the first one, MyInterface, is a declaration of an interface which is, according to the official documentation is an instance of the zop.interface.interface.InterfaceClass.
MyInterface1, however,is a normal class (object of the mega class type, of which all classes are objects. As an exemple, TestClass is also an object of the mega class type), and it is just inheriting from the class zope.interface.interface.InterfaceClass
Of course this is just an educated guess, I am new to python interfaces and OOP myself, but I hope this at least helps answer your questions.
A:
I don't know if this might help, but this code works for me:
import zope.interface
class MyInterface(zope.interface.Interface):
pass
while this one doesn't, it doesn't compile
import zope.interface
class MyInterface(zope.interface.Interface)
A:
Problem solved ,
turns out there was no problem at all !
I was getting an error on my IDE (vsCode) so I didn't bother to build, however, when I did try to build my code, it woked just fine with no build errors whatsoever.
According to many forums online , vscode does quite frequently show "false" errors and that's fixable (see link below)
https://superuser.com/questions/1639666/visual-studio-code-false-errors-at-random
| Implementing an interface in python | I am pretty new to Python and couldn't understand the origin of this problem.
I'm trying to implement an interface, I have downloaded the zope.interface package, and imported it in my file like this
import zope.interface
Now when I write
class MyInterface(zope.interface.Interface)
I get this error:
"message": "Inheriting 'zope.interface.Interface', which is not a class."
but when I do
class MyInterface(zope.interface.interface.InterfaceClass):
it works fine.
I don't understand the difference.
| [
"I am new to python too, but I will try to help using the little knowledge I have.\nActually I tested your code, and it works for me, it doesn't give me that error message. But concerning the difference between both statements, I wrote the following code to figure out the difference:\n import zope.interface\n class MyInterface(zope.interface.Interface):\n pass\n print(type(MyInterface))\n\n class MyInterface1(zope.interface.interface.InterfaceClass):\n pass\n print(type(MyInterface1))\n\n class TestClass:\n pass\n print(type(TestClass))\n\nThis code gave me this output:\n <class 'zope.interface.interface.InterfaceClass'>\n <class 'type'>\n <class 'type'>\n\nSo to answer your question about the difference between the two statements, the first one, MyInterface, is a declaration of an interface which is, according to the official documentation is an instance of the zop.interface.interface.InterfaceClass.\nMyInterface1, however,is a normal class (object of the mega class type, of which all classes are objects. As an exemple, TestClass is also an object of the mega class type), and it is just inheriting from the class zope.interface.interface.InterfaceClass\nOf course this is just an educated guess, I am new to python interfaces and OOP myself, but I hope this at least helps answer your questions.\n",
"I don't know if this might help, but this code works for me:\n import zope.interface \n \n class MyInterface(zope.interface.Interface):\n pass\n\nwhile this one doesn't, it doesn't compile\n import zope.interface \n \n class MyInterface(zope.interface.Interface)\n\n",
"Problem solved ,\nturns out there was no problem at all !\nI was getting an error on my IDE (vsCode) so I didn't bother to build, however, when I did try to build my code, it woked just fine with no build errors whatsoever.\nAccording to many forums online , vscode does quite frequently show \"false\" errors and that's fixable (see link below)\nhttps://superuser.com/questions/1639666/visual-studio-code-false-errors-at-random\n"
] | [
0,
0,
0
] | [] | [] | [
"python",
"zope",
"zope.interface"
] | stackoverflow_0074665243_python_zope_zope.interface.txt |
Q:
Im trying to build an Installer for some packages that my programm needs. I also want to have a Status bar which shows the current progress
import tkinter as tk
import multiprocessing
from tkinter import messagebox
def installPackages_1(self):
self.t = ""
label = tk.Label(fenster, text="Checking for packages...").place(x=60, y=100)
pb = ttk.Progressbar(fenster, orient='horizontal', mode='determinate', length=280)
pb.place(x=180, y=100)
fenster.update()
packages = ["pandas", "openpyxl", "odfpy"]
for i in packages:
t1 = multiprocessing.Process(target=self.installPackages_2(i))
t1.start()
pb['value'] += 100 / 3
fenster.update()
label1 = tk.Label(fenster, text="Done").place(x=30, y=100, width=450, height=25)
fenster.update()
m_text = "\nStatus:\n%s" % (self.t)
tk.messagebox.showinfo(message=m_text, title="Installation")
def installPackages_2(self,package):
s = ""
s = str(subprocess.check_output([sys.executable, '-m', 'pip', 'install', package]))[2:12]
if s == "Collecting":
self.t += "Package '%s' installed\n" % (package)
else:
self.t += "[OK]: Paket '%s' found\n" % (package)
When i convert my python programm into an .exe the tkinter window open up multiple times, I think this is caused because th subprocess interrupts the process of the tkinterr window. I tried to implement some kind of multiprocessing but it didnt change anything.I convert through auto-py-to-exe.
A:
Pyinstaller already bundles the libraries with your executable, you don't need to check for them.
checking for libraries and installing them is completely unnecessary (and isn't as simple as you expect), don't call either functions inside your executable and your app will work just fine, as you don't need to call them anyway.
needless to say checking for their existence this way will fail and will cause a lot of undesirable behavior, as the application is no longer running as a python executable on a script but as an embedded interpreter, in other words sys.executable no longer points to python.exe.
also the correct way to check that a certain library exists is to use, importlib.util.find_spec, which should correctly work for frozen applications, but again, you don't need it for you executable because pyinstaller already packages all dependencies.
| Im trying to build an Installer for some packages that my programm needs. I also want to have a Status bar which shows the current progress | import tkinter as tk
import multiprocessing
from tkinter import messagebox
def installPackages_1(self):
self.t = ""
label = tk.Label(fenster, text="Checking for packages...").place(x=60, y=100)
pb = ttk.Progressbar(fenster, orient='horizontal', mode='determinate', length=280)
pb.place(x=180, y=100)
fenster.update()
packages = ["pandas", "openpyxl", "odfpy"]
for i in packages:
t1 = multiprocessing.Process(target=self.installPackages_2(i))
t1.start()
pb['value'] += 100 / 3
fenster.update()
label1 = tk.Label(fenster, text="Done").place(x=30, y=100, width=450, height=25)
fenster.update()
m_text = "\nStatus:\n%s" % (self.t)
tk.messagebox.showinfo(message=m_text, title="Installation")
def installPackages_2(self,package):
s = ""
s = str(subprocess.check_output([sys.executable, '-m', 'pip', 'install', package]))[2:12]
if s == "Collecting":
self.t += "Package '%s' installed\n" % (package)
else:
self.t += "[OK]: Paket '%s' found\n" % (package)
When i convert my python programm into an .exe the tkinter window open up multiple times, I think this is caused because th subprocess interrupts the process of the tkinterr window. I tried to implement some kind of multiprocessing but it didnt change anything.I convert through auto-py-to-exe.
| [
"Pyinstaller already bundles the libraries with your executable, you don't need to check for them.\nchecking for libraries and installing them is completely unnecessary (and isn't as simple as you expect), don't call either functions inside your executable and your app will work just fine, as you don't need to call them anyway.\nneedless to say checking for their existence this way will fail and will cause a lot of undesirable behavior, as the application is no longer running as a python executable on a script but as an embedded interpreter, in other words sys.executable no longer points to python.exe.\nalso the correct way to check that a certain library exists is to use, importlib.util.find_spec, which should correctly work for frozen applications, but again, you don't need it for you executable because pyinstaller already packages all dependencies.\n"
] | [
0
] | [] | [] | [
"multiprocessing",
"python",
"subprocess",
"tkinter"
] | stackoverflow_0074669815_multiprocessing_python_subprocess_tkinter.txt |
Q:
How do you pull specific information out of a text file? Python
Here is an example of some of the information in the text file:
Ticker : Ticker representing the company | Company: Name | Title: Position of trader | Trade Type: Buy or sell | Value: Monetary value
Ticker : AKUS | Company: Akouos, Inc. | Title: 10% | Trade Type: P - Purchase | Value: +$374,908,350
Ticker : HHC | Company: Howard Hughes Corp | Title: Dir, 10% | Trade Type: P - Purchase | Value: +$109,214,243
Where each time it says ticker, it's a new line. Is there a way to pull out specific information and set it to a dictionary? For example, would I be able to get a dictionary filled with all the tickers, all the positions and all of the monetary values?
A:
The best way I can think of is to import into a dataframe (df), and then convert to a dictionary (if that is what you really want).
Firstly import the data into a pandas dataframe:
import pandas as pd
filename = 'file1.txt'
df = pd.read_csv(filename,
sep = ':\s+|\s\|',
engine='python',
usecols=[1,3,5,7,9]
)
df.columns = ['Ticker', 'Company', 'Title', 'Trade Type', 'Value']
print(df)
This is the dataframe:
You can then convert this into a dictionary using the following code:
data_dictionary = df.to_dict()
print(data_dictionary)
OUTPUT:
{'Ticker': {0: 'AKUS', 1: 'HHC'}, 'Company': {0: 'Akouos, Inc.', 1: 'Howard Hughes Corp'}, 'Title': {0: '10%', 1: 'Dir, 10%'}, 'Trade Type': {0: 'P - Purchase', 1: 'P - Purchase'}, 'Value': {0: '+$374,908,350', 1: '+$109,214,243'}}
Dict Usage
Should you actually want to use the dictionary for retrieval (instead of the dataframe), and if you would want to search based on ticker symbols. Then this is how I would approach it:
Search for Value of ticker symbol 'AKUS'
tickers = {v:k for k,v in data_dictionary.get('Ticker').items()}
print('AKUS Value:', data_dictionary['Value'][tickers.get('AKUS')])
Output:
AKUS Value: +$374,908,350
A:
My suggestion would be that the dictionary should be keyed on ticker name. Each value for the ticker is itself a dictionary which makes access to the data very easy. Something like this:
ticker = {}
with open('ticker.txt') as tdata:
next(tdata) # skip first line
for row in tdata:
if columns := row.split('|'):
_, t = columns[0].split(':')
ticker[t.strip()] = {k.strip(): v.strip() for k, v in [column.split(':') for column in columns[1:]]}
print(ticker)
Output:
{'AKUS': {'Company': 'Akouos, Inc.', 'Title': '10%', 'Trade Type': 'P - Purchase', 'Value': '+$374,908,350'}, 'HHC': {'Company': 'Howard Hughes Corp', 'Title': 'Dir, 10%', 'Trade Type': 'P - Purchase', 'Value': '+$109,214,243'}}
Usage:
For example, to get the value associated with HHC then it's:
ticker['HHC']['Value']
| How do you pull specific information out of a text file? Python | Here is an example of some of the information in the text file:
Ticker : Ticker representing the company | Company: Name | Title: Position of trader | Trade Type: Buy or sell | Value: Monetary value
Ticker : AKUS | Company: Akouos, Inc. | Title: 10% | Trade Type: P - Purchase | Value: +$374,908,350
Ticker : HHC | Company: Howard Hughes Corp | Title: Dir, 10% | Trade Type: P - Purchase | Value: +$109,214,243
Where each time it says ticker, it's a new line. Is there a way to pull out specific information and set it to a dictionary? For example, would I be able to get a dictionary filled with all the tickers, all the positions and all of the monetary values?
| [
"The best way I can think of is to import into a dataframe (df), and then convert to a dictionary (if that is what you really want).\n\nFirstly import the data into a pandas dataframe:\nimport pandas as pd\n\nfilename = 'file1.txt'\n\ndf = pd.read_csv(filename,\n sep = ':\\s+|\\s\\|',\n engine='python',\n usecols=[1,3,5,7,9]\n )\ndf.columns = ['Ticker', 'Company', 'Title', 'Trade Type', 'Value']\n\nprint(df)\n\n\nThis is the dataframe:\n\n\n\nYou can then convert this into a dictionary using the following code:\ndata_dictionary = df.to_dict()\nprint(data_dictionary)\n\nOUTPUT:\n{'Ticker': {0: 'AKUS', 1: 'HHC'}, 'Company': {0: 'Akouos, Inc.', 1: 'Howard Hughes Corp'}, 'Title': {0: '10%', 1: 'Dir, 10%'}, 'Trade Type': {0: 'P - Purchase', 1: 'P - Purchase'}, 'Value': {0: '+$374,908,350', 1: '+$109,214,243'}}\n\n\n\nDict Usage\nShould you actually want to use the dictionary for retrieval (instead of the dataframe), and if you would want to search based on ticker symbols. Then this is how I would approach it:\n\nSearch for Value of ticker symbol 'AKUS'\ntickers = {v:k for k,v in data_dictionary.get('Ticker').items()}\n\nprint('AKUS Value:', data_dictionary['Value'][tickers.get('AKUS')])\n\nOutput:\nAKUS Value: +$374,908,350\n\n",
"My suggestion would be that the dictionary should be keyed on ticker name. Each value for the ticker is itself a dictionary which makes access to the data very easy. Something like this:\nticker = {}\n\nwith open('ticker.txt') as tdata:\n next(tdata) # skip first line\n for row in tdata:\n if columns := row.split('|'):\n _, t = columns[0].split(':')\n ticker[t.strip()] = {k.strip(): v.strip() for k, v in [column.split(':') for column in columns[1:]]}\n\nprint(ticker)\n\nOutput:\n{'AKUS': {'Company': 'Akouos, Inc.', 'Title': '10%', 'Trade Type': 'P - Purchase', 'Value': '+$374,908,350'}, 'HHC': {'Company': 'Howard Hughes Corp', 'Title': 'Dir, 10%', 'Trade Type': 'P - Purchase', 'Value': '+$109,214,243'}}\n\nUsage:\nFor example, to get the value associated with HHC then it's:\nticker['HHC']['Value']\n\n"
] | [
2,
1
] | [] | [] | [
"python",
"txt"
] | stackoverflow_0074669178_python_txt.txt |
Q:
Advice on how to debug python code using Pycharm
I am a relatively new python user, and wanted advice on how best to debug my code.
Currently, I have a script (main.py), that I run in debug mode using PyCharm. This file is quite short, as most of my functions are contained within another module I have written (i.e. functionsmodule.py). If I put breakpoints in the function I want to modify in functionsmodule.py, this works quite well - then I can explore the variables available inside this function.
However, if I update the function in 'functionsmodule.py', save the file, then reload using importlib.reload, the breakpoints don't seem to be recognised anymore. I then have to rerun the whole of main.py to get to the breakpoint again.
Is there a better solution to this? Thanks for your help!
A:
You can specify a breakpoint in the code directly using the built-in breakpoint()function, which might help in a case like this.
See PEP-553 for more details.
| Advice on how to debug python code using Pycharm | I am a relatively new python user, and wanted advice on how best to debug my code.
Currently, I have a script (main.py), that I run in debug mode using PyCharm. This file is quite short, as most of my functions are contained within another module I have written (i.e. functionsmodule.py). If I put breakpoints in the function I want to modify in functionsmodule.py, this works quite well - then I can explore the variables available inside this function.
However, if I update the function in 'functionsmodule.py', save the file, then reload using importlib.reload, the breakpoints don't seem to be recognised anymore. I then have to rerun the whole of main.py to get to the breakpoint again.
Is there a better solution to this? Thanks for your help!
| [
"You can specify a breakpoint in the code directly using the built-in breakpoint()function, which might help in a case like this.\nSee PEP-553 for more details.\n"
] | [
1
] | [] | [] | [
"debugging",
"pycharm",
"python"
] | stackoverflow_0074669843_debugging_pycharm_python.txt |
Q:
Django form with multi input from loop save only last record to database
I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record from the form appears in the save view. What am I doing wrong, can someone help?
forms.py
class DoctorsSchedule(forms.ModelForm):
# work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
# official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
class Meta:
model = DoctorSchedule
fields = ['date', 'day_type', 'work_hours', 'scheme', 'official_hours']
model.py
class DoctorSchedule(models.Model):
id = models.AutoField(primary_key=True, unique=True)
date = models.DateField(blank=True, null=True)
day_type = models.CharField(max_length=255, blank=True, null=True, default='Pracujący')
work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
scheme = models.CharField(max_length=255, blank=True, null=True, default='20')
official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
def __str__(self):
return self.date
view.py
def terminarz(request):
today = datetime.now()
now = date.today()
locale.setlocale(locale.LC_TIME, 'pl_PL')
def months():
months = {'1': 'Styczeń', '2': 'Luty', '3': 'Marzec', '4': 'Kwiecień', '5': 'Maj', '6': 'Czerwiec',
'7': 'Lipiec',
'8': 'Sierpień', '9': 'Wrzesień', '10': 'Październik', '11': 'Listopad', '12': 'Grudzień'}
return months
##################### days of month list ######################################
def days_of_month_list():
if request.GET.get('year') and request.GET.get('month'):
y = int(request.GET.get('year'))
m = int(request.GET.get('month'))
btn_y = int(request.GET.get('year'))
else:
y = today.year
m = today.month
btn_y = today.year
date_list = {}
for d in range(1, monthrange(y, m)[1] + 1):
x = '{:04d}-{:02d}-{:02d}'.format(y, m, d)
dayName = datetime.strptime(x, '%Y-%m-%d').weekday()
date_list[x] = calendar.day_name[dayName].capitalize()
################### end days of month list #################################
return date_list
months = months()
date_list = days_of_month_list()
btn_today = today.year
btn_today_1 = today.year + 1
btn_today_2 = today.year + 2
if request.GET.get('year') and request.GET.get('month'):
btn_y = int(request.GET.get('year'))
else:
btn_y = today.year
if request.method == 'POST':
form = DoctorsSchedule(request.POST)
if form.is_valid():
form.save()
else:
print(form.is_valid()) # form contains data and errors
print(form.errors)
form = DoctorsSchedule()
else:
form = DoctorsSchedule
context = {
'form': form,
'today': today,
'now': now,
'months': months,
'date_list': date_list,
'btn_today': btn_today,
'btn_today_1': btn_today_1,
'btn_today_2': btn_today_2
}
return render(request, "vita/panel/terminarz.html", context)
templates.html
<div class="card-body">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div class="row p-3 text-center">
{% include 'vita/messages.html' %}
<div class="text-center p-2">
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{btn_today}}'>{{ btn_today }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_1 }}'>{{ btn_today_1 }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_2 }}'>{{ btn_today_2 }}</a>
</div>
{% for nr, month in months.items %}
<div class="col text-center">
{% if btn_y == btn_today_1 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_1}}">{{month|upper}}</a>
{% elif btn_y == btn_today_2 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_2}}">{{month|upper}}</a>
{% else %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today}}">{{month|upper}}</a>
{% endif %}
</div>
{% endfor %}
</div>
<table class="table table-striped table-sm table-responsive">
<thead class="text-light" style="background: #26396F;">
<tr>
<th>Data</th>
<th class="text-center">Dzień pracy</th>
<th class="text-center">Godziny oficjalne</th>
<th class="text-center">Godziny pracy</th>
<th class="text-center">Przedział</th>
<th class="text-center">Ilość wizyt</th>
</tr>
</thead>
<tbody>
{% for date, day in date_list.items %}
<tr>
<td class="p-1">
<a href="/panel/{{ date }}">
<b>{{ date }}</b> -
{% if day == 'Sobota' or day == 'Niedziela' %}
<span class="text-danger">{{ day }}</span>
{% else %}
<span class="text-success">{{ day }}</span>
{% endif %}
</a>
<input type="hidden" name="data" value="{{date}}" />
</td>
<td class="p-1">
<select name="day_type">
{% if day == 'Sobota' or day == 'Niedziela' %}
<option value="Wolny" selected>Wolny</option>
<option value="Pracujący">Pracujący</option>
{% else %}
<option value="Pracujący" selected>Pracujący</option>
<option value="Wolny" >Wolny</option>
{% endif %}
</select>
</td>
{% if day == 'Sobota' or day == 'Niedziela' %}
<td></td>
<td></td>
<td></td>
<td></td>
{% else %}
<td class="p-1 text-center"><input name="official_hours_start" type="time" value="08:00" />-<input name="official_hours_end" type="time" value="19:00" /></td>
<td class="p-1 text-center"><input name="work_hours_start" type="time" value="08:00" />-<input name="work_hours_end" type="time" value="21:00" /></td>
<td class="p-1 text-center">
<select name="scheme">
<option value="10">10 min</option>
<option value="15">15 min</option>
<option value="20">20 min</option>
<option value="25">25 min</option>
<option value="30" selected>30 min</option>
</select>
</td>
<td class="p-1 text-center">0</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-center"><input class="btn btn-success" type="submit" name="update_schedule" value="Uaktualnij terminarz" /></div>
</form>
</div>
A:
You need to pass the form to the template. Now this is OK in your code. But I thing the problem come with the way you manage your form lifecycle.
If I understand your code the workflow is the following:
A GET REQUEST Initialize to form with the current states
You use several GET requests (buttons) to update states/values
Then A POST request to save the form
And you end up with some bad values ?
It's quite Normal ...
let me explain if I'm correct :
First GET You initialize the page data and the form with the an initial state (but maybe not I don't see it)
In other intermediate steps, you use GET request where you modify the page data with the current state but not the form
Finally you save the form with ??? ...
How to fix it:
At each intermediate step update the form data but don't save it. Therefore at the last step, The POST request will normally save correct data
change this:
...
else:
form = DoctorsSchedule()
...
# into
...
else:
form = DoctorsSchedule({
'date': <place here the current correct value for this field>,
'day_type': <place here the current correct value for this field>,
etc...
})
and please replace
form = DoctorsSchedule # this is a Form class not an instance
# with
form = DoctorsSchedule()
# or better
form = DoctorsSchedule(initial_data={<your data>})
# or also better
form = DoctorsSchedule(<some DoctorsSchedule (the Model one) instance>)
you should use a form instance not a form class in your template
and you should rename one of DoctorsSchedule Model or DoctorsSchedule Form in order to avoid confusion
You can also Write some javascript code in order to propagate page changes into the form input fields data directly in the page
A:
Update:
I print(request.POST) and this is the result. When I use form.is_valid it's not show errors and form.save() save only last record from QueryDict
<QueryDict: {'csrfmiddlewaretoken': ['mzIuVQEY1a6s15UEInWD5xZOm6HapMyOAikLItkMTvIGOizxIU9NErfh4SUkfiR9'], 'data': ['2022-12-01', '2022-12-02', '2022-12-03', '2022-12-04', '2022-12-05', '2022-12-06', '2022-12-07', '2022-12-08', '2022
-12-09', '2022-12-10', '2022-12-11', '2022-12-12', '2022-12-13', '2022-12-14', '2022-12-15', '2022-12-16', '2022-12-17', '2022-12-18', '2022-12-19', '2022-12-20', '2022-12-21', '2022-12-22', '2022-12-23', '2022-12-24', '2022-12-25',
'2022-12-26', '2022-12-27', '2022-12-28', '2022-12-29', '2022-12-30', '2022-12-31'], 'day_type': ['Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracu
jący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny'
], 'official_hours_start': ['08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19
:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00'], 'work_hours_start': ['08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21
:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00'], 'scheme': ['30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30'], 'update_schedule': ['Uaktualnij terminarz']}>
A:
This is resolve my problem
if request.method == "POST":
if form.is_valid():
x1 = request.POST #get data from request and getlist from QueryDict
data_l = x1.getlist('data')
day_type_l = x1.getlist('day_type')
work_hours_l = x1.getlist('work_hours_start')
scheme_l = x1.getlist('scheme')
official_hours_l = x1.getlist('official_hours_start')
for date, day_type, work_hours, official_hours, scheme in zip(data_l,day_type_l,work_hours_l,official_hours_l,scheme_l):
post_dict = {'date': date, 'day_type': day_type, 'work_hours': work_hours, 'official_hours': official_hours, 'scheme': scheme}
form = DoctorsScheduleForm(post_dict)
form.save()
else:
form = DoctorsScheduleForm()
| Django form with multi input from loop save only last record to database | I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record from the form appears in the save view. What am I doing wrong, can someone help?
forms.py
class DoctorsSchedule(forms.ModelForm):
# work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
# official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
class Meta:
model = DoctorSchedule
fields = ['date', 'day_type', 'work_hours', 'scheme', 'official_hours']
model.py
class DoctorSchedule(models.Model):
id = models.AutoField(primary_key=True, unique=True)
date = models.DateField(blank=True, null=True)
day_type = models.CharField(max_length=255, blank=True, null=True, default='Pracujący')
work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
scheme = models.CharField(max_length=255, blank=True, null=True, default='20')
official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
def __str__(self):
return self.date
view.py
def terminarz(request):
today = datetime.now()
now = date.today()
locale.setlocale(locale.LC_TIME, 'pl_PL')
def months():
months = {'1': 'Styczeń', '2': 'Luty', '3': 'Marzec', '4': 'Kwiecień', '5': 'Maj', '6': 'Czerwiec',
'7': 'Lipiec',
'8': 'Sierpień', '9': 'Wrzesień', '10': 'Październik', '11': 'Listopad', '12': 'Grudzień'}
return months
##################### days of month list ######################################
def days_of_month_list():
if request.GET.get('year') and request.GET.get('month'):
y = int(request.GET.get('year'))
m = int(request.GET.get('month'))
btn_y = int(request.GET.get('year'))
else:
y = today.year
m = today.month
btn_y = today.year
date_list = {}
for d in range(1, monthrange(y, m)[1] + 1):
x = '{:04d}-{:02d}-{:02d}'.format(y, m, d)
dayName = datetime.strptime(x, '%Y-%m-%d').weekday()
date_list[x] = calendar.day_name[dayName].capitalize()
################### end days of month list #################################
return date_list
months = months()
date_list = days_of_month_list()
btn_today = today.year
btn_today_1 = today.year + 1
btn_today_2 = today.year + 2
if request.GET.get('year') and request.GET.get('month'):
btn_y = int(request.GET.get('year'))
else:
btn_y = today.year
if request.method == 'POST':
form = DoctorsSchedule(request.POST)
if form.is_valid():
form.save()
else:
print(form.is_valid()) # form contains data and errors
print(form.errors)
form = DoctorsSchedule()
else:
form = DoctorsSchedule
context = {
'form': form,
'today': today,
'now': now,
'months': months,
'date_list': date_list,
'btn_today': btn_today,
'btn_today_1': btn_today_1,
'btn_today_2': btn_today_2
}
return render(request, "vita/panel/terminarz.html", context)
templates.html
<div class="card-body">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div class="row p-3 text-center">
{% include 'vita/messages.html' %}
<div class="text-center p-2">
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{btn_today}}'>{{ btn_today }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_1 }}'>{{ btn_today_1 }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_2 }}'>{{ btn_today_2 }}</a>
</div>
{% for nr, month in months.items %}
<div class="col text-center">
{% if btn_y == btn_today_1 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_1}}">{{month|upper}}</a>
{% elif btn_y == btn_today_2 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_2}}">{{month|upper}}</a>
{% else %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today}}">{{month|upper}}</a>
{% endif %}
</div>
{% endfor %}
</div>
<table class="table table-striped table-sm table-responsive">
<thead class="text-light" style="background: #26396F;">
<tr>
<th>Data</th>
<th class="text-center">Dzień pracy</th>
<th class="text-center">Godziny oficjalne</th>
<th class="text-center">Godziny pracy</th>
<th class="text-center">Przedział</th>
<th class="text-center">Ilość wizyt</th>
</tr>
</thead>
<tbody>
{% for date, day in date_list.items %}
<tr>
<td class="p-1">
<a href="/panel/{{ date }}">
<b>{{ date }}</b> -
{% if day == 'Sobota' or day == 'Niedziela' %}
<span class="text-danger">{{ day }}</span>
{% else %}
<span class="text-success">{{ day }}</span>
{% endif %}
</a>
<input type="hidden" name="data" value="{{date}}" />
</td>
<td class="p-1">
<select name="day_type">
{% if day == 'Sobota' or day == 'Niedziela' %}
<option value="Wolny" selected>Wolny</option>
<option value="Pracujący">Pracujący</option>
{% else %}
<option value="Pracujący" selected>Pracujący</option>
<option value="Wolny" >Wolny</option>
{% endif %}
</select>
</td>
{% if day == 'Sobota' or day == 'Niedziela' %}
<td></td>
<td></td>
<td></td>
<td></td>
{% else %}
<td class="p-1 text-center"><input name="official_hours_start" type="time" value="08:00" />-<input name="official_hours_end" type="time" value="19:00" /></td>
<td class="p-1 text-center"><input name="work_hours_start" type="time" value="08:00" />-<input name="work_hours_end" type="time" value="21:00" /></td>
<td class="p-1 text-center">
<select name="scheme">
<option value="10">10 min</option>
<option value="15">15 min</option>
<option value="20">20 min</option>
<option value="25">25 min</option>
<option value="30" selected>30 min</option>
</select>
</td>
<td class="p-1 text-center">0</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-center"><input class="btn btn-success" type="submit" name="update_schedule" value="Uaktualnij terminarz" /></div>
</form>
</div>
| [
"You need to pass the form to the template. Now this is OK in your code. But I thing the problem come with the way you manage your form lifecycle.\nIf I understand your code the workflow is the following:\n\nA GET REQUEST Initialize to form with the current states\nYou use several GET requests (buttons) to update states/values\nThen A POST request to save the form\n\nAnd you end up with some bad values ?\nIt's quite Normal ...\nlet me explain if I'm correct :\n\nFirst GET You initialize the page data and the form with the an initial state (but maybe not I don't see it)\nIn other intermediate steps, you use GET request where you modify the page data with the current state but not the form\nFinally you save the form with ??? ...\n\nHow to fix it:\n\nAt each intermediate step update the form data but don't save it. Therefore at the last step, The POST request will normally save correct data\n\nchange this:\n...\nelse:\n form = DoctorsSchedule()\n...\n# into\n\n...\nelse:\n form = DoctorsSchedule({\n 'date': <place here the current correct value for this field>, \n 'day_type': <place here the current correct value for this field>, \n etc...\n })\n\n\nand please replace\n form = DoctorsSchedule # this is a Form class not an instance\n# with \n form = DoctorsSchedule()\n# or better\n form = DoctorsSchedule(initial_data={<your data>})\n# or also better\n form = DoctorsSchedule(<some DoctorsSchedule (the Model one) instance>)\n\nyou should use a form instance not a form class in your template\nand you should rename one of DoctorsSchedule Model or DoctorsSchedule Form in order to avoid confusion\n\nYou can also Write some javascript code in order to propagate page changes into the form input fields data directly in the page\n\n",
"Update:\nI print(request.POST) and this is the result. When I use form.is_valid it's not show errors and form.save() save only last record from QueryDict\n<QueryDict: {'csrfmiddlewaretoken': ['mzIuVQEY1a6s15UEInWD5xZOm6HapMyOAikLItkMTvIGOizxIU9NErfh4SUkfiR9'], 'data': ['2022-12-01', '2022-12-02', '2022-12-03', '2022-12-04', '2022-12-05', '2022-12-06', '2022-12-07', '2022-12-08', '2022\n-12-09', '2022-12-10', '2022-12-11', '2022-12-12', '2022-12-13', '2022-12-14', '2022-12-15', '2022-12-16', '2022-12-17', '2022-12-18', '2022-12-19', '2022-12-20', '2022-12-21', '2022-12-22', '2022-12-23', '2022-12-24', '2022-12-25',\n '2022-12-26', '2022-12-27', '2022-12-28', '2022-12-29', '2022-12-30', '2022-12-31'], 'day_type': ['Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracu\njący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny'\n], 'official_hours_start': ['08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19\n:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00'], 'work_hours_start': ['08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21\n:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00'], 'scheme': ['30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30'], 'update_schedule': ['Uaktualnij terminarz']}>\n\n",
"This is resolve my problem\n\n if request.method == \"POST\":\n if form.is_valid():\n x1 = request.POST #get data from request and getlist from QueryDict\n data_l = x1.getlist('data')\n day_type_l = x1.getlist('day_type')\n work_hours_l = x1.getlist('work_hours_start')\n scheme_l = x1.getlist('scheme')\n official_hours_l = x1.getlist('official_hours_start')\n\n for date, day_type, work_hours, official_hours, scheme in zip(data_l,day_type_l,work_hours_l,official_hours_l,scheme_l):\n\n post_dict = {'date': date, 'day_type': day_type, 'work_hours': work_hours, 'official_hours': official_hours, 'scheme': scheme}\n \n form = DoctorsScheduleForm(post_dict)\n form.save()\n\n else:\n form = DoctorsScheduleForm()\n\n"
] | [
1,
0,
0
] | [] | [] | [
"django",
"forms",
"html",
"python"
] | stackoverflow_0074615371_django_forms_html_python.txt |
Q:
Extracting information from a list of json Python
Identifier Properties
1 [{"$id":"2","SMName":"pia.redoabs.com","Type":"sms"},{"$id":"3","Name":"_18_Lucene41_0.doc","Type":"file"}]
2 [{"$id":"2","SMName":"pred.redocad.com","Type":"sms"},{"$id":"3","Name":"_18_Nil41_0.doc","Type":"file"}]
3 [{"$id":"2","SMName":"promomaster.com","Type":"sms"},{"$id":"3","Name":"_17_Litre41_0.doc","Type":"file"}]
4 [{"$id":"2","SMName":"admaster.com","Type":"sms"},{"$id":"3","Name":"_k.pos","Type":"file"}]
5 [{"$id":"2","SMName":"plan.com.com","Type":"sms"},{"$id":"3","Name":"_3_Lucene41_0.doc","Type":"file"}]
6 [{"$id":"2","Name":"jm460","ETNDomain":"ent.ad.ent","Sid":"S-1-5-21-117609710-2111687655-839522115-432193","AadUserId":"7133971dffgh5r-b9b8-4af3-bbfd-85b1b56d1f6f","IsDomainJoined":true,"Type":"account","UserPrincipalName":"[email protected]"},{"$id":"3","Directory":"C:\\CR\\new_cbest_malware","Name":"ent_Survey.zip","hash":[{"$id":"4","Algorithm":"hsa1","Value":"cecce931f21697876efc80f5897a31481c396795","Type":"hash"},{"$id":"5","Algorithm":"MI5","Value":"12c216630a5f24faab06d463c9ce72a5","Type":"hash"},{"$id":"6","Algorithm":"TM345","Value":"cbb327b70a83fefeaf744458f2ed62021e529ce0ece36566761779f17d4c07a6","Type":"hash"}],"CreatedTimeUtc":"2022-08-22T17:42:02.4272869Z","Type":"file"},{"$ref":"4"},{"$ref":"5"},{"$ref":"6"},{"$id":"7","ProcessId":"54884","CommandLine":"\"7zG.exe\" a -i#7zMap23807:40278:7zEvent24942 -ad -saa -- \"C:\\CR\\CR_2\"","ElevationToken":"Default","CreationTimeUtc":"2022-10-03T17:59:35.2339055Z","ImageFile":{"$id":"8","Directory":"C:\\Program Files\\7-Zip","Name":"9zG.exe","FileHashes":[{"$id":"9","Algorithm":"HSA2","Value":"df22612647e9404a515d48ebad490349685250de","Type":"hash"},{"$id":"10","Algorithm":"MI5","Value":"04fb3ae7f05c8bc333125972ba907398","Type":"hash"},{"$id":"11","Algorithm":"hsa1","Value":"2fb898bacb587f2484c9c4aa6da2729079d93d1f923a017bb84beef87bf74fef","Type":"hash"}],"CreatedTimeUtc":"2020-09-21T16:34:33.1299959Z","Type":"file"},"ParentProcess":{"$id":"12","ProcessId":"13516","CreationTimeUtc":"2022-09-21T12:41:32.4609401Z","CreatedTimeUtc":"2022-09-21T12:41:32.4609401Z","Type":"process"},"CreatedTimeUtc":"2022-10-03T17:59:35.2339055Z","Type":"process"},{"$ref":"12"},{"$ref":"8"},{"$ref":"9"},{"$ref":"10"},{"$ref":"11"},{"$id":"13","DnsDomain":"ent.ad.ent.com","HostName":"ilch-l788441","OSFamily":"Windows","OSVersion":"20H2","Tags":[{"ProviderName":"tmdp","TagId":"VwanPov","TagName":"VwanPov","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"Proxy Allow Personal Storage","TagName":"Proxy Allow Personal Storage","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"Proxy Allow Webmail","TagName":"Proxy Allow Webmail","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"proxy-allow-social-media","TagName":"proxy-allow-social-media","TagType":"UserDefined"}],"Type":"host","dmptDeviceId":"fa52ff90ab60ee6eac86ec60ed2ac748a33e29fa","FQDN":"ilch-567.ent.ad.ent.com","AadDeviceId":"e1d59b69-dd3f-4f33-96b5-db9233654c16","RiskScore":"Medium","HealthStatus":"Active","LastSeen":"2022-10-03T18:09:32.7812655","LastExternalIpAddress":"208.95.144.39","LastIpAddress":"10.14.126.52","AvStatus":"Updated","OnboardingStatus":"Onboarded","LoggedOnUsers":[{"AccountName":"jmjklo460","DomainName":"ENT"}]}]
This is a dataframe with 2 columns "Identifier" & "Properties". The "Properties" column appears as a list of json.The aim is to create 2 different columns for "sms" & "file".
I noticed that one of the rows have entirely different information & I would need a few of them.For eg- ENTDomain,UserPrincipalName
The code that you provided works for the first 5 observations but tends to fail when it encounters the 6th observation.
Can we make the code dynamic to be able to extract any values ?
Further I used kql to parse this data & it was relatively straightforward.
A:
You can try:
import json
df["Properties"] = df["Properties"].apply(
lambda x: {
d["Type"]: (d["SMName"] if d["Type"] == "sms" else d["Name"])
for d in json.loads(x)
}
)
df = pd.concat([df, df.pop("Properties").apply(pd.Series)], axis=1)
print(df)
Prints:
Identifier sms file
0 1 pia.redoabs.com _18_Lucene41_0.doc
1 2 pred.redocad.com _18_Nil41_0.doc
2 3 promomaster.com _17_Litre41_0.doc
3 4 admaster.com _k.pos
4 5 plan.com.com _3_Lucene41_0.doc
| Extracting information from a list of json Python | Identifier Properties
1 [{"$id":"2","SMName":"pia.redoabs.com","Type":"sms"},{"$id":"3","Name":"_18_Lucene41_0.doc","Type":"file"}]
2 [{"$id":"2","SMName":"pred.redocad.com","Type":"sms"},{"$id":"3","Name":"_18_Nil41_0.doc","Type":"file"}]
3 [{"$id":"2","SMName":"promomaster.com","Type":"sms"},{"$id":"3","Name":"_17_Litre41_0.doc","Type":"file"}]
4 [{"$id":"2","SMName":"admaster.com","Type":"sms"},{"$id":"3","Name":"_k.pos","Type":"file"}]
5 [{"$id":"2","SMName":"plan.com.com","Type":"sms"},{"$id":"3","Name":"_3_Lucene41_0.doc","Type":"file"}]
6 [{"$id":"2","Name":"jm460","ETNDomain":"ent.ad.ent","Sid":"S-1-5-21-117609710-2111687655-839522115-432193","AadUserId":"7133971dffgh5r-b9b8-4af3-bbfd-85b1b56d1f6f","IsDomainJoined":true,"Type":"account","UserPrincipalName":"[email protected]"},{"$id":"3","Directory":"C:\\CR\\new_cbest_malware","Name":"ent_Survey.zip","hash":[{"$id":"4","Algorithm":"hsa1","Value":"cecce931f21697876efc80f5897a31481c396795","Type":"hash"},{"$id":"5","Algorithm":"MI5","Value":"12c216630a5f24faab06d463c9ce72a5","Type":"hash"},{"$id":"6","Algorithm":"TM345","Value":"cbb327b70a83fefeaf744458f2ed62021e529ce0ece36566761779f17d4c07a6","Type":"hash"}],"CreatedTimeUtc":"2022-08-22T17:42:02.4272869Z","Type":"file"},{"$ref":"4"},{"$ref":"5"},{"$ref":"6"},{"$id":"7","ProcessId":"54884","CommandLine":"\"7zG.exe\" a -i#7zMap23807:40278:7zEvent24942 -ad -saa -- \"C:\\CR\\CR_2\"","ElevationToken":"Default","CreationTimeUtc":"2022-10-03T17:59:35.2339055Z","ImageFile":{"$id":"8","Directory":"C:\\Program Files\\7-Zip","Name":"9zG.exe","FileHashes":[{"$id":"9","Algorithm":"HSA2","Value":"df22612647e9404a515d48ebad490349685250de","Type":"hash"},{"$id":"10","Algorithm":"MI5","Value":"04fb3ae7f05c8bc333125972ba907398","Type":"hash"},{"$id":"11","Algorithm":"hsa1","Value":"2fb898bacb587f2484c9c4aa6da2729079d93d1f923a017bb84beef87bf74fef","Type":"hash"}],"CreatedTimeUtc":"2020-09-21T16:34:33.1299959Z","Type":"file"},"ParentProcess":{"$id":"12","ProcessId":"13516","CreationTimeUtc":"2022-09-21T12:41:32.4609401Z","CreatedTimeUtc":"2022-09-21T12:41:32.4609401Z","Type":"process"},"CreatedTimeUtc":"2022-10-03T17:59:35.2339055Z","Type":"process"},{"$ref":"12"},{"$ref":"8"},{"$ref":"9"},{"$ref":"10"},{"$ref":"11"},{"$id":"13","DnsDomain":"ent.ad.ent.com","HostName":"ilch-l788441","OSFamily":"Windows","OSVersion":"20H2","Tags":[{"ProviderName":"tmdp","TagId":"VwanPov","TagName":"VwanPov","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"Proxy Allow Personal Storage","TagName":"Proxy Allow Personal Storage","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"Proxy Allow Webmail","TagName":"Proxy Allow Webmail","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"proxy-allow-social-media","TagName":"proxy-allow-social-media","TagType":"UserDefined"}],"Type":"host","dmptDeviceId":"fa52ff90ab60ee6eac86ec60ed2ac748a33e29fa","FQDN":"ilch-567.ent.ad.ent.com","AadDeviceId":"e1d59b69-dd3f-4f33-96b5-db9233654c16","RiskScore":"Medium","HealthStatus":"Active","LastSeen":"2022-10-03T18:09:32.7812655","LastExternalIpAddress":"208.95.144.39","LastIpAddress":"10.14.126.52","AvStatus":"Updated","OnboardingStatus":"Onboarded","LoggedOnUsers":[{"AccountName":"jmjklo460","DomainName":"ENT"}]}]
This is a dataframe with 2 columns "Identifier" & "Properties". The "Properties" column appears as a list of json.The aim is to create 2 different columns for "sms" & "file".
I noticed that one of the rows have entirely different information & I would need a few of them.For eg- ENTDomain,UserPrincipalName
The code that you provided works for the first 5 observations but tends to fail when it encounters the 6th observation.
Can we make the code dynamic to be able to extract any values ?
Further I used kql to parse this data & it was relatively straightforward.
| [
"You can try:\nimport json\n\ndf[\"Properties\"] = df[\"Properties\"].apply(\n lambda x: {\n d[\"Type\"]: (d[\"SMName\"] if d[\"Type\"] == \"sms\" else d[\"Name\"])\n for d in json.loads(x)\n }\n)\n\ndf = pd.concat([df, df.pop(\"Properties\").apply(pd.Series)], axis=1)\n\nprint(df)\n\nPrints:\n Identifier sms file\n0 1 pia.redoabs.com _18_Lucene41_0.doc\n1 2 pred.redocad.com _18_Nil41_0.doc\n2 3 promomaster.com _17_Litre41_0.doc\n3 4 admaster.com _k.pos\n4 5 plan.com.com _3_Lucene41_0.doc\n\n"
] | [
0
] | [] | [] | [
"json",
"list",
"python"
] | stackoverflow_0074669506_json_list_python.txt |
Q:
Attempting to install Stable Diffusion via Python
I've trawled through stack overflow, several youtube videos and can't for the life of me work this out.
I've unpackaged and pulled from git, all files are where they need to be as far as the installation for Stable Diffusion goes - but when I go to run I get two errors, one being the pip version. I upgraded via 'pip install --upgrade pip' and though the version updated, I'm still getting the below error.
The other issue is that pytorch doesn't seem to have installed. I've added it to the requirements.txt and run 'pip install -r requirements.txt' which doesn't seem to work either. I also downloaded 1.12.1+cu113 and ran pip install "path/" and received the error "ERROR: torch-1.12.1+cu113-cp39-cp39-win_amd64.whl is not a supported wheel on this platform."
Error received below:
stderr: ERROR: Could not find a version that satisfies the requirement torch==1.12.1+cu113 (from versions: none)
ERROR: No matching distribution found for torch==1.12.1+cu113
WARNING: You are using pip version 20.1.1; however, version 22.3 is available.
You should consider upgrading via the 'C:\Users\XXX\Downloads\STABLE\stable-diffusion-webui\venv\Scripts\python.exe -m pip install --upgrade pip' command.
Any help would be greatly appreciated, I've tried my best to be self-sufficient so I'm putting it to the people who may know how to help.
A:
One of the easiest methods to install SD is with Automatic1111
https://github.com/AUTOMATIC1111/stable-diffusion-webui
Instructions on this page in a section titled "Automatic Installation on Windows" (since you're using windows paths in your post)
Install Python 3.10.6, checking "Add Python to PATH" Install git.
Download the stable-diffusion-webui repository, for example by running git clonehttps://github.com/AUTOMATIC1111/stable-diffusion-webui.git.
Place model.ckpt in the models directory (see dependencies for where to
get it).
(Optional) Place GFPGANv1.4.pth in the base directory,
alongside webui.py (see dependencies for where to get it).
Run webui-user.bat from Windows Explorer as normal, non-administrator,
user.
This is much easier and improved from the early days of Automatic and Stable Diffusion itself.
| Attempting to install Stable Diffusion via Python | I've trawled through stack overflow, several youtube videos and can't for the life of me work this out.
I've unpackaged and pulled from git, all files are where they need to be as far as the installation for Stable Diffusion goes - but when I go to run I get two errors, one being the pip version. I upgraded via 'pip install --upgrade pip' and though the version updated, I'm still getting the below error.
The other issue is that pytorch doesn't seem to have installed. I've added it to the requirements.txt and run 'pip install -r requirements.txt' which doesn't seem to work either. I also downloaded 1.12.1+cu113 and ran pip install "path/" and received the error "ERROR: torch-1.12.1+cu113-cp39-cp39-win_amd64.whl is not a supported wheel on this platform."
Error received below:
stderr: ERROR: Could not find a version that satisfies the requirement torch==1.12.1+cu113 (from versions: none)
ERROR: No matching distribution found for torch==1.12.1+cu113
WARNING: You are using pip version 20.1.1; however, version 22.3 is available.
You should consider upgrading via the 'C:\Users\XXX\Downloads\STABLE\stable-diffusion-webui\venv\Scripts\python.exe -m pip install --upgrade pip' command.
Any help would be greatly appreciated, I've tried my best to be self-sufficient so I'm putting it to the people who may know how to help.
| [
"One of the easiest methods to install SD is with Automatic1111\nhttps://github.com/AUTOMATIC1111/stable-diffusion-webui\nInstructions on this page in a section titled \"Automatic Installation on Windows\" (since you're using windows paths in your post)\n\nInstall Python 3.10.6, checking \"Add Python to PATH\" Install git.\nDownload the stable-diffusion-webui repository, for example by running git clonehttps://github.com/AUTOMATIC1111/stable-diffusion-webui.git.\nPlace model.ckpt in the models directory (see dependencies for where to\nget it).\n(Optional) Place GFPGANv1.4.pth in the base directory,\nalongside webui.py (see dependencies for where to get it).\nRun webui-user.bat from Windows Explorer as normal, non-administrator,\nuser.\n\nThis is much easier and improved from the early days of Automatic and Stable Diffusion itself.\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"stable_diffusion"
] | stackoverflow_0074313444_pip_python_stable_diffusion.txt |
Q:
TypeError converting fahrenheit to celsius in python
my code:
temperature_f = input('Please enter the temperature :')
print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')
run code:
Please enter the temperature :50
Traceback (most recent call last):
File "c:\Users\Aryan\.vscode\py\test1.py", line 2, in <module>
print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')
~~~~~~~~~~~~~~^~~~
TypeError: unsupported operand type(s) for -: 'str' and 'int'
How can I fix this error?
I want to write a code that will convert fahrenheit to celsius for me but i am getting this error
Please tell me how I can fix this error
A:
You have to type cast your input
temperature_f = input(int('Please enter the temperature :'))
A:
type cast temperature string into float.
temperature_f = float(input('Please enter the temperature :'))
print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')
| TypeError converting fahrenheit to celsius in python | my code:
temperature_f = input('Please enter the temperature :')
print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')
run code:
Please enter the temperature :50
Traceback (most recent call last):
File "c:\Users\Aryan\.vscode\py\test1.py", line 2, in <module>
print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')
~~~~~~~~~~~~~~^~~~
TypeError: unsupported operand type(s) for -: 'str' and 'int'
How can I fix this error?
I want to write a code that will convert fahrenheit to celsius for me but i am getting this error
Please tell me how I can fix this error
| [
"You have to type cast your input\ntemperature_f = input(int('Please enter the temperature :'))\n\n",
"type cast temperature string into float.\ntemperature_f = float(input('Please enter the temperature :'))\nprint('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')\n\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074669949_python.txt |
Q:
openAI DALL-E ModuleNotFoundError
I installed DALL-E following the instructions on https://github.com/openai/DALL-E
and got :
---> 10 from dall_e import map_pixels, unmap_pixels, load_model
11 from IPython.display import display, display_markdown
12
ModuleNotFoundError: No module named 'dall_e'
A:
I found that it helped when I changed which Python version I was using.
It fixed my issue when I changed mine from 3.7.- to 3.10.7.
| openAI DALL-E ModuleNotFoundError | I installed DALL-E following the instructions on https://github.com/openai/DALL-E
and got :
---> 10 from dall_e import map_pixels, unmap_pixels, load_model
11 from IPython.display import display, display_markdown
12
ModuleNotFoundError: No module named 'dall_e'
| [
"I found that it helped when I changed which Python version I was using.\nIt fixed my issue when I changed mine from 3.7.- to 3.10.7.\n"
] | [
1
] | [] | [] | [
"openai",
"python",
"pytorch"
] | stackoverflow_0072078830_openai_python_pytorch.txt |
Q:
planets created from 1d perlin noise terrain look weird
i am trying to make planets using pyglet but they end up looking like stars result
here is my code
also i need a way to convert a batch to a sprite (to move it easily)
import pyglet
from pyglet import shapes
import opensimplex
import math
import time
brtd = 0
######## planets###########
class planetobj():
def __init__(self,seed=1234,age=68,position=(0,0),color=(0,1,0),name="planet",description=" 127.0.0.1 , home sweet home never will thy become infected with the virus that has a closedcure"):
self.seed = seed
self.age = age
self.position = position
self.color = color
self.name = name
self.description = description
def gplanet(self,size):
opensimplex.seed(self.seed)
done = 0
xc = 0
c = 0
self.terrain = []
start = opensimplex.noise2(x=0, y=self.age)
while (done == 0 or xc < 50) and not xc > 100 :
xc = xc + 1
c = c + size
value = opensimplex.noise2(x=xc, y=self.age)
self.terrain.append(value * size)
if xc > 50:
if math.floor(value * 100 ) == math.floor(start * 100):
self.done = 1
def mkplanet(self, x,y):
self.batch = pyglet.graphics.Batch()
corner1 = (x,y)
self.trias = []
counter = 0
cornerback = [0,0]
for i in self.terrain:
counter += 1
radi = (360 / len(self.terrain)) * counter
radi2 = (360 / len(self.terrain)) * ((counter + 1 ) % len(self.terrain))
theta = self.terrain[(counter +1 ) % len(self.terrain)]
corner3 = (x + math.sin(radi) * ( i ) ,math.cos(radi) * ( i ) + y )
corner2 = (x + math.sin(radi2) * ( theta ) ,math.cos(radi2) * ( theta ) + y )
self.trias.append(shapes.Triangle( x,y,corner2[0], corner2[1], corner3[0], corner3[1], color=(255, counter % 255, 255), batch=self.batch) )
############ basic game logic & rendering ###########
scr_X = 400
scr_Y = 300
window = pyglet.window.Window(scr_X,scr_Y)
samplebatch = pyglet.graphics.Batch()
earth = planetobj()
earth.gplanet(200)
planets = []
planets.append(earth)
earth.mkplanet( 50 ,50)
@window.event
def on_draw():
window.clear()
earth.batch.draw()
pyglet.app.run()
i tried changing the values that get divided by 'len(self.terrain)'
but i could not find out how to make the planets look round
A:
OK, I've corrected your trigonometry, but there are some other issues. The random values you get back from the noise generator are between -1 and 1. You are then multiplying that by the planet size, which gives you wild variations from wedge to wedge. What you want is to have a basic wedge size, which you use the noise to adjust bit by bit. Here, I'm saying that the noise should be 3% of the wedge size (size/30).
I didn't want to download opensimplex, so I've used a uniform random number generator. I'm also using matplotlib to plot the triangle, but see if this is closer to what you intended.
import math
import random
import numpy as np
import matplotlib.pyplot as plt
class planetobj():
def __init__(self,seed=1234,age=68,position=(0,0),color=(0,1,0),name="planet",description=""):
self.seed = seed
self.age = age
self.position = position
self.color = color
self.name = name
self.description = description
def gplanet(self,size):
done = 0
xc = 0
self.terrain = []
start = random.uniform(-1,1)
while (done == 0 or xc < 50) and not xc > 100 :
xc = xc + 1
value = random.uniform(-1,1)
self.terrain.append(size + value * size / 30)
if xc > 50 and math.floor(value * 100) == math.floor(start * 100):
done = 1
def mkplanet(self, x,y):
corner1 = (x,y)
self.trias = []
deltatheta = 360 / len(self.terrain)
for counter,i in enumerate(self.terrain):
theta1 = deltatheta * counter
theta2 = deltatheta * (counter + 1)
radius = self.terrain[counter]
corner2 = (x + radius * math.cos(theta1), y + radius * math.sin(theta1))
corner3 = (x + radius * math.cos(theta2), y + radius * math.sin(theta2))
# self.trias.append(shapes.Triangle( x, y, corner2[0], corner2[1], corner3[0], corner3[1], color=(255, counter % 255, 255), batch=self.batch) )
self.trias.append(( x, y, corner2[0], corner2[1], corner3[0], corner3[1], (1.0,(counter%255)/255,1.0) ))
earth = planetobj()
earth.gplanet(200)
earth.mkplanet(50 ,50)
print(earth.trias)
plt.figure()
plt.scatter( [48,48,52,52],[-50,50,-50,50] )
for t in earth.trias:
tri = np.array(t[:6]).reshape(3,2)
plt.gca().add_patch(plt.Polygon( tri, color=t[6] ))
plt.show()
Output:
| planets created from 1d perlin noise terrain look weird | i am trying to make planets using pyglet but they end up looking like stars result
here is my code
also i need a way to convert a batch to a sprite (to move it easily)
import pyglet
from pyglet import shapes
import opensimplex
import math
import time
brtd = 0
######## planets###########
class planetobj():
def __init__(self,seed=1234,age=68,position=(0,0),color=(0,1,0),name="planet",description=" 127.0.0.1 , home sweet home never will thy become infected with the virus that has a closedcure"):
self.seed = seed
self.age = age
self.position = position
self.color = color
self.name = name
self.description = description
def gplanet(self,size):
opensimplex.seed(self.seed)
done = 0
xc = 0
c = 0
self.terrain = []
start = opensimplex.noise2(x=0, y=self.age)
while (done == 0 or xc < 50) and not xc > 100 :
xc = xc + 1
c = c + size
value = opensimplex.noise2(x=xc, y=self.age)
self.terrain.append(value * size)
if xc > 50:
if math.floor(value * 100 ) == math.floor(start * 100):
self.done = 1
def mkplanet(self, x,y):
self.batch = pyglet.graphics.Batch()
corner1 = (x,y)
self.trias = []
counter = 0
cornerback = [0,0]
for i in self.terrain:
counter += 1
radi = (360 / len(self.terrain)) * counter
radi2 = (360 / len(self.terrain)) * ((counter + 1 ) % len(self.terrain))
theta = self.terrain[(counter +1 ) % len(self.terrain)]
corner3 = (x + math.sin(radi) * ( i ) ,math.cos(radi) * ( i ) + y )
corner2 = (x + math.sin(radi2) * ( theta ) ,math.cos(radi2) * ( theta ) + y )
self.trias.append(shapes.Triangle( x,y,corner2[0], corner2[1], corner3[0], corner3[1], color=(255, counter % 255, 255), batch=self.batch) )
############ basic game logic & rendering ###########
scr_X = 400
scr_Y = 300
window = pyglet.window.Window(scr_X,scr_Y)
samplebatch = pyglet.graphics.Batch()
earth = planetobj()
earth.gplanet(200)
planets = []
planets.append(earth)
earth.mkplanet( 50 ,50)
@window.event
def on_draw():
window.clear()
earth.batch.draw()
pyglet.app.run()
i tried changing the values that get divided by 'len(self.terrain)'
but i could not find out how to make the planets look round
| [
"OK, I've corrected your trigonometry, but there are some other issues. The random values you get back from the noise generator are between -1 and 1. You are then multiplying that by the planet size, which gives you wild variations from wedge to wedge. What you want is to have a basic wedge size, which you use the noise to adjust bit by bit. Here, I'm saying that the noise should be 3% of the wedge size (size/30).\nI didn't want to download opensimplex, so I've used a uniform random number generator. I'm also using matplotlib to plot the triangle, but see if this is closer to what you intended.\nimport math\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass planetobj():\n def __init__(self,seed=1234,age=68,position=(0,0),color=(0,1,0),name=\"planet\",description=\"\"):\n self.seed = seed\n self.age = age\n self.position = position\n self.color = color\n self.name = name\n self.description = description\n\n def gplanet(self,size):\n done = 0\n xc = 0\n self.terrain = []\n start = random.uniform(-1,1)\n while (done == 0 or xc < 50) and not xc > 100 :\n xc = xc + 1\n value = random.uniform(-1,1)\n self.terrain.append(size + value * size / 30)\n if xc > 50 and math.floor(value * 100) == math.floor(start * 100):\n done = 1\n\n def mkplanet(self, x,y):\n corner1 = (x,y)\n self.trias = []\n deltatheta = 360 / len(self.terrain)\n for counter,i in enumerate(self.terrain):\n theta1 = deltatheta * counter\n theta2 = deltatheta * (counter + 1)\n radius = self.terrain[counter] \n corner2 = (x + radius * math.cos(theta1), y + radius * math.sin(theta1))\n corner3 = (x + radius * math.cos(theta2), y + radius * math.sin(theta2))\n# self.trias.append(shapes.Triangle( x, y, corner2[0], corner2[1], corner3[0], corner3[1], color=(255, counter % 255, 255), batch=self.batch) )\n self.trias.append(( x, y, corner2[0], corner2[1], corner3[0], corner3[1], (1.0,(counter%255)/255,1.0) ))\n\n\nearth = planetobj()\nearth.gplanet(200)\n\nearth.mkplanet(50 ,50)\nprint(earth.trias)\nplt.figure()\nplt.scatter( [48,48,52,52],[-50,50,-50,50] )\nfor t in earth.trias:\n tri = np.array(t[:6]).reshape(3,2)\n plt.gca().add_patch(plt.Polygon( tri, color=t[6] ))\nplt.show()\n\nOutput:\n\n"
] | [
0
] | [] | [] | [
"procedural_generation",
"pyglet",
"python"
] | stackoverflow_0074664055_procedural_generation_pyglet_python.txt |
Q:
launch URL in Flet
I'm using Flet and I want for my app to launch a link when clicking on a button.
According to the docs, I can use launch_url method. But when I tried, I got the following error:
Exception in thread Thread-6 (open_repo):
Traceback (most recent call last):
File "C:\Users\Iqmal\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\Iqmal\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
self._target(*self._args, **self._kwargs)
File "d:\Iqmal\Documents\Python Projects\flet-hello\main.py", line 58, in open_repo
ft.page.launch_url('https://github.com/iqfareez/flet-hello')
^^^^^^^^^^^^^^^^^^
AttributeError: 'function' object has no attribute 'launch_url'
Code
import flet as ft
def main(page: ft.Page):
page.padding = ft.Padding(20, 35, 20, 20)
page.theme_mode = ft.ThemeMode.LIGHT
appbar = ft.AppBar(
title=ft.Text(value="Flutter using Flet"),
bgcolor=ft.colors.BLUE,
color=ft.colors.WHITE,
actions=[ft.IconButton(icon=ft.icons.CODE, on_click=open_repo)])
page.controls.append(appbar)
page.update()
def open_repo(e):
ft.page.launch_url('https://github.com/iqfareez/flet-hello')
ft.app(target=main, assets_dir='assets')
A:
To fix the error you're getting, you need to import the page module from the flet library and then create an instance of the page class. Then, you can call the launch_url method on that instance to open a URL in the default web browser.
Here's how you might update your code to do that:
import flet as ft
Import the page module from the flet library
from flet import page
def main(page: ft.Page):
# Create a new page object
my_page = page.Page()
# Set the padding and theme mode for the page
my_page.padding = ft.Padding(20, 35, 20, 20)
my_page.theme_mode = ft.ThemeMode.LIGHT
# Create an app bar and add it to the page
appbar = ft.AppBar(
title=ft.Text(value="Flutter using Flet"),
bgcolor=ft.colors.BLUE,
color=ft.colors.WHITE,
actions=[ft.IconButton(icon=ft.icons.CODE, on_click=open_repo)])
my_page.controls.append(appbar)
# Update the page to display the changes
my_page.update()
def open_repo(e):
# Use the launch_url method to open a URL in the default web browser
my_page.launch_url('https://github.com/iqfareez/flet-hello')
Run the app using the main function as the target
ft.app(target=main, assets_dir='assets')
A:
From what I'm seeing here and the errors you're getting it's just possible you might have a problem with the installation of Flet. Try installing running in a virtual environment and see if it changes.
Good Luck
| launch URL in Flet | I'm using Flet and I want for my app to launch a link when clicking on a button.
According to the docs, I can use launch_url method. But when I tried, I got the following error:
Exception in thread Thread-6 (open_repo):
Traceback (most recent call last):
File "C:\Users\Iqmal\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\Iqmal\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
self._target(*self._args, **self._kwargs)
File "d:\Iqmal\Documents\Python Projects\flet-hello\main.py", line 58, in open_repo
ft.page.launch_url('https://github.com/iqfareez/flet-hello')
^^^^^^^^^^^^^^^^^^
AttributeError: 'function' object has no attribute 'launch_url'
Code
import flet as ft
def main(page: ft.Page):
page.padding = ft.Padding(20, 35, 20, 20)
page.theme_mode = ft.ThemeMode.LIGHT
appbar = ft.AppBar(
title=ft.Text(value="Flutter using Flet"),
bgcolor=ft.colors.BLUE,
color=ft.colors.WHITE,
actions=[ft.IconButton(icon=ft.icons.CODE, on_click=open_repo)])
page.controls.append(appbar)
page.update()
def open_repo(e):
ft.page.launch_url('https://github.com/iqfareez/flet-hello')
ft.app(target=main, assets_dir='assets')
| [
"To fix the error you're getting, you need to import the page module from the flet library and then create an instance of the page class. Then, you can call the launch_url method on that instance to open a URL in the default web browser.\nHere's how you might update your code to do that:\nimport flet as ft\nImport the page module from the flet library\nfrom flet import page\ndef main(page: ft.Page):\n# Create a new page object\nmy_page = page.Page()\n\n# Set the padding and theme mode for the page\nmy_page.padding = ft.Padding(20, 35, 20, 20)\nmy_page.theme_mode = ft.ThemeMode.LIGHT\n\n# Create an app bar and add it to the page\nappbar = ft.AppBar(\n title=ft.Text(value=\"Flutter using Flet\"),\n bgcolor=ft.colors.BLUE,\n color=ft.colors.WHITE,\n actions=[ft.IconButton(icon=ft.icons.CODE, on_click=open_repo)])\n\nmy_page.controls.append(appbar)\n\n# Update the page to display the changes\nmy_page.update()\n\ndef open_repo(e):\n# Use the launch_url method to open a URL in the default web browser\nmy_page.launch_url('https://github.com/iqfareez/flet-hello')\nRun the app using the main function as the target\nft.app(target=main, assets_dir='assets')\n",
"From what I'm seeing here and the errors you're getting it's just possible you might have a problem with the installation of Flet. Try installing running in a virtual environment and see if it changes.\nGood Luck\n"
] | [
0,
0
] | [] | [] | [
"flet",
"flutter",
"python"
] | stackoverflow_0074661326_flet_flutter_python.txt |
Q:
How to crop square inscribed in partial circle?
I have frames of a video taken from a microscope. I need to crop them to a square inscribed to the circle but the issue is that the circle isn't whole (like in the following image). How can I do it?
My idea was to use contour finding to get the center of the circle and then find the distance from each point over the whole array of coordinates to the center, take the maximum distance as the radius and find the corners of the square analytically but there must be a better way to do it (also I don't really have a formula to find the corners).
A:
This may not be adequate in terms of centered at center of circle, but using my iterative processing, one can crop to an approximation of the largest rectangle inside your circle area.
Input:
import cv2
import numpy as np
# read image
img = cv2.imread('img.jpg')
h, w = img.shape[:2]
# threshold so border is black and rest is white (invert as needed).
# Here I needed to specify the upper threshold at 20 as your black is not pure black.
lower = (0,0,0)
upper = (20,20,20)
mask = cv2.inRange(img, lower, upper)
mask = 255 - mask
# define top and left starting coordinates and starting width and height
top = 0
left = 0
bottom = h
right = w
# compute the mean of each side of the image and its stop test
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_bottom, mean_right)
top_test = "stop" if (mean_top == 255) else "go"
left_test = "stop" if (mean_left == 255) else "go"
bottom_test = "stop" if (mean_bottom == 255) else "go"
right_test = "stop" if (mean_right == 255) else "go"
# iterate to compute new side coordinates if mean of given side is not 255 (all white) and it is the current darkest side
while top_test == "go" or left_test == "go" or right_test == "go" or bottom_test == "go":
# top processing
if top_test == "go":
if mean_top != 255:
if mean_top == mean_minimum:
top += 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("top",mean_top)
continue
else:
top_test = "stop"
# left processing
if left_test == "go":
if mean_left != 255:
if mean_left == mean_minimum:
left += 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("left",mean_left)
continue
else:
left_test = "stop"
# bottom processing
if bottom_test == "go":
if mean_bottom != 255:
if mean_bottom == mean_minimum:
bottom -= 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("bottom",mean_bottom)
continue
else:
bottom_test = "stop"
# right processing
if right_test == "go":
if mean_right != 255:
if mean_right == mean_minimum:
right -= 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("right",mean_right)
continue
else:
right_test = "stop"
# crop input
result = img[top:bottom, left:right]
# print crop values
print("top: ",top)
print("bottom: ",bottom)
print("left: ",left)
print("right: ",right)
print("height:",result.shape[0])
print("width:",result.shape[1])
# save cropped image
#cv2.imwrite('border_image1_cropped.png',result)
cv2.imwrite('img_cropped.png',result)
cv2.imwrite('img_mask.png',mask)
# show the images
cv2.imshow("mask", mask)
cv2.imshow("cropped", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result:
A:
Let's start with an illustration of the problem to help with the explanation.
Of course, we have to begin with loading the image. Let's also grab its width and height, since they will be useful later on.
img = cv2.imread('TUP74.jpg', cv2.IMREAD_COLOR)
height, width = img.shape[:2]
First, let's convert the image to grayscale and then apply threshold to make the circle all white, and the background black. I arbitrarily picked a threshold value of 31, which seems to give reasonable results.
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(img_gray, 31, 255, cv2.THRESH_BINARY)
The result of those operations looks like this:
Now, we can determine the "top" and "bottom" of the circle (first_yd and last_yd), by finding the first and last row that contains at least one white pixel. I chose to use cv2.reduce to find the maximum of each row (since the thresholded image only contains 0's and 255's, a non-zero result means there is at least 1 white pixel), followed by cv2.findNonZero to get the row numbers.
reduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)
row_info = cv2.findNonZero(reduced)
first_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]
This information allows us to determine the diameter of the circle d, its radius r (r = d/2), as well as the Y coordinate of the center of the circle center_y.
diameter = last_yd - first_yd
radius = int(diameter / 2)
center_y = first_yd + radius
Next, we need to determine the X coordinate of the center of the circle center_x.
Let's take advantage of the fact that the circle is cropped on the left-hand side. The white pixels in the first column of the threshold image represent a chord c of the circle (red in the diagram).
Again, we begin with finding the "top" and "bottom" of the chord (first_yc and last_yc), but since we're working with a single column, we only need cv2.findNonZero.
row_info = cv2.findNonZero(thresh[:,0])
first_yc, last_yc = row_info[0][0][1], row_info[-1][0][1]
c = last_yc - first_yc
Now we have a nice right-angled triangle with one side adjacent to the right angle being half of the chord c (red in the diagram), the other adjacent side being the unknown offset o, and the hypotenuse (green in the diagram) being the radius of the circle r. Let's apply Pythagoras' theorem:
r2 = (c/2)2 + o2
o2 = r2 - (c/2)2
o = sqrt(r2 - (c/2)2)
And in Python:
center_x = int(math.sqrt(radius**2 - (c/2)**2))
Now we're ready to determine the parameters of the inscribed square. Let's keep in mind that the center of the circle and center of its inscribed square are co-located. Here is another illustration:
We will again use Pythagoras' theorem. The hypotenuse of the right triangle is again the radius r. Both of the sides adjacent to the right angle are of equal length, which is half the length of the side of inscribed square s.
r2 = (s/2)2 + (s/2)2
r2 = 2 × (s/2)2
r2 = 2 × s2/22
r2 = s2/2
s2 = 2 × r2
s = sqrt(2) × r
And in Python:
s = int(math.sqrt(2) * radius)
Finally, we can determine the top-left and bottom-right corners of the inscribed square. Both of those points are offset by s/2 from the common center.
half_s = int(s/2)
tl = (center_x - half_s, center_y - half_s)
br = (center_x + half_s, center_y + half_s)
We have determined all the parameters we need. Let's print them out...
Circle diameter = 1167 pixels
Circle radius = 583 pixels
Circle center = (404,1089)
Inscribed square side = 824 pixels
Inscribed square top-left = (-8,677)
Inscribed square bottom-right = (816,1501)
and visualize the center (green), the detected circle (red) and the inscribed square (blue) on a copy of the input image:
Now we can do the cropping, but first we have to make sure we don't go out of bounds of the source image.
crop_left = max(tl[0], 0)
crop_top = max(tl[1], 0) # Kinda redundant, but why not
crop_right = min(br[0], width)
crop_bottom = min(br[1], height) # ditto
cropped = img[crop_top:crop_bottom, crop_left:crop_right]
And that's it. Here's the cropped image (it's rectangular, since small part of the inscribed square falls outside the source image, and scaled down for embedding -- click to get the full-sized image):
Complete Script
import cv2
import numpy as np
import math
img = cv2.imread('TUP74.jpg', cv2.IMREAD_COLOR)
height, width = img.shape[:2]
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(img_gray, 31, 255, cv2.THRESH_BINARY)
# Find top/bottom of the circle, to determine radius and center
reduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)
row_info = cv2.findNonZero(reduced)
first_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]
diameter = last_yd - first_yd
radius = int(diameter / 2)
center_y = first_yd + radius
# Repeat again, just on first column, to find length of a chord of the circle
row_info = cv2.findNonZero(thresh[:,0])
first_yc, last_yc = row_info[0][0][1], row_info[-1][0][1]
c = last_yc - first_yc
# Apply Pythagoras theorem to find the X offset of the center from the chord
# Since the chord is in row 0, this is also the X coordinate
center_x = int(math.sqrt(radius**2 - (c/2)**2))
# Find length of the side of the inscribed square (Pythagoras again)
s = int(math.sqrt(2) * radius)
# Now find the top-left and bottom-right corners of the square
half_s = int(s/2)
tl = (center_x - half_s, center_y - half_s)
br = (center_x + half_s, center_y + half_s)
# Let's print out what we found
print("Circle diameter = %d pixels" % diameter)
print("Circle radius = %d pixels" % radius)
print("Circle center = (%d,%d)" % (center_x, center_y))
print("Inscribed square side = %d pixels" % s)
print("Inscribed square top-left = (%d,%d)" % tl)
print("Inscribed square bottom-right = (%d,%d)" % br)
# And visualize it...
vis = img.copy()
cv2.line(vis, (center_x-5,center_y), (center_x+5,center_y), (0,255,0), 3)
cv2.line(vis, (center_x,center_y-5), (center_x,center_y+5), (0,255,0), 3)
cv2.circle(vis, (center_x,center_y), radius, (0,0,255), 3)
cv2.rectangle(vis, tl, br, (255,0,0), 3)
# Write some illustration images
cv2.imwrite('circ_thresh.png', thresh)
cv2.imwrite('circ_vis.png', vis)
# Time to do some cropping, but we need to make sure the coordinates are inside the bounds of the image
crop_left = max(tl[0], 0)
crop_top = max(tl[1], 0) # Kinda redundant, but why not
crop_right = min(br[0], width)
crop_bottom = min(br[1], height) # ditto
cropped = img[crop_top:crop_bottom, crop_left:crop_right]
cv2.imwrite('circ_cropped.png', cropped)
NB: The main focus of this was the explanation of the algorithm. I've been kinda blunt on rounding the values, and there may be some off-by-one errors. For the sake of brevity, error checking is minimal. It's left as an excercise to the reader to address those issues as necessary.
Furthermore, the assumption is that the left-hand side of the circle is cropped as in the sample image. It should be fairly trivial to extend this to handle other possible scenarios, using the techniques I've demonstrated.
A:
Building on Dan Mašek's answer, here is an alternate method of computing the center and radius in Python/OpenCV/Numpy, in particular, the x-coordinate of the center.
The idea is simply find the coordinate of column that has the largest non-zero count in the thresholded image.
Input:
import cv2
import numpy as np
import math
img = cv2.imread('img_circle.jpg')
height, width = img.shape[:2]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 31, 255, cv2.THRESH_BINARY)[1]
# Find top/bottom of the circle, to determine radius and y coordinate center
reduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)
row_info = cv2.findNonZero(reduced)
first_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]
diameter = last_yd - first_yd
radius = int(diameter / 2)
center_y = first_yd + radius
# count non-zero pixels in columns to find the column with the largest count
# that will give us the x coordinate center
col_counts = np.count_nonzero(thresh, axis=0)
max_counts = np.amax(col_counts)
# find index (x-coordinate) where col_counts=max_counts
max_coords = np.argwhere(col_counts==max_counts)
# get number of max values in case more than one
num_max = len(max_coords)
# compute center_y
center_x = max_coords[0][0] + num_max//2
print("radius:", radius, "center_x:", center_x, "center_y:", center_y)
print('')
Result:
radius: 583 center_x: 388 center_y: 1089
The rest is the same as in Dan Mašek's answer.
A:
Find the edge points of the image circle, and then fit a circle to the edge.
Or, you may be able to use minEnclosingCircle() instead of circle fitting.
(I omit the explanation of the subsequent steps for obtaining a square.)
| How to crop square inscribed in partial circle? | I have frames of a video taken from a microscope. I need to crop them to a square inscribed to the circle but the issue is that the circle isn't whole (like in the following image). How can I do it?
My idea was to use contour finding to get the center of the circle and then find the distance from each point over the whole array of coordinates to the center, take the maximum distance as the radius and find the corners of the square analytically but there must be a better way to do it (also I don't really have a formula to find the corners).
| [
"This may not be adequate in terms of centered at center of circle, but using my iterative processing, one can crop to an approximation of the largest rectangle inside your circle area.\nInput:\n\nimport cv2\nimport numpy as np\n\n# read image\nimg = cv2.imread('img.jpg')\nh, w = img.shape[:2]\n\n# threshold so border is black and rest is white (invert as needed). \n# Here I needed to specify the upper threshold at 20 as your black is not pure black.\n\nlower = (0,0,0)\nupper = (20,20,20)\nmask = cv2.inRange(img, lower, upper)\nmask = 255 - mask\n\n# define top and left starting coordinates and starting width and height\ntop = 0\nleft = 0\nbottom = h\nright = w\n\n# compute the mean of each side of the image and its stop test\nmean_top = np.mean( mask[top:top+1, left:right] )\nmean_left = np.mean( mask[top:bottom, left:left+1] )\nmean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\nmean_right = np.mean( mask[top:bottom, right-1:right] )\n\nmean_minimum = min(mean_top, mean_left, mean_bottom, mean_right)\n\ntop_test = \"stop\" if (mean_top == 255) else \"go\"\nleft_test = \"stop\" if (mean_left == 255) else \"go\"\nbottom_test = \"stop\" if (mean_bottom == 255) else \"go\"\nright_test = \"stop\" if (mean_right == 255) else \"go\"\n\n# iterate to compute new side coordinates if mean of given side is not 255 (all white) and it is the current darkest side\nwhile top_test == \"go\" or left_test == \"go\" or right_test == \"go\" or bottom_test == \"go\":\n\n # top processing\n if top_test == \"go\":\n if mean_top != 255:\n if mean_top == mean_minimum:\n top += 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"top\",mean_top)\n continue\n else:\n top_test = \"stop\" \n\n # left processing\n if left_test == \"go\":\n if mean_left != 255:\n if mean_left == mean_minimum:\n left += 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"left\",mean_left)\n continue\n else:\n left_test = \"stop\" \n\n # bottom processing\n if bottom_test == \"go\":\n if mean_bottom != 255:\n if mean_bottom == mean_minimum:\n bottom -= 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"bottom\",mean_bottom)\n continue\n else:\n bottom_test = \"stop\" \n\n # right processing\n if right_test == \"go\":\n if mean_right != 255:\n if mean_right == mean_minimum:\n right -= 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"right\",mean_right)\n continue\n else:\n right_test = \"stop\" \n\n\n# crop input\nresult = img[top:bottom, left:right]\n\n# print crop values \nprint(\"top: \",top)\nprint(\"bottom: \",bottom)\nprint(\"left: \",left)\nprint(\"right: \",right)\nprint(\"height:\",result.shape[0])\nprint(\"width:\",result.shape[1])\n\n# save cropped image\n#cv2.imwrite('border_image1_cropped.png',result)\ncv2.imwrite('img_cropped.png',result)\ncv2.imwrite('img_mask.png',mask)\n\n# show the images\ncv2.imshow(\"mask\", mask)\ncv2.imshow(\"cropped\", result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nResult:\n\n",
"Let's start with an illustration of the problem to help with the explanation.\n\n\nOf course, we have to begin with loading the image. Let's also grab its width and height, since they will be useful later on.\nimg = cv2.imread('TUP74.jpg', cv2.IMREAD_COLOR)\nheight, width = img.shape[:2]\n\n\nFirst, let's convert the image to grayscale and then apply threshold to make the circle all white, and the background black. I arbitrarily picked a threshold value of 31, which seems to give reasonable results.\nimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n_, thresh = cv2.threshold(img_gray, 31, 255, cv2.THRESH_BINARY)\n\nThe result of those operations looks like this:\n\n\nNow, we can determine the \"top\" and \"bottom\" of the circle (first_yd and last_yd), by finding the first and last row that contains at least one white pixel. I chose to use cv2.reduce to find the maximum of each row (since the thresholded image only contains 0's and 255's, a non-zero result means there is at least 1 white pixel), followed by cv2.findNonZero to get the row numbers.\nreduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)\nrow_info = cv2.findNonZero(reduced)\nfirst_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]\n\nThis information allows us to determine the diameter of the circle d, its radius r (r = d/2), as well as the Y coordinate of the center of the circle center_y.\ndiameter = last_yd - first_yd\nradius = int(diameter / 2)\ncenter_y = first_yd + radius\n\n\nNext, we need to determine the X coordinate of the center of the circle center_x.\nLet's take advantage of the fact that the circle is cropped on the left-hand side. The white pixels in the first column of the threshold image represent a chord c of the circle (red in the diagram).\nAgain, we begin with finding the \"top\" and \"bottom\" of the chord (first_yc and last_yc), but since we're working with a single column, we only need cv2.findNonZero.\nrow_info = cv2.findNonZero(thresh[:,0])\nfirst_yc, last_yc = row_info[0][0][1], row_info[-1][0][1]\n\nc = last_yc - first_yc\n\nNow we have a nice right-angled triangle with one side adjacent to the right angle being half of the chord c (red in the diagram), the other adjacent side being the unknown offset o, and the hypotenuse (green in the diagram) being the radius of the circle r. Let's apply Pythagoras' theorem:\nr2 = (c/2)2 + o2\no2 = r2 - (c/2)2\no = sqrt(r2 - (c/2)2)\nAnd in Python:\ncenter_x = int(math.sqrt(radius**2 - (c/2)**2))\n\n\nNow we're ready to determine the parameters of the inscribed square. Let's keep in mind that the center of the circle and center of its inscribed square are co-located. Here is another illustration:\n\nWe will again use Pythagoras' theorem. The hypotenuse of the right triangle is again the radius r. Both of the sides adjacent to the right angle are of equal length, which is half the length of the side of inscribed square s.\nr2 = (s/2)2 + (s/2)2\nr2 = 2 × (s/2)2\nr2 = 2 × s2/22\nr2 = s2/2\ns2 = 2 × r2\ns = sqrt(2) × r\n\nAnd in Python:\ns = int(math.sqrt(2) * radius)\n\nFinally, we can determine the top-left and bottom-right corners of the inscribed square. Both of those points are offset by s/2 from the common center.\nhalf_s = int(s/2)\ntl = (center_x - half_s, center_y - half_s)\nbr = (center_x + half_s, center_y + half_s)\n\n\nWe have determined all the parameters we need. Let's print them out...\nCircle diameter = 1167 pixels\nCircle radius = 583 pixels\nCircle center = (404,1089)\nInscribed square side = 824 pixels\nInscribed square top-left = (-8,677)\nInscribed square bottom-right = (816,1501)\n\nand visualize the center (green), the detected circle (red) and the inscribed square (blue) on a copy of the input image:\n\n\nNow we can do the cropping, but first we have to make sure we don't go out of bounds of the source image.\ncrop_left = max(tl[0], 0)\ncrop_top = max(tl[1], 0) # Kinda redundant, but why not\ncrop_right = min(br[0], width)\ncrop_bottom = min(br[1], height) # ditto\n\ncropped = img[crop_top:crop_bottom, crop_left:crop_right]\n\nAnd that's it. Here's the cropped image (it's rectangular, since small part of the inscribed square falls outside the source image, and scaled down for embedding -- click to get the full-sized image):\n\n\nComplete Script\nimport cv2\nimport numpy as np\nimport math\n\nimg = cv2.imread('TUP74.jpg', cv2.IMREAD_COLOR)\nheight, width = img.shape[:2]\n\nimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n_, thresh = cv2.threshold(img_gray, 31, 255, cv2.THRESH_BINARY)\n\n# Find top/bottom of the circle, to determine radius and center\nreduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)\nrow_info = cv2.findNonZero(reduced)\nfirst_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]\n\ndiameter = last_yd - first_yd\nradius = int(diameter / 2)\ncenter_y = first_yd + radius\n\n# Repeat again, just on first column, to find length of a chord of the circle\nrow_info = cv2.findNonZero(thresh[:,0])\nfirst_yc, last_yc = row_info[0][0][1], row_info[-1][0][1]\n\nc = last_yc - first_yc\n\n# Apply Pythagoras theorem to find the X offset of the center from the chord\n# Since the chord is in row 0, this is also the X coordinate\ncenter_x = int(math.sqrt(radius**2 - (c/2)**2))\n\n# Find length of the side of the inscribed square (Pythagoras again)\ns = int(math.sqrt(2) * radius)\n\n# Now find the top-left and bottom-right corners of the square\nhalf_s = int(s/2)\ntl = (center_x - half_s, center_y - half_s)\nbr = (center_x + half_s, center_y + half_s)\n\n# Let's print out what we found\nprint(\"Circle diameter = %d pixels\" % diameter)\nprint(\"Circle radius = %d pixels\" % radius)\nprint(\"Circle center = (%d,%d)\" % (center_x, center_y))\nprint(\"Inscribed square side = %d pixels\" % s)\nprint(\"Inscribed square top-left = (%d,%d)\" % tl)\nprint(\"Inscribed square bottom-right = (%d,%d)\" % br)\n\n# And visualize it...\nvis = img.copy()\ncv2.line(vis, (center_x-5,center_y), (center_x+5,center_y), (0,255,0), 3)\ncv2.line(vis, (center_x,center_y-5), (center_x,center_y+5), (0,255,0), 3)\ncv2.circle(vis, (center_x,center_y), radius, (0,0,255), 3)\ncv2.rectangle(vis, tl, br, (255,0,0), 3)\n\n# Write some illustration images\ncv2.imwrite('circ_thresh.png', thresh)\ncv2.imwrite('circ_vis.png', vis)\n\n# Time to do some cropping, but we need to make sure the coordinates are inside the bounds of the image\ncrop_left = max(tl[0], 0)\ncrop_top = max(tl[1], 0) # Kinda redundant, but why not\ncrop_right = min(br[0], width)\ncrop_bottom = min(br[1], height) # ditto\n\ncropped = img[crop_top:crop_bottom, crop_left:crop_right]\ncv2.imwrite('circ_cropped.png', cropped)\n\n\nNB: The main focus of this was the explanation of the algorithm. I've been kinda blunt on rounding the values, and there may be some off-by-one errors. For the sake of brevity, error checking is minimal. It's left as an excercise to the reader to address those issues as necessary.\nFurthermore, the assumption is that the left-hand side of the circle is cropped as in the sample image. It should be fairly trivial to extend this to handle other possible scenarios, using the techniques I've demonstrated.\n",
"Building on Dan Mašek's answer, here is an alternate method of computing the center and radius in Python/OpenCV/Numpy, in particular, the x-coordinate of the center.\nThe idea is simply find the coordinate of column that has the largest non-zero count in the thresholded image.\nInput:\n\nimport cv2\nimport numpy as np\nimport math\n\nimg = cv2.imread('img_circle.jpg')\nheight, width = img.shape[:2]\n\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nthresh = cv2.threshold(gray, 31, 255, cv2.THRESH_BINARY)[1]\n\n# Find top/bottom of the circle, to determine radius and y coordinate center\nreduced = cv2.reduce(thresh, 1, cv2.REDUCE_MAX)\nrow_info = cv2.findNonZero(reduced)\nfirst_yd, last_yd = row_info[0][0][1], row_info[-1][0][1]\n\ndiameter = last_yd - first_yd\nradius = int(diameter / 2)\ncenter_y = first_yd + radius\n\n# count non-zero pixels in columns to find the column with the largest count\n# that will give us the x coordinate center\ncol_counts = np.count_nonzero(thresh, axis=0)\nmax_counts = np.amax(col_counts)\n\n# find index (x-coordinate) where col_counts=max_counts\nmax_coords = np.argwhere(col_counts==max_counts)\n\n# get number of max values in case more than one\nnum_max = len(max_coords)\n\n# compute center_y\ncenter_x = max_coords[0][0] + num_max//2\n\nprint(\"radius:\", radius, \"center_x:\", center_x, \"center_y:\", center_y)\nprint('')\n\nResult:\nradius: 583 center_x: 388 center_y: 1089\n\nThe rest is the same as in Dan Mašek's answer.\n",
"Find the edge points of the image circle, and then fit a circle to the edge.\nOr, you may be able to use minEnclosingCircle() instead of circle fitting.\n(I omit the explanation of the subsequent steps for obtaining a square.)\n"
] | [
6,
4,
1,
0
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0074645811_image_processing_opencv_python.txt |
Q:
Passing a function's output as a parameter of another function
I'm having a hard time figuring out how to pass a function's return as a parameter to another function. I've searched a lot of threads that are deviations of this problem but I can't think of a solution from them. My code isn't good yet, but I just need help on the line where the error is occurring to start with.
Instructions:
create a function that asks the user to enter their birthday and returns a date object. Validate user input as well. This function must NOT take any parameters.
create another function that takes the date object as a parameter. Calculate the age of the user using their birth year and the current year.
def func1():
bd = input("When is your birthday? ")
try:
dt.datetime.strptime(bd, "%m/%d/%Y")
except ValueError as e:
print("There is a ValueError. Please format as MM/DD/YYY")
except Exception as e:
print(e)
return bd
def func2(bd):
today = dt.datetime.today()
age = today.year - bd.year
return age
This is the Error I get:
TypeError: func2() missing 1 required positional argument: 'bday'
So far, I've tried:
assigning the func1 to a variable and passing the variable as func2 parameter
calling func1 inside func2
defining func1 inside func2
A:
You can't use a function as a parameter, I think what you want to do is use it as an argument. You can do it like this:
import datetime as dt
def func1():
bd = input("When is your birthday? ")
try:
dt.datetime.strptime(bd, "%m/%d/%Y")
except ValueError as e:
print("There is a ValueError. Please format as MM/DD/YYY")
except Exception as e:
print(e)
return bd
def func2(bd)
today = dt.datetime.today()
age = today.year - bd.year
return age
func2(func1)
There are still some errors to be solved but the problem you had should be solved there
A:
You're almost there, a few subtleties to consider:
The datetime object must be assigned to a variable and returned.
Your code was not assigning the datetime object, but returning a str object for input into func2. Which would have thrown an attribute error as a str has no year attribute.
Simply subtracting the years will not always give the age. What if the individual's date of birth has not yet come? In this case, 1 must be subtracted. (Notice the code update below).
For example:
from datetime import datetime as dt
def func1():
bday = input("When is your birthday? Enter as MM/DD/YYYY: ")
try:
# Assign the datetime object.
dte = dt.strptime(bday, "%m/%d/%Y")
except ValueError as e:
print("There is a ValueError. Please format as MM/DD/YYYY")
except Exception as e:
print(e)
return dte # <-- Return the datetime, not a string.
def func2(bdate):
today = dt.today()
# Account for the date of birth not yet arriving.
age = today.year - bdate.year - ((today.month, today.day) < (bdate.month, bdate.day))
return age
Can be called using:
func2(bdate=func1())
| Passing a function's output as a parameter of another function | I'm having a hard time figuring out how to pass a function's return as a parameter to another function. I've searched a lot of threads that are deviations of this problem but I can't think of a solution from them. My code isn't good yet, but I just need help on the line where the error is occurring to start with.
Instructions:
create a function that asks the user to enter their birthday and returns a date object. Validate user input as well. This function must NOT take any parameters.
create another function that takes the date object as a parameter. Calculate the age of the user using their birth year and the current year.
def func1():
bd = input("When is your birthday? ")
try:
dt.datetime.strptime(bd, "%m/%d/%Y")
except ValueError as e:
print("There is a ValueError. Please format as MM/DD/YYY")
except Exception as e:
print(e)
return bd
def func2(bd):
today = dt.datetime.today()
age = today.year - bd.year
return age
This is the Error I get:
TypeError: func2() missing 1 required positional argument: 'bday'
So far, I've tried:
assigning the func1 to a variable and passing the variable as func2 parameter
calling func1 inside func2
defining func1 inside func2
| [
"You can't use a function as a parameter, I think what you want to do is use it as an argument. You can do it like this:\nimport datetime as dt\n\ndef func1():\n bd = input(\"When is your birthday? \")\n try:\n dt.datetime.strptime(bd, \"%m/%d/%Y\")\n except ValueError as e:\n print(\"There is a ValueError. Please format as MM/DD/YYY\")\n except Exception as e:\n print(e)\n return bd\n\ndef func2(bd)\n today = dt.datetime.today()\n age = today.year - bd.year\n return age\n\nfunc2(func1)\n\nThere are still some errors to be solved but the problem you had should be solved there\n",
"You're almost there, a few subtleties to consider:\n\nThe datetime object must be assigned to a variable and returned.\nYour code was not assigning the datetime object, but returning a str object for input into func2. Which would have thrown an attribute error as a str has no year attribute.\nSimply subtracting the years will not always give the age. What if the individual's date of birth has not yet come? In this case, 1 must be subtracted. (Notice the code update below).\n\nFor example:\nfrom datetime import datetime as dt\n\ndef func1():\n bday = input(\"When is your birthday? Enter as MM/DD/YYYY: \")\n try:\n # Assign the datetime object.\n dte = dt.strptime(bday, \"%m/%d/%Y\")\n except ValueError as e:\n print(\"There is a ValueError. Please format as MM/DD/YYYY\")\n except Exception as e:\n print(e)\n return dte # <-- Return the datetime, not a string.\n\ndef func2(bdate):\n today = dt.today()\n # Account for the date of birth not yet arriving.\n age = today.year - bdate.year - ((today.month, today.day) < (bdate.month, bdate.day))\n return age\n\nCan be called using:\nfunc2(bdate=func1())\n\n"
] | [
0,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074663224_function_python.txt |
Q:
How can I turn a xy-meshgrid and a 1D array into a contour?
So I have a csv file (which I have read with pandas), which has 3 columns the first column corresponds to the x-axis, the second column the y-axis and the third column is the value for the free energy, we can interpret that as the z-axis or the height of the xy-plane. I have create a meshgrid with my x,y colums which has the shape (6105,6105). The z-axis is just a 1D array with the length 6105. I can't find a way to combine my z-axis with the xy grid, in order for me to depict it in a contour. Does anybody have an idea of how to do it?
My code:
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits import mplot3d
import os
import numpy as np
import math
current_dir = os.path.abspath(os.getcwd())
file_path = (current_dir + '/__files/fes.csv')
df = pd.read_csv(file_path, sep=r'\t', engine='python')
df.drop(df[df['free energy (kJ/mol)'] == math.inf].index, inplace=True)
x = df['CV1']
y = df['CV2']
z = df['free energy (kJ/mol)']
x_array = np.array(x)
y_array = np.array(y)
z_array = np.array(z)
z_reshaped = z_array.reshape(int(math.sqrt(len(x_array))), int(math.sqrt(len(y_array))))
X , Y = np.meshgrid(x, y, sparse=True)
plt.contour(X, Y, z_reshaped)
plt.show()
And I get the following error
z_reshaped = z_array.reshape(int(math.sqrt(len(x_array))), int(math.sqrt(len(y_array))))
ValueError: cannot reshape array of size 6105 into shape (78,78)
After checking the other stack overflow threads on the topic of reshaping, I couldn't find the answer of how to reshape my z-array to my xy-meshgrid. Each x, y, z have the size 6105.
I want the output to be the left image
I tried using the reshape function:
z_reshape = z.reshape(-1,1) # => 2D array
but I didn't work. Afterwords I tried putting all three in a mesh grid like
X, Y, Z =np.meshgrid(x, y, z)
but it could not compile.
At last I created a mesh grid with both inputs being z but of course it didn't work
Z, Z = np.meshgrid(z, z)
A:
Use the contour() function from the matplotlib library. This function takes in three arguments: x,y,z.
You can reshape your z array to be the same size as your X and Y arrays using the reshape() method. Then, you can pass all three arrays to the contour() function to generate your desired contour plot.
import matplotlib.pyplot as plt
# Reshape your z array to be the same size as X and Y
z_reshaped = z.reshape(X.shape)
# Generate the contour plot using contour()
plt.contour(X, Y, z_reshaped)
# Show the plot
plt.show()
customize the contour plot by setting options such as the number of contour levels, the color map, and the line styles.
| How can I turn a xy-meshgrid and a 1D array into a contour? | So I have a csv file (which I have read with pandas), which has 3 columns the first column corresponds to the x-axis, the second column the y-axis and the third column is the value for the free energy, we can interpret that as the z-axis or the height of the xy-plane. I have create a meshgrid with my x,y colums which has the shape (6105,6105). The z-axis is just a 1D array with the length 6105. I can't find a way to combine my z-axis with the xy grid, in order for me to depict it in a contour. Does anybody have an idea of how to do it?
My code:
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits import mplot3d
import os
import numpy as np
import math
current_dir = os.path.abspath(os.getcwd())
file_path = (current_dir + '/__files/fes.csv')
df = pd.read_csv(file_path, sep=r'\t', engine='python')
df.drop(df[df['free energy (kJ/mol)'] == math.inf].index, inplace=True)
x = df['CV1']
y = df['CV2']
z = df['free energy (kJ/mol)']
x_array = np.array(x)
y_array = np.array(y)
z_array = np.array(z)
z_reshaped = z_array.reshape(int(math.sqrt(len(x_array))), int(math.sqrt(len(y_array))))
X , Y = np.meshgrid(x, y, sparse=True)
plt.contour(X, Y, z_reshaped)
plt.show()
And I get the following error
z_reshaped = z_array.reshape(int(math.sqrt(len(x_array))), int(math.sqrt(len(y_array))))
ValueError: cannot reshape array of size 6105 into shape (78,78)
After checking the other stack overflow threads on the topic of reshaping, I couldn't find the answer of how to reshape my z-array to my xy-meshgrid. Each x, y, z have the size 6105.
I want the output to be the left image
I tried using the reshape function:
z_reshape = z.reshape(-1,1) # => 2D array
but I didn't work. Afterwords I tried putting all three in a mesh grid like
X, Y, Z =np.meshgrid(x, y, z)
but it could not compile.
At last I created a mesh grid with both inputs being z but of course it didn't work
Z, Z = np.meshgrid(z, z)
| [
"Use the contour() function from the matplotlib library. This function takes in three arguments: x,y,z.\nYou can reshape your z array to be the same size as your X and Y arrays using the reshape() method. Then, you can pass all three arrays to the contour() function to generate your desired contour plot.\nimport matplotlib.pyplot as plt\n\n# Reshape your z array to be the same size as X and Y\nz_reshaped = z.reshape(X.shape)\n\n# Generate the contour plot using contour()\nplt.contour(X, Y, z_reshaped)\n\n# Show the plot\nplt.show()\n\ncustomize the contour plot by setting options such as the number of contour levels, the color map, and the line styles.\n"
] | [
0
] | [] | [] | [
"3d",
"contour",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074670095_3d_contour_matplotlib_numpy_python.txt |
Q:
How to find if elements of a column in a data frame are string-contained by the elements of a column of another data frame?
I have a data frame tweets_df that looks like this:
sentiment id date text
0 0 1502071360117424136 2022-03-10 23:58:14+00:00 AngelaRaeBoon1 Same Alabama Republicans charge...
1 0 1502070916318121994 2022-03-10 23:56:28+00:00 This ’ w/the sentencing JussieSmollett But mad...
2 0 1502057466267377665 2022-03-10 23:03:01+00:00 DannyClayton Not hard find takes smallest amou...
3 0 1502053718711316512 2022-03-10 22:48:08+00:00 I make fake scenarios getting fights protectin...
4 0 1502045714486022146 2022-03-10 22:16:19+00:00 WipeHomophobia Well people lands wildest thing...
.. ... ... ... ...
94 0 1501702542899691525 2022-03-09 23:32:41+00:00 There 's reason deep look things kill bad peop...
95 0 1501700281729433606 2022-03-09 23:23:42+00:00 Shame UN United Dictators Shame NATO Repeat We...
96 0 1501699859803516934 2022-03-09 23:22:01+00:00 GayleKing The difference Ukrainian refugees IL...
97 0 1501697172441550848 2022-03-09 23:11:20+00:00 hrkbenowen And includes new United States I un...
98 0 1501696149853511687 2022-03-09 23:07:16+00:00 JLaw_OTD A world women minorities POC LGBTQ÷ d...
And the second dataFrame globe_df that looks like this:
Country Region
0 Andorra Europe
1 United Arab Emirates Middle east
2 Afghanistan Asia & Pacific
3 Antigua and Barbuda South/Latin America
4 Anguilla South/Latin America
.. ... ...
243 Guernsey Europe
244 Isle of Man Europe
245 Jersey Europe
246 Saint Barthelemy South/Latin America
247 Saint Martin South/Latin America
I want to delete all rows of the dataframe tweets_df which have 'text' that does not contain a 'Country' or 'Region'.
This was my attempt:
globe_df = pd.read_csv('countriesAndRegions.csv')
tweets_df = pd.read_csv('tweetSheet.csv')
for entry in globe_df['Country']:
tweet_index = tweets_df[entry in tweets_df['text']].index # if tweets that *contain*, not equal...... entry in tweets_df['text] .... (in)or (not in)?
tweets_df.drop(tweet_index , inplace=True)
print(tweets_df)
Edit: Also, fuzzy, case-insensitive matching with stemming would be preferred when searching the 'text' for countries and regions.
Ex) If the text contained 'Ukrainian', 'british', 'engliSH', etc... then it would not be deleted
A:
Convert country and region values to a list and use str.contains to filter out rows that do not contain these values.
#with case insensitive
vals=globe_df.stack().to_list()
tweets_df = tweets_df[tweets_df ['text'].str.contains('|'.join(vals), regex=True, case=False)]
or (with case insensitive)
vals="({})".format('|'.join(globe_df.stack().str.lower().to_list())) #make all letters lowercase
tweets_df['matched'] = tweets_df.text.str.lower().str.extract(vals, expand=False)
tweets_df = tweets_df.dropna()
| How to find if elements of a column in a data frame are string-contained by the elements of a column of another data frame? | I have a data frame tweets_df that looks like this:
sentiment id date text
0 0 1502071360117424136 2022-03-10 23:58:14+00:00 AngelaRaeBoon1 Same Alabama Republicans charge...
1 0 1502070916318121994 2022-03-10 23:56:28+00:00 This ’ w/the sentencing JussieSmollett But mad...
2 0 1502057466267377665 2022-03-10 23:03:01+00:00 DannyClayton Not hard find takes smallest amou...
3 0 1502053718711316512 2022-03-10 22:48:08+00:00 I make fake scenarios getting fights protectin...
4 0 1502045714486022146 2022-03-10 22:16:19+00:00 WipeHomophobia Well people lands wildest thing...
.. ... ... ... ...
94 0 1501702542899691525 2022-03-09 23:32:41+00:00 There 's reason deep look things kill bad peop...
95 0 1501700281729433606 2022-03-09 23:23:42+00:00 Shame UN United Dictators Shame NATO Repeat We...
96 0 1501699859803516934 2022-03-09 23:22:01+00:00 GayleKing The difference Ukrainian refugees IL...
97 0 1501697172441550848 2022-03-09 23:11:20+00:00 hrkbenowen And includes new United States I un...
98 0 1501696149853511687 2022-03-09 23:07:16+00:00 JLaw_OTD A world women minorities POC LGBTQ÷ d...
And the second dataFrame globe_df that looks like this:
Country Region
0 Andorra Europe
1 United Arab Emirates Middle east
2 Afghanistan Asia & Pacific
3 Antigua and Barbuda South/Latin America
4 Anguilla South/Latin America
.. ... ...
243 Guernsey Europe
244 Isle of Man Europe
245 Jersey Europe
246 Saint Barthelemy South/Latin America
247 Saint Martin South/Latin America
I want to delete all rows of the dataframe tweets_df which have 'text' that does not contain a 'Country' or 'Region'.
This was my attempt:
globe_df = pd.read_csv('countriesAndRegions.csv')
tweets_df = pd.read_csv('tweetSheet.csv')
for entry in globe_df['Country']:
tweet_index = tweets_df[entry in tweets_df['text']].index # if tweets that *contain*, not equal...... entry in tweets_df['text] .... (in)or (not in)?
tweets_df.drop(tweet_index , inplace=True)
print(tweets_df)
Edit: Also, fuzzy, case-insensitive matching with stemming would be preferred when searching the 'text' for countries and regions.
Ex) If the text contained 'Ukrainian', 'british', 'engliSH', etc... then it would not be deleted
| [
"Convert country and region values to a list and use str.contains to filter out rows that do not contain these values.\n#with case insensitive\nvals=globe_df.stack().to_list()\n\ntweets_df = tweets_df[tweets_df ['text'].str.contains('|'.join(vals), regex=True, case=False)]\n\nor (with case insensitive)\nvals=\"({})\".format('|'.join(globe_df.stack().str.lower().to_list())) #make all letters lowercase\ntweets_df['matched'] = tweets_df.text.str.lower().str.extract(vals, expand=False)\ntweets_df = tweets_df.dropna()\n\n"
] | [
0
] | [
"You can try using pandas.Series.str.contains to find the values.\ntweets_df[tweets_df['text'].contains('{}|{}'.format(entry['Country'],entry['Region'])]\n\nAnd after creating a new column with boolean values, you can remove rows with the value True.\n",
"# Import data\nglobe_df = pd.read_csv('countriesAndRegions.csv')\ntweets_df = pd.read_csv('tweetSheet.csv')\n# Get country and region column as list\nglobe_df_country = globe_df['Country'].values.tolist()\nglobe_df_region = globe_df['Region'].values.tolist()\n# merge_lists, cause you want to check with or operator\nmerged_list = globe_df_country + globe_df_region\n# If you want to update df while iterating it, best way to do it with using copy df\ndf_tweets2 = tweets_df.copy()\nfor index,row in tweets_df.iterrows():\n # Check if splitted row's text values are intersecting with merged_list\n if [i for i in merged_list if i in row['text'].split()] == []:\n df_tweets2 = df_tweets2.drop[index]\ntweets_df_new = df_tweets2.copy()\nprint(tweets_df_new) \n \n\n"
] | [
-1,
-1
] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074669715_dataframe_pandas_python.txt |
Q:
Simple question, Finding word count within file trouble
I've looked up a simple way to file word count for a file but it keeps giving me zero
output
script
A:
This should hopefully solve your problem. The split is only set to count words separated by spaces. Hope this helps!
fileName = input('Enter File Name: ')
with open(fileName,'r') as file:
lineCnt = 0
wordCnt = 0
for i in file:
lineCnt += 1
for j in i.split():
wordCnt += 1
print(lineCnt,wordCnt)
| Simple question, Finding word count within file trouble | I've looked up a simple way to file word count for a file but it keeps giving me zero
output
script
| [
"This should hopefully solve your problem. The split is only set to count words separated by spaces. Hope this helps!\nfileName = input('Enter File Name: ')\nwith open(fileName,'r') as file:\n lineCnt = 0\n wordCnt = 0\n for i in file:\n lineCnt += 1\n for j in i.split():\n wordCnt += 1\nprint(lineCnt,wordCnt)\n\n"
] | [
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074670150_file_python.txt |
Q:
python selenium alternative for web actions
I am constantly waiting for the page to load in web actions. Is there a way to do web actions faster without waiting for the page to load ?
When working with Selenium, it takes time to navigate from page to page.
A:
If your use case does not require opening an actual browser and interacting with the webpage through simulated user input, then you can use HTTP requests to extract/manipulate data from the page. Popular modules for this are Requests and BeautifulSoup.
| python selenium alternative for web actions | I am constantly waiting for the page to load in web actions. Is there a way to do web actions faster without waiting for the page to load ?
When working with Selenium, it takes time to navigate from page to page.
| [
"If your use case does not require opening an actual browser and interacting with the webpage through simulated user input, then you can use HTTP requests to extract/manipulate data from the page. Popular modules for this are Requests and BeautifulSoup.\n"
] | [
0
] | [] | [] | [
"automation",
"bots",
"javascript",
"python",
"selenium"
] | stackoverflow_0074669684_automation_bots_javascript_python_selenium.txt |
Q:
Transform For loop into while loop
s=0
for i in range(3,20,2):
if i>10:
break
else:
s=s+i
print(s)
how can i transform this code into a while loop?
I don't know how to include the step.
A:
s = 0
i = 3
while i<10:
s+=i
i+=2
print(s)
A:
If you want to break the loop when i>10, then why you're running the loop till 20? Any way you can try this
s,i=0,3
while i<=20:
if i>10:
break
else:
s=s+i
i+=2
print(s)
A:
Here's how you can transform the for loop into a while loop:
s = 0
i = 3
while i < 20:
if i > 10:
break
else:
s = s + i
i += 2
print(s)
A:
Why reinvent something when you could do this using a range and the sum functions:
>>> sum(range(3,10, 2))
24
| Transform For loop into while loop | s=0
for i in range(3,20,2):
if i>10:
break
else:
s=s+i
print(s)
how can i transform this code into a while loop?
I don't know how to include the step.
| [
"s = 0\ni = 3\nwhile i<10:\n s+=i\n i+=2\nprint(s)\n\n",
"If you want to break the loop when i>10, then why you're running the loop till 20? Any way you can try this\ns,i=0,3\nwhile i<=20:\n if i>10:\n break\n else:\n s=s+i\n i+=2\nprint(s)\n\n",
"Here's how you can transform the for loop into a while loop:\ns = 0\ni = 3\nwhile i < 20:\n if i > 10:\n break\n else:\n s = s + i\n i += 2\nprint(s)\n\n",
"Why reinvent something when you could do this using a range and the sum functions:\n>>> sum(range(3,10, 2))\n24\n\n"
] | [
1,
0,
0,
0
] | [] | [] | [
"for_loop",
"python",
"while_loop"
] | stackoverflow_0074669923_for_loop_python_while_loop.txt |
Q:
Check for None in pandas dataframe
I would like to find where None is found in the dataframe.
pd.DataFrame([None,np.nan]).isnull()
OUT:
0
0 True
1 True
isnull() finds both numpy Nan and None values.
I only want the None values and not numpy Nan. Is there an easier way to do that without looping through the dataframe?
Edit:
After reading the comments, I realized that in my dataframe in my work also include strings, so the None were not coerced to numpy Nan. So the answer given by Pisdom works.
A:
If you want to get True/False for each line, you can use the following code. Here is an example as a result for the following DataFrame:
df = pd.DataFrame([[None, 3], ["", np.nan]])
df
# 0 1
#0 None 3.0
#1 NaN
How to check None
Available: .isnull()
>>> df[0].isnull()
0 True
1 False
Name: 0, dtype: bool
Available: .apply == or is None
>>> df[0].apply(lambda x: x == None)
0 True
1 False
Name: 0, dtype: bool
>>> df[0].apply(lambda x: x is None)
0 True
1 False
Name: 0, dtype: bool
Available: .values == None
>>> df[0].values == None
array([ True, False])
Unavailable: is or ==
>>> df[0] is None
False
>>> df[0] == None
0 False
1 False
Name: 0, dtype: bool
Unavailable: .values is None
>>> df[0].values is None
False
How to check np.nan
Available: .isnull()
>>> df[1].isnull()
0 False
1 True
Name: 1, dtype: bool
Available: np.isnan
>>> np.isnan(df[1])
0 False
1 True
Name: 1, dtype: bool
>>> np.isnan(df[1].values)
array([False, True])
>>> df[1].apply(lambda x: np.isnan(x))
0 False
1 True
Name: 1, dtype: bool
Unavailable: is or == np.nan
>>> df[1] is np.nan
False
>>> df[1] == np.nan
0 False
1 False
Name: 1, dtype: bool
>>> df[1].values is np.nan
False
>>> df[1].values == np.nan
array([False, False])
>>> df[1].apply(lambda x: x is np.nan)
0 False
1 False
Name: 1, dtype: bool
>>> df[1].apply(lambda x: x == np.nan)
0 False
1 False
Name: 1, dtype: bool
A:
You could use applymap with a lambda to check if an element is None as follows, (constructed a different example, as in your original one, None is coerced to np.nan because the data type is float, you will need an object type column to hold None as is, or as commented by @Evert, None and NaN are indistinguishable in numeric type columns):
df = pd.DataFrame([[None, 3], ["", np.nan]])
df
# 0 1
#0 None 3.0
#1 NaN
df.applymap(lambda x: x is None)
# 0 1
#0 True False
#1 False False
A:
Q: How check for None in DataFrame / Series
A: isna works but also catches nan. Two suggestions:
Use x.isna() and replace none with nan
If you really care about None: x.applymap(type) == type(None)
I prefer comparing type since for example nan == nan is false.
In my case the Nones appeared unintentionally so x[x.isna()] = nan solved the problem.
Example:
x = pd.DataFrame([12, False, 0, nan, None]).T
x.isna()
0 1 2 3 4
0 False False False True True
x.applymap(type) == type(None)
0 1 2 3 4
0 False False False False True
x
0 1 2 3 4
0 12 False 0 NaN None
x[x.isna()] = nan
0 1 2 3 4
0 12 False 0 NaN NaN
| Check for None in pandas dataframe | I would like to find where None is found in the dataframe.
pd.DataFrame([None,np.nan]).isnull()
OUT:
0
0 True
1 True
isnull() finds both numpy Nan and None values.
I only want the None values and not numpy Nan. Is there an easier way to do that without looping through the dataframe?
Edit:
After reading the comments, I realized that in my dataframe in my work also include strings, so the None were not coerced to numpy Nan. So the answer given by Pisdom works.
| [
"If you want to get True/False for each line, you can use the following code. Here is an example as a result for the following DataFrame:\ndf = pd.DataFrame([[None, 3], [\"\", np.nan]])\n\ndf\n# 0 1\n#0 None 3.0\n#1 NaN\n\nHow to check None\nAvailable: .isnull()\n>>> df[0].isnull()\n0 True\n1 False\nName: 0, dtype: bool\n\nAvailable: .apply == or is None\n>>> df[0].apply(lambda x: x == None)\n0 True\n1 False\nName: 0, dtype: bool\n\n>>> df[0].apply(lambda x: x is None)\n0 True\n1 False\nName: 0, dtype: bool\n\nAvailable: .values == None\n>>> df[0].values == None\narray([ True, False])\n\nUnavailable: is or ==\n>>> df[0] is None\nFalse\n\n>>> df[0] == None\n0 False\n1 False\nName: 0, dtype: bool\n\nUnavailable: .values is None\n>>> df[0].values is None\nFalse\n\nHow to check np.nan\nAvailable: .isnull()\n>>> df[1].isnull()\n0 False\n1 True\nName: 1, dtype: bool\n\nAvailable: np.isnan\n>>> np.isnan(df[1])\n0 False\n1 True\nName: 1, dtype: bool\n\n>>> np.isnan(df[1].values)\narray([False, True])\n\n>>> df[1].apply(lambda x: np.isnan(x))\n0 False\n1 True\nName: 1, dtype: bool\n\nUnavailable: is or == np.nan\n>>> df[1] is np.nan\nFalse\n\n>>> df[1] == np.nan\n0 False\n1 False\nName: 1, dtype: bool\n\n>>> df[1].values is np.nan\nFalse\n\n>>> df[1].values == np.nan\narray([False, False])\n\n>>> df[1].apply(lambda x: x is np.nan)\n0 False\n1 False\nName: 1, dtype: bool\n\n>>> df[1].apply(lambda x: x == np.nan)\n0 False\n1 False\nName: 1, dtype: bool\n\n",
"You could use applymap with a lambda to check if an element is None as follows, (constructed a different example, as in your original one, None is coerced to np.nan because the data type is float, you will need an object type column to hold None as is, or as commented by @Evert, None and NaN are indistinguishable in numeric type columns):\ndf = pd.DataFrame([[None, 3], [\"\", np.nan]])\n\ndf\n# 0 1\n#0 None 3.0\n#1 NaN\n\ndf.applymap(lambda x: x is None)\n\n# 0 1\n#0 True False\n#1 False False\n\n",
"Q: How check for None in DataFrame / Series\nA: isna works but also catches nan. Two suggestions:\n\nUse x.isna() and replace none with nan\nIf you really care about None: x.applymap(type) == type(None)\n\nI prefer comparing type since for example nan == nan is false.\nIn my case the Nones appeared unintentionally so x[x.isna()] = nan solved the problem.\nExample:\nx = pd.DataFrame([12, False, 0, nan, None]).T\nx.isna()\n 0 1 2 3 4\n0 False False False True True\n\nx.applymap(type) == type(None)\n 0 1 2 3 4\n0 False False False False True\n\nx\n 0 1 2 3 4\n0 12 False 0 NaN None\n\nx[x.isna()] = nan\n 0 1 2 3 4\n0 12 False 0 NaN NaN\n\n"
] | [
13,
8,
0
] | [] | [] | [
"nan",
"numpy",
"pandas",
"python"
] | stackoverflow_0045271309_nan_numpy_pandas_python.txt |
Q:
How do I pass in a 1d array to sklearn's LabelEncoder?
I'm following along an Uber-Lyft price prediction notebook on Kaggle, but I'm trying to use the Polars module.
In cell 43 where they use sklearn's LabelEncoder, they have the following loop that appears to loop through each feature, except for price, and encodes it:
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
df_cat_encode= df_cat.copy()
for col in df_cat_encode.select_dtypes(include='O').columns:
df_cat_encode[col]=le.fit_transform(df_cat_encode[col])
The data being passed through looks like this:
source
destination
cab_type
name
short_summary
icon
price
Haymarket Square
North Station
Lyft
Shared
Mostly Cloudy
partly-cloudy-night
5.0
Haymarket Square
North Station
Lyft
Lux
Rain
rain
11.0
Haymarket Square
North Station
Lyft
Lyft
Clear
clear-night
7.0
Haymarket Square
North Station
Lyft
Lux Black XL
Clear
clear-night
26.0
and the label encoded result looks like this:
637975 rows x 7 columns
source
destination
cab_type
name
short_summary
icon
price
5
7
0
7
4
5
5.0
5
7
0
2
8
6
11.0
5
7
0
5
0
1
7.0
5
7
0
4
6
1
26.0
...
...
...
...
...
...
...
The problem I'm having is when I try to build the same loop with Polars syntax like
for col in df_cat_encode.select(["source","destination","cab_type","name","short_summary","icon"]).columns:
df_cat_encode.with_column(le.fit_transform(col))
I get the following error
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/preprocessing/_label.py", line 115, in fit_transform
y = column_or_1d(y, warn=True)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py", line 1038, in column_or_1d
raise ValueError(
ValueError: y should be a 1d array, got an array of shape () instead.
What am I doing wrong, and how can I fix this?
A:
It looks like this encoding is the equivalent of a "dense" ranking.
>>> df_cat_encode
source destination cab_type name short_summary icon price
0 0 0 0 3 1 1 5.0
1 0 0 0 0 2 2 11.0
2 0 0 0 2 0 0 7.0
3 0 0 0 1 0 0 26.0
Which you can do in polars using .rank():
>>> df.with_columns(pl.all().exclude("price").rank(method="dense") - 1)
shape: (4, 7)
┌────────┬─────────────┬──────────┬──────┬───────────────┬──────┬───────┐
│ source | destination | cab_type | name | short_summary | icon | price │
│ --- | --- | --- | --- | --- | --- | --- │
│ u32 | u32 | u32 | u32 | u32 | u32 | f64 │
╞════════╪═════════════╪══════════╪══════╪═══════════════╪══════╪═══════╡
│ 0 | 0 | 0 | 3 | 1 | 1 | 5.0 │
├────────┼─────────────┼──────────┼──────┼───────────────┼──────┼───────┤
│ 0 | 0 | 0 | 0 | 2 | 2 | 11.0 │
├────────┼─────────────┼──────────┼──────┼───────────────┼──────┼───────┤
│ 0 | 0 | 0 | 2 | 0 | 0 | 7.0 │
├────────┼─────────────┼──────────┼──────┼───────────────┼──────┼───────┤
│ 0 | 0 | 0 | 1 | 0 | 0 | 26.0 │
└─//─────┴─//──────────┴─//───────┴─//───┴─//────────────┴─//───┴─//────┘
| How do I pass in a 1d array to sklearn's LabelEncoder? | I'm following along an Uber-Lyft price prediction notebook on Kaggle, but I'm trying to use the Polars module.
In cell 43 where they use sklearn's LabelEncoder, they have the following loop that appears to loop through each feature, except for price, and encodes it:
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
df_cat_encode= df_cat.copy()
for col in df_cat_encode.select_dtypes(include='O').columns:
df_cat_encode[col]=le.fit_transform(df_cat_encode[col])
The data being passed through looks like this:
source
destination
cab_type
name
short_summary
icon
price
Haymarket Square
North Station
Lyft
Shared
Mostly Cloudy
partly-cloudy-night
5.0
Haymarket Square
North Station
Lyft
Lux
Rain
rain
11.0
Haymarket Square
North Station
Lyft
Lyft
Clear
clear-night
7.0
Haymarket Square
North Station
Lyft
Lux Black XL
Clear
clear-night
26.0
and the label encoded result looks like this:
637975 rows x 7 columns
source
destination
cab_type
name
short_summary
icon
price
5
7
0
7
4
5
5.0
5
7
0
2
8
6
11.0
5
7
0
5
0
1
7.0
5
7
0
4
6
1
26.0
...
...
...
...
...
...
...
The problem I'm having is when I try to build the same loop with Polars syntax like
for col in df_cat_encode.select(["source","destination","cab_type","name","short_summary","icon"]).columns:
df_cat_encode.with_column(le.fit_transform(col))
I get the following error
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/preprocessing/_label.py", line 115, in fit_transform
y = column_or_1d(y, warn=True)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py", line 1038, in column_or_1d
raise ValueError(
ValueError: y should be a 1d array, got an array of shape () instead.
What am I doing wrong, and how can I fix this?
| [
"It looks like this encoding is the equivalent of a \"dense\" ranking.\n>>> df_cat_encode\n source destination cab_type name short_summary icon price\n0 0 0 0 3 1 1 5.0\n1 0 0 0 0 2 2 11.0\n2 0 0 0 2 0 0 7.0\n3 0 0 0 1 0 0 26.0\n\nWhich you can do in polars using .rank():\n>>> df.with_columns(pl.all().exclude(\"price\").rank(method=\"dense\") - 1)\nshape: (4, 7)\n┌────────┬─────────────┬──────────┬──────┬───────────────┬──────┬───────┐\n│ source | destination | cab_type | name | short_summary | icon | price │\n│ --- | --- | --- | --- | --- | --- | --- │\n│ u32 | u32 | u32 | u32 | u32 | u32 | f64 │\n╞════════╪═════════════╪══════════╪══════╪═══════════════╪══════╪═══════╡\n│ 0 | 0 | 0 | 3 | 1 | 1 | 5.0 │\n├────────┼─────────────┼──────────┼──────┼───────────────┼──────┼───────┤\n│ 0 | 0 | 0 | 0 | 2 | 2 | 11.0 │\n├────────┼─────────────┼──────────┼──────┼───────────────┼──────┼───────┤\n│ 0 | 0 | 0 | 2 | 0 | 0 | 7.0 │\n├────────┼─────────────┼──────────┼──────┼───────────────┼──────┼───────┤\n│ 0 | 0 | 0 | 1 | 0 | 0 | 26.0 │\n└─//─────┴─//──────────┴─//───────┴─//───┴─//────────────┴─//───┴─//────┘\n\n"
] | [
0
] | [] | [] | [
"arrays",
"python",
"python_polars",
"scikit_learn"
] | stackoverflow_0074669199_arrays_python_python_polars_scikit_learn.txt |
Q:
getting timers to print values from bubblesort, wont print my last value unless I lower it?
import sys
import time
from random import randint
import numpy as np
sys.setrecursionlimit(6000)
nums = [10, 50, 100, 500, 1000, 5000]
def bubble(A, n):
for i in range(n - 1):
if A[i] > A[i + 1]:
A[i], A[i + 1] = A[i + 1], A[i]
if n - 1 > 1:
bubble(A, n - 1)
def time_by_bubble_sort(nums):
time_taken_by_bubble_sort = []
for num in nums:
A = list(np.random.randint(low=1, high=num, size=num))
st_time = time.time()
bubble(A, len(A))
end_time = time.time()
time_taken = end_time - st_time
time_taken_by_bubble_sort.append(time_taken)
return time_taken_by_bubble_sort
print(time_by_bubble_sort(nums))
I want to compare time with my values from nums:
[10, 50, 100, 500, 1000, 5000]
Why dosen't generate a time for the last value (5000), but when I switch it out to 2000 or remove it, it will print?
this is the error code:
exit code -1073741571 (0xC00000FD)
After googling, it might be that my recursive function goes to infinite, but I don't see it.
sorry for bad english.
A:
According to sys.setrecursionlimit, emphasis mine:
The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.
Your limit of 6000 is too high. My system crashes after about 2130 recursive calls to bubble, which explains why using 2000 instead of 5000 works. The crash is due to the Python process's stack running out of space which is platform-dependent.
| getting timers to print values from bubblesort, wont print my last value unless I lower it? | import sys
import time
from random import randint
import numpy as np
sys.setrecursionlimit(6000)
nums = [10, 50, 100, 500, 1000, 5000]
def bubble(A, n):
for i in range(n - 1):
if A[i] > A[i + 1]:
A[i], A[i + 1] = A[i + 1], A[i]
if n - 1 > 1:
bubble(A, n - 1)
def time_by_bubble_sort(nums):
time_taken_by_bubble_sort = []
for num in nums:
A = list(np.random.randint(low=1, high=num, size=num))
st_time = time.time()
bubble(A, len(A))
end_time = time.time()
time_taken = end_time - st_time
time_taken_by_bubble_sort.append(time_taken)
return time_taken_by_bubble_sort
print(time_by_bubble_sort(nums))
I want to compare time with my values from nums:
[10, 50, 100, 500, 1000, 5000]
Why dosen't generate a time for the last value (5000), but when I switch it out to 2000 or remove it, it will print?
this is the error code:
exit code -1073741571 (0xC00000FD)
After googling, it might be that my recursive function goes to infinite, but I don't see it.
sorry for bad english.
| [
"According to sys.setrecursionlimit, emphasis mine:\n\nThe highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.\n\nYour limit of 6000 is too high. My system crashes after about 2130 recursive calls to bubble, which explains why using 2000 instead of 5000 works. The crash is due to the Python process's stack running out of space which is platform-dependent.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074635282_python.txt |
Q:
General way of filtering by IDs with DRF
Is there a generic way that I can filter by an array of IDs when using DRF?
For example, if I wanted to return all images with the following IDs, I would do this:
/images/?ids=1,2,3,4
My current implementation is to do the following:
# filter
class ProjectImageFilter(django_filters.FilterSet):
"""
Filter on existing fields, or defined query_params with
associated functions
"""
ids = django_filters.MethodFilter(action='id_list')
def id_list(self, queryset, value):
"""
Filter by IDs by passing in a query param of this structure
`?ids=265,263`
"""
id_list = value.split(',')
return queryset.filter(id__in=id_list)
class Meta:
model = ProjectImage
fields = ['ids',]
# viewset
class Images(viewsets.ModelViewSet):
"""
Images associated with a project
"""
serializer_class = ImageSerializer
queryset = ProjectImage.objects.all()
filter_class = ProjectImageFilter
However, in this case ProjectImageFilter requires a model to be specified ( ProjectImage). Is there a way that I can just generally define this filter so I can use it on multiple ViewSets with different models?
A:
One solution without django-filters is to just super() override get_queryset. Here is an example:
class MyViewSet(view.ViewSet):
# your code
def get_queryset(self):
queryset = super(MyViewSet, self).get_queryset()
ids = self.request.query_params.get('ids', None)
if ids:
ids_list = ids.split(',')
queryset = queryset.filter(id__in=ids_list)
return queryset
A:
The library django-filter has support for this using BaseInFilter, in conjunction with DRF.
From their docs:
class NumberRangeFilter(BaseRangeFilter, NumberFilter):
pass
class F(FilterSet):
id__range = NumberRangeFilter(field_name='id', lookup_expr='range')
class Meta:
model = User
User.objects.create(username='alex')
User.objects.create(username='jacob')
User.objects.create(username='aaron')
User.objects.create(username='carl')
# Range: User with IDs between 1 and 3.
f = F({'id__range': '1,3'})
assert len(f.qs) == 3
| General way of filtering by IDs with DRF | Is there a generic way that I can filter by an array of IDs when using DRF?
For example, if I wanted to return all images with the following IDs, I would do this:
/images/?ids=1,2,3,4
My current implementation is to do the following:
# filter
class ProjectImageFilter(django_filters.FilterSet):
"""
Filter on existing fields, or defined query_params with
associated functions
"""
ids = django_filters.MethodFilter(action='id_list')
def id_list(self, queryset, value):
"""
Filter by IDs by passing in a query param of this structure
`?ids=265,263`
"""
id_list = value.split(',')
return queryset.filter(id__in=id_list)
class Meta:
model = ProjectImage
fields = ['ids',]
# viewset
class Images(viewsets.ModelViewSet):
"""
Images associated with a project
"""
serializer_class = ImageSerializer
queryset = ProjectImage.objects.all()
filter_class = ProjectImageFilter
However, in this case ProjectImageFilter requires a model to be specified ( ProjectImage). Is there a way that I can just generally define this filter so I can use it on multiple ViewSets with different models?
| [
"One solution without django-filters is to just super() override get_queryset. Here is an example:\nclass MyViewSet(view.ViewSet):\n\n # your code\n\n def get_queryset(self):\n queryset = super(MyViewSet, self).get_queryset()\n\n ids = self.request.query_params.get('ids', None)\n if ids:\n ids_list = ids.split(',')\n queryset = queryset.filter(id__in=ids_list)\n\n return queryset\n\n",
"The library django-filter has support for this using BaseInFilter, in conjunction with DRF.\nFrom their docs:\nclass NumberRangeFilter(BaseRangeFilter, NumberFilter):\n pass\n\nclass F(FilterSet):\n id__range = NumberRangeFilter(field_name='id', lookup_expr='range')\n\n class Meta:\n model = User\n\nUser.objects.create(username='alex')\nUser.objects.create(username='jacob')\nUser.objects.create(username='aaron')\nUser.objects.create(username='carl')\n\n# Range: User with IDs between 1 and 3.\nf = F({'id__range': '1,3'})\nassert len(f.qs) == 3\n\n"
] | [
1,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"python_2.7"
] | stackoverflow_0036851257_django_django_rest_framework_python_python_2.7.txt |
Q:
Joblib UserWarning while trying to cache results
I get the following UserWarning when trying to cache results using joblib:
import numpy
from tempfile import mkdtemp
cachedir = mkdtemp()
from joblib import Memory
memory = Memory(cachedir=cachedir, verbose=0)
@memory.cache
def get_nc_var3d(path_nc, var, year):
"""
Get value from netcdf for variable var for year
:param path_nc:
:param var:
:param year:
:return:
"""
try:
hndl_nc = open_or_die(path_nc)
val = hndl_nc.variables[var][int(year), :, :]
except:
val = numpy.nan
logger.info('Error in getting var ' + var + ' for year ' + str(year) + ' from netcdf ')
hndl_nc.close()
return val
I get the following warning when calling this function using parameters:
UserWarning: Persisting input arguments took 0.58s to run.
If this happens often in your code, it can cause performance problems
(results will be correct in all cases).
The reason for this is probably some large input arguments for a wrapped function (e.g. large strings).
THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem.
Input parameters: C:/Users/rit/Documents/PhD/Projects/\GLA/Input/LUWH/\LUWLAN_v1.0h\transit_model.nc range_to_large 1150
How do I get rid of the warning? And why is it happening, since the input parameters are not too long?
A:
I don't have an answer to the "why doesn't this work?" portion of the question. However to simply ignore the warning you can use warnings.catch_warnings with warnings.simplefilter as seen here.
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
your_code()
Obviously, I don't recommend ignoring the warning unless you're sure its harmless, but if you're going to do it this way will only suppress warnings inside the context manager and is straight out of the python docs
A:
UserWarning: Persisting input arguments took 0.58s to run.
If this happens often in your code, it can cause performance problems
(results will be correct in all cases).
The reason for this is probably some large input arguments for a wrapped function (e.g. large strings).
THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem.
the warning itself is self explanatory in my humble opinion. it might be in your code issue you can try to decrease the input size,or you can share your report with joblib team so that they can either help to improve joblib or suggest your better approach of usage to avoid this type of performance warnings.
A:
This warning is generated by joblib when it takes a long time to store the input arguments of a function in its cache. In some cases, this can cause performance issues and should be avoided if possible.
To avoid this warning, you can try to minimize the size of the input arguments to the function by passing only the necessary information.
For example, instead of passing the entire path to the netcdf file as a string, you could pass only the filename and use that to construct the full path inside the function.
Alternatively, you can disable the warning by setting the verbose argument of the Memory object to 0:
memory = Memory(cachedir=cachedir, verbose=0)
This will prevent joblib from printing the warning, but it will not fix the underlying performance issue. It's generally a good idea to try to minimize the size of the input arguments to avoid this warning.
| Joblib UserWarning while trying to cache results | I get the following UserWarning when trying to cache results using joblib:
import numpy
from tempfile import mkdtemp
cachedir = mkdtemp()
from joblib import Memory
memory = Memory(cachedir=cachedir, verbose=0)
@memory.cache
def get_nc_var3d(path_nc, var, year):
"""
Get value from netcdf for variable var for year
:param path_nc:
:param var:
:param year:
:return:
"""
try:
hndl_nc = open_or_die(path_nc)
val = hndl_nc.variables[var][int(year), :, :]
except:
val = numpy.nan
logger.info('Error in getting var ' + var + ' for year ' + str(year) + ' from netcdf ')
hndl_nc.close()
return val
I get the following warning when calling this function using parameters:
UserWarning: Persisting input arguments took 0.58s to run.
If this happens often in your code, it can cause performance problems
(results will be correct in all cases).
The reason for this is probably some large input arguments for a wrapped function (e.g. large strings).
THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem.
Input parameters: C:/Users/rit/Documents/PhD/Projects/\GLA/Input/LUWH/\LUWLAN_v1.0h\transit_model.nc range_to_large 1150
How do I get rid of the warning? And why is it happening, since the input parameters are not too long?
| [
"I don't have an answer to the \"why doesn't this work?\" portion of the question. However to simply ignore the warning you can use warnings.catch_warnings with warnings.simplefilter as seen here.\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n your_code()\n\n\nObviously, I don't recommend ignoring the warning unless you're sure its harmless, but if you're going to do it this way will only suppress warnings inside the context manager and is straight out of the python docs\n",
"UserWarning: Persisting input arguments took 0.58s to run.\nIf this happens often in your code, it can cause performance problems\n(results will be correct in all cases).\nThe reason for this is probably some large input arguments for a wrapped function (e.g. large strings).\nTHIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an example so that they can fix the problem.\nthe warning itself is self explanatory in my humble opinion. it might be in your code issue you can try to decrease the input size,or you can share your report with joblib team so that they can either help to improve joblib or suggest your better approach of usage to avoid this type of performance warnings.\n",
"This warning is generated by joblib when it takes a long time to store the input arguments of a function in its cache. In some cases, this can cause performance issues and should be avoided if possible.\nTo avoid this warning, you can try to minimize the size of the input arguments to the function by passing only the necessary information.\nFor example, instead of passing the entire path to the netcdf file as a string, you could pass only the filename and use that to construct the full path inside the function.\nAlternatively, you can disable the warning by setting the verbose argument of the Memory object to 0:\nmemory = Memory(cachedir=cachedir, verbose=0)\n\nThis will prevent joblib from printing the warning, but it will not fix the underlying performance issue. It's generally a good idea to try to minimize the size of the input arguments to avoid this warning.\n"
] | [
0,
0,
0
] | [] | [] | [
"joblib",
"netcdf",
"numpy",
"python"
] | stackoverflow_0037129754_joblib_netcdf_numpy_python.txt |
Q:
Converting week numbers to dates
Say I have a week number of a given year (e.g. week number 6 of 2014).
How can I convert this to the date of the Monday that starts that week?
One brute force solution I thought of would be to go through all Mondays of the year:
date1 = datetime.date(1,1,2014)
date2 = datetime.date(12,31,2014)
def monday_range(date1,date2):
while date1 < date2:
if date1.weekday() == 0:
yield date1
date1 = date1 + timedelta(days=1)
and store a hash from the first to the last Monday of the year, but this wouldn't do it, since, the first week of the year may not contain a Monday.
A:
You could just feed the data into time.asctime().
>>> import time
>>> week = 6
>>> year = 2014
>>> atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w'))
>>> atime
'Mon Feb 10 00:00:00 2014'
EDIT:
To convert this to a datetime.date object:
>>> datetime.datetime.fromtimestamp(time.mktime(atime)).date()
datetime.date(2014, 2, 10)
A:
All about strptime \ strftime:
https://docs.python.org/2/library/datetime.html
mytime.strftime('%U') #for W\C Monday
mytime.strftime('%W') #for W\C Sunday
Sorry wrong way around
from datetime import datetime
mytime=datetime.strptime('2012W6 MON'. '%YW%U %a')
Strptime needs to see both the year and the weekday to do this. I'm assuming you've got weekly data so just add 'mon' to the end of the string.
Enjoy
A:
A simple function to get the Monday, given a date.
def get_monday(dte):
return dte - datetime.timedelta(days = dte.weekday())
Some sample output:
>>> get_monday(date1)
datetime.date(2013, 12, 30)
>>> get_monday(date2)
datetime.date(2014, 12, 29)
Call this function within your loop.
A:
We can just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)
A:
To piggyback and give a different version of the answer @anon582847382 gave, you can do something like the below code if you're creating a function for it and the week number is given like "11-2023":
import time
def get_date_from_week_number(str_value):
temp_str = time.asctime(time.strptime('{} {} 1'.format(str_value[3:7], str_value[0:2]), '%Y %W %w'))
return datetime.strptime(temp_str, '%a %b %d %H:%M:%S %Y').date()
| Converting week numbers to dates | Say I have a week number of a given year (e.g. week number 6 of 2014).
How can I convert this to the date of the Monday that starts that week?
One brute force solution I thought of would be to go through all Mondays of the year:
date1 = datetime.date(1,1,2014)
date2 = datetime.date(12,31,2014)
def monday_range(date1,date2):
while date1 < date2:
if date1.weekday() == 0:
yield date1
date1 = date1 + timedelta(days=1)
and store a hash from the first to the last Monday of the year, but this wouldn't do it, since, the first week of the year may not contain a Monday.
| [
"You could just feed the data into time.asctime(). \n>>> import time\n>>> week = 6\n>>> year = 2014\n>>> atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w'))\n>>> atime\n'Mon Feb 10 00:00:00 2014'\n\n\nEDIT:\nTo convert this to a datetime.date object:\n>>> datetime.datetime.fromtimestamp(time.mktime(atime)).date()\ndatetime.date(2014, 2, 10)\n\n",
"All about strptime \\ strftime:\nhttps://docs.python.org/2/library/datetime.html\nmytime.strftime('%U') #for W\\C Monday\nmytime.strftime('%W') #for W\\C Sunday\n\nSorry wrong way around\nfrom datetime import datetime\nmytime=datetime.strptime('2012W6 MON'. '%YW%U %a')\n\nStrptime needs to see both the year and the weekday to do this. I'm assuming you've got weekly data so just add 'mon' to the end of the string.\nEnjoy\n",
"A simple function to get the Monday, given a date.\ndef get_monday(dte):\n return dte - datetime.timedelta(days = dte.weekday())\n\nSome sample output:\n>>> get_monday(date1)\ndatetime.date(2013, 12, 30)\n>>> get_monday(date2)\ndatetime.date(2014, 12, 29)\n\nCall this function within your loop.\n",
"We can just add the number of weeks to the first day of the year.\n>>> import datetime\n>>> from dateutil.relativedelta import relativedelta\n\n>>> week = 40\n>>> year = 2019\n>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)\n>>> date\ndatetime.date(2019, 10, 8)\n\n",
"To piggyback and give a different version of the answer @anon582847382 gave, you can do something like the below code if you're creating a function for it and the week number is given like \"11-2023\":\nimport time\n\n\ndef get_date_from_week_number(str_value):\n temp_str = time.asctime(time.strptime('{} {} 1'.format(str_value[3:7], str_value[0:2]), '%Y %W %w'))\n return datetime.strptime(temp_str, '%a %b %d %H:%M:%S %Y').date()\n\n"
] | [
6,
5,
4,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0022789198_datetime_python.txt |
Q:
discord.py temprole command
First of all i dont really know why its not working properly. Its not returning any errors, messages etc., the code is running properly. Can somebody help me fix my issue?
EDIT1: Just want to add that im noob in coding and ive spent about 1 hour trying to solve the problem
import discord
from discord.ext import commands
from discord.ext import tasks
from discord.utils import get
import asyncio
bot = discord.ext.commands.Bot(command_prefix = "$", intents=discord.Intents.default())
intents = discord.Intents.default()
intents.message_content = True
time_convert = {"sec":1, "min":60, "h":3600,"d":86400}
client = discord.Client(intents=intents)
@bot.command()
async def temprole(ctx, role_time: int, member: discord.Member = None, role: discord.Role = None):
if not member:
await ctx.send("Who do you want me to give a role?")
return
if role is None:
await ctx.send('Text me a role to add')
return
await member.add_roles(role)
await ctx.send(f"Role has been given to {member.mention} \nfor {role_time}")
await asyncio.sleep(role_time)
await member.remove_roles(role)
await ctx.send(f"{role.mention} has been removed from {member.mention} \n*(expired)*")
client.run('My Token Is Here')
A:
as I can see you have a warning so you there are some missing intents
change this
bot = discord.ext.commands.Bot(command_prefix = "$", intents=discord.Intents.default())
to
bot = discord.ext.commands.Bot(command_prefix = "$", intents=discord.Intents.all())
| discord.py temprole command | First of all i dont really know why its not working properly. Its not returning any errors, messages etc., the code is running properly. Can somebody help me fix my issue?
EDIT1: Just want to add that im noob in coding and ive spent about 1 hour trying to solve the problem
import discord
from discord.ext import commands
from discord.ext import tasks
from discord.utils import get
import asyncio
bot = discord.ext.commands.Bot(command_prefix = "$", intents=discord.Intents.default())
intents = discord.Intents.default()
intents.message_content = True
time_convert = {"sec":1, "min":60, "h":3600,"d":86400}
client = discord.Client(intents=intents)
@bot.command()
async def temprole(ctx, role_time: int, member: discord.Member = None, role: discord.Role = None):
if not member:
await ctx.send("Who do you want me to give a role?")
return
if role is None:
await ctx.send('Text me a role to add')
return
await member.add_roles(role)
await ctx.send(f"Role has been given to {member.mention} \nfor {role_time}")
await asyncio.sleep(role_time)
await member.remove_roles(role)
await ctx.send(f"{role.mention} has been removed from {member.mention} \n*(expired)*")
client.run('My Token Is Here')
| [
"as I can see you have a warning so you there are some missing intents\nchange this\nbot = discord.ext.commands.Bot(command_prefix = \"$\", intents=discord.Intents.default()) \nto\nbot = discord.ext.commands.Bot(command_prefix = \"$\", intents=discord.Intents.all())\n\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074668821_discord_discord.py_python.txt |
Q:
How can I make permanent changes to a list using a function in python tkinter?
I want to enter an item into the entry box press a button and add the item to the list changing the list permanently, however I cannot seem to make a permanent change to the list. The program always returns "[]" and never the updated list. Is there a way I can do this?
I have tested and there are no issues involving extracting text from the entry box and adding It to the list. The only problem is making the change permanent.
here is the code:
from tkinter import *
window = Tk()
names = []
ent = Entry(window)
ent.pack()
def change():
names.append(ent.get())
btn = Button (window, command = change )
btn.pack()
print(names)
window.mainloop()
why is the response always "[]" and not the updated list
A:
It is printing an empty list because the list is empty. You are not printing after appending
from tkinter import *
window = Tk()
names = []
ent = Entry(window) ent.pack()
def change():
names.append(ent.get())
print(names)
btn = Button (window, command = change ) btn.pack()
#print(names)
window.mainloop()
A:
While mapperx's answer is correct, I think what you're trying to do is to persist the list, so that when you close the program and open it again, the names are still there. If this is what you intend, you need to store the list (or its content) into a file before closing the program. You can do this using pickle.
from tkinter import *
import pickle
window = Tk()
# Create list from file (if no file exists, create empty list)
try:
with open('names.pickle', 'rb') as f: names = pickle.load(f)
except: names = []
ent = Entry(window)
ent.pack()
def change():
names.append(ent.get())
btn = Button (window, command = change )
btn.pack()
print(names)
def onClose():
with open('names.pickle', 'wb') as f: pickle.dump(names, f) # Store (persist) the list
window.destroy()
# This will call "onClose" before closing the window
window.protocol("WM_DELETE_WINDOW", onClose)
window.mainloop()
You can change names.pickle to any filename you want
| How can I make permanent changes to a list using a function in python tkinter? | I want to enter an item into the entry box press a button and add the item to the list changing the list permanently, however I cannot seem to make a permanent change to the list. The program always returns "[]" and never the updated list. Is there a way I can do this?
I have tested and there are no issues involving extracting text from the entry box and adding It to the list. The only problem is making the change permanent.
here is the code:
from tkinter import *
window = Tk()
names = []
ent = Entry(window)
ent.pack()
def change():
names.append(ent.get())
btn = Button (window, command = change )
btn.pack()
print(names)
window.mainloop()
why is the response always "[]" and not the updated list
| [
"It is printing an empty list because the list is empty. You are not printing after appending\nfrom tkinter import *\n\nwindow = Tk()\n\nnames = []\n\nent = Entry(window) ent.pack()\n\ndef change():\n names.append(ent.get())\n print(names)\n\nbtn = Button (window, command = change ) btn.pack()\n\n#print(names)\n\nwindow.mainloop()\n\n",
"While mapperx's answer is correct, I think what you're trying to do is to persist the list, so that when you close the program and open it again, the names are still there. If this is what you intend, you need to store the list (or its content) into a file before closing the program. You can do this using pickle. \nfrom tkinter import *\nimport pickle\n\nwindow = Tk()\n\n# Create list from file (if no file exists, create empty list)\ntry:\n with open('names.pickle', 'rb') as f: names = pickle.load(f)\nexcept: names = []\n\nent = Entry(window)\nent.pack()\n\ndef change():\n names.append(ent.get())\n\nbtn = Button (window, command = change )\nbtn.pack()\n\nprint(names)\n\ndef onClose():\n with open('names.pickle', 'wb') as f: pickle.dump(names, f) # Store (persist) the list\n window.destroy()\n\n# This will call \"onClose\" before closing the window\nwindow.protocol(\"WM_DELETE_WINDOW\", onClose)\nwindow.mainloop()\n\nYou can change names.pickle to any filename you want\n"
] | [
1,
0
] | [] | [] | [
"list",
"python",
"tkinter"
] | stackoverflow_0074670268_list_python_tkinter.txt |
Q:
Django rest framework CORS( Cross Origin Resource Sharing) is not working
I have done token authentication for the url 'localhost:8000/api/posts' and according to django-cors-headers library I have also changed the settings.py file. Here is my settings.py file,
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'rest_framework',
'rest_framework.authtoken'
]
Here is my middleware settings,
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Here are my other settings,
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:4000"]
Here I have given access only for "http://127.0.0.1:4000"
This is my client django project views file which is hosted on "http://127.0.0.1:3000"
import requests
from django.http import HttpResponse
def get_token():
url = "http://127.0.0.1:8000/api/authentication/"
response = requests.post(url, data={'username':'thomas','password':'thomas1234567890'})
token=response.json()
return token
token=get_token()
def get_details():
url = "http://127.0.0.1:8000/api/posts/"
header = {"Authorization": "Token {}".format(token['token'])}
response = requests.get(url, headers = header)
return response.text
def homepage(request):
x= get_details()
return HttpResponse(x)
Now even though I am requesting for the data from other domain which is not mentioned on django cors origin whitelist, I am able to fetch the data without any error, I am not able to restrict other domains for accessing the data. Can anyone please help me in solving this issue.
A:
use this setting for your app. This happened because of the fact that you are using HTTPS over HTTP.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
| Django rest framework CORS( Cross Origin Resource Sharing) is not working | I have done token authentication for the url 'localhost:8000/api/posts' and according to django-cors-headers library I have also changed the settings.py file. Here is my settings.py file,
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'rest_framework',
'rest_framework.authtoken'
]
Here is my middleware settings,
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Here are my other settings,
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:4000"]
Here I have given access only for "http://127.0.0.1:4000"
This is my client django project views file which is hosted on "http://127.0.0.1:3000"
import requests
from django.http import HttpResponse
def get_token():
url = "http://127.0.0.1:8000/api/authentication/"
response = requests.post(url, data={'username':'thomas','password':'thomas1234567890'})
token=response.json()
return token
token=get_token()
def get_details():
url = "http://127.0.0.1:8000/api/posts/"
header = {"Authorization": "Token {}".format(token['token'])}
response = requests.get(url, headers = header)
return response.text
def homepage(request):
x= get_details()
return HttpResponse(x)
Now even though I am requesting for the data from other domain which is not mentioned on django cors origin whitelist, I am able to fetch the data without any error, I am not able to restrict other domains for accessing the data. Can anyone please help me in solving this issue.
| [
"use this setting for your app. This happened because of the fact that you are using HTTPS over HTTP.\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n"
] | [
0
] | [
"According to docs for CORS_ALLOW_ALL_ORIGINS\n\nIf True, all origins will be allowed. Other settings restricting\nallowed origins will be ignored. Defaults to False.\n\nSo it looks like your CORS_ALLOWED_ORIGINS is ignored because CORS_ALLOW_ALL_ORIGINS is explicitly set to False forbidding all origins.\n"
] | [
-1
] | [
"django",
"django_cors_headers",
"django_rest_framework",
"python"
] | stackoverflow_0063626757_django_django_cors_headers_django_rest_framework_python.txt |
Q:
Django Crispy Form doesn't add or update database
Hello, I am writing a small project about a car shop and this is the problem I came up with.
I'm trying to add a new car and everything seems to work, but when I fill out the form and click submit, it just redirects me to products page without errors and without adding a new car to the database.
Here is the code.
views.py
class AddProductView(View):
action = 'Add'
template_name = 'myApp/manipulate_product.html'
context = {
}
form_class = ManipulateProductForm
def get(self, req, *args, **kwargs):
form = self.form_class()
self.context['action'] = self.action
self.context['form'] = form
return render(req, self.template_name, self.context)
def post(self, req, *args, **kwargs):
form = self.form_class(req.POST or None)
if form.is_valid():
form.save()
else:
print(form.errors)
return redirect('products', permanent=True)
models.py
class Car(models.Model):
name = models.CharField(max_length=32)
model = models.CharField(max_length=32, unique=True)
price = models.IntegerField(validators=[
MinValueValidator(0),
])
def __str__(self):
return f'{self.name} {self.model}'
forms.py
class ManipulateProductForm(forms.ModelForm):
def __init__(self, action="Submit", *args, **kwargs):
super().__init__(*args, **kwargs)
self.action = action
self.helper = FormHelper(self)
self.helper.add_input(Submit('submit', self.action, css_class='btn btn-primary'))
class Meta:
model = Car
fields = '__all__'
manipulate_product.html
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="product-manipulate-container">
{% crispy form form.helper%}
</div>
{% endblock %}
I'm sure the problem is in Crispy, because if I replace code in forms.py and manipulate_product.html to this
forms.py
class ManipulateProductForm(forms.ModelForm):
class Meta:
model = Car
fields = '__all__'
manipulate_product.html
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="product-manipulate-container">
<form action="" method="POST">
{% csrf_token %}
{{ form.as_div }}
<input type="submit" value="Submit">
</form>
</div>
{% endblock %}
Everything is working fine!
I noticed that when I use Crispy in AddProductView post method
is_valid() method returns False but without Crispy it returns True
I have tried everything except one delete the whole project and start over.
I searched on youtube , google , stackoverflow but didn't find anything similar.
Looked at the Crysp documentation, but it's also empty.
I hope someone has come across this problem and can help me.
Thank you!
A:
Try rewriting your form like this:
class ManipulateProductForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ManipulateProductForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_action = 'Submit'
self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary'))
class Meta:
model = Car
fields = '__all__'
And in your template you can just do the following, since you used the default name of the helper:
{% crispy form %}
| Django Crispy Form doesn't add or update database | Hello, I am writing a small project about a car shop and this is the problem I came up with.
I'm trying to add a new car and everything seems to work, but when I fill out the form and click submit, it just redirects me to products page without errors and without adding a new car to the database.
Here is the code.
views.py
class AddProductView(View):
action = 'Add'
template_name = 'myApp/manipulate_product.html'
context = {
}
form_class = ManipulateProductForm
def get(self, req, *args, **kwargs):
form = self.form_class()
self.context['action'] = self.action
self.context['form'] = form
return render(req, self.template_name, self.context)
def post(self, req, *args, **kwargs):
form = self.form_class(req.POST or None)
if form.is_valid():
form.save()
else:
print(form.errors)
return redirect('products', permanent=True)
models.py
class Car(models.Model):
name = models.CharField(max_length=32)
model = models.CharField(max_length=32, unique=True)
price = models.IntegerField(validators=[
MinValueValidator(0),
])
def __str__(self):
return f'{self.name} {self.model}'
forms.py
class ManipulateProductForm(forms.ModelForm):
def __init__(self, action="Submit", *args, **kwargs):
super().__init__(*args, **kwargs)
self.action = action
self.helper = FormHelper(self)
self.helper.add_input(Submit('submit', self.action, css_class='btn btn-primary'))
class Meta:
model = Car
fields = '__all__'
manipulate_product.html
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="product-manipulate-container">
{% crispy form form.helper%}
</div>
{% endblock %}
I'm sure the problem is in Crispy, because if I replace code in forms.py and manipulate_product.html to this
forms.py
class ManipulateProductForm(forms.ModelForm):
class Meta:
model = Car
fields = '__all__'
manipulate_product.html
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="product-manipulate-container">
<form action="" method="POST">
{% csrf_token %}
{{ form.as_div }}
<input type="submit" value="Submit">
</form>
</div>
{% endblock %}
Everything is working fine!
I noticed that when I use Crispy in AddProductView post method
is_valid() method returns False but without Crispy it returns True
I have tried everything except one delete the whole project and start over.
I searched on youtube , google , stackoverflow but didn't find anything similar.
Looked at the Crysp documentation, but it's also empty.
I hope someone has come across this problem and can help me.
Thank you!
| [
"Try rewriting your form like this:\nclass ManipulateProductForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(ManipulateProductForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n self.helper.form_action = 'Submit'\n self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary'))\n\n class Meta:\n model = Car\n fields = '__all__'\n\nAnd in your template you can just do the following, since you used the default name of the helper:\n{% crispy form %}\n\n"
] | [
1
] | [] | [] | [
"backend",
"django",
"django_crispy_forms",
"python"
] | stackoverflow_0074670091_backend_django_django_crispy_forms_python.txt |
Q:
CSV file data to Excel (Remove csv file after workbook save not working)
I'm having trouble removing the csv file after the data is integrated into the workbook. I'm getting a message
The process cannot access the file because it is being used by another process!
and I tried closing the file before I am applying the os.remove syntax to my code. I am curretly stuck in what I should do. I've tried a few methods, but the end statement keeps popping up.
# importing pandas
#importing os
import pandas as pd
import os
csv_1 = open('SearchResults.csv', 'r')
csv_2 = open('SearchResults (1).csv', 'r')
csv_3 = open('SearchResults (2).csv', 'r')
writer = pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter')
# merging three csv files
df = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True)
#Exports csv files to excel sheet on DB_1.xlsx
df.to_excel(writer, sheet_name='sheetname')
csv_1.close()
csv_2.close()
csv_3.close()
writer.save()
try:
os.remove('SearchResults.csv')
print("The file: {} is deleted!".format('SearchResults.csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
try:
os.remove('SearchResults (1).csv')
print("The file: {} is deleted!".format('SearchResults (1).csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
try:
os.remove('SearchResults (2).csv')
print("The file: {} is deleted!".format('SearchResults (2).csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
#Results:
Error: SearchResults.csv - The process cannot access the file because it is being used by another process!
Error: SearchResults (1).csv - The process cannot access the file because it is being used by another process!
Error: SearchResults (2).csv - The process cannot access the file because it is being used by another process!
A:
Using pathlib.glob to find all files, concatenate the csv files with a generator to excel. Finally delete csv files.
import contextlib
from pathlib import Path
import pandas as pd
def concatenate_csvs(path: str) -> None:
pd.concat(
(pd.read_csv(x) for x in Path(f"{path}/").glob("SearchResults*.csv")), ignore_index=True
).to_excel(f"{path}/DB_1.xlsx", index=False, sheet_name="sheetname")
with contextlib.suppress(PermissionError):
[Path(x).unlink() for x in Path(f"{path}/").glob("SearchResults*.csv")]
concatenate_csvs("/path/to/files")
A:
Unless you need to do line by line operations on your three .csv files (and it doesn't seem to be the case here), there is no need to use python's built-in funciton open with pandas.read_csv.
Try this :
import pandas as pd
import os
csv_1 = 'SearchResults.csv'
csv_2 = 'SearchResults (1).csv'
csv_3 = 'SearchResults (2).csv'
# merging three csv files
df = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True)
with pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter') as writer :
#Exports csv files to excel sheet on DB_1.xlsx
df.to_excel(writer, sheet_name='sheetname')
try:
os.remove('SearchResults.csv')
print("The file: {} is deleted!".format('SearchResults.csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
try:
os.remove('SearchResults (1).csv')
print("The file: {} is deleted!".format('SearchResults (1).csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
try:
os.remove('SearchResults (2).csv')
print("The file: {} is deleted!".format('SearchResults (2).csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
| CSV file data to Excel (Remove csv file after workbook save not working) | I'm having trouble removing the csv file after the data is integrated into the workbook. I'm getting a message
The process cannot access the file because it is being used by another process!
and I tried closing the file before I am applying the os.remove syntax to my code. I am curretly stuck in what I should do. I've tried a few methods, but the end statement keeps popping up.
# importing pandas
#importing os
import pandas as pd
import os
csv_1 = open('SearchResults.csv', 'r')
csv_2 = open('SearchResults (1).csv', 'r')
csv_3 = open('SearchResults (2).csv', 'r')
writer = pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter')
# merging three csv files
df = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True)
#Exports csv files to excel sheet on DB_1.xlsx
df.to_excel(writer, sheet_name='sheetname')
csv_1.close()
csv_2.close()
csv_3.close()
writer.save()
try:
os.remove('SearchResults.csv')
print("The file: {} is deleted!".format('SearchResults.csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
try:
os.remove('SearchResults (1).csv')
print("The file: {} is deleted!".format('SearchResults (1).csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
try:
os.remove('SearchResults (2).csv')
print("The file: {} is deleted!".format('SearchResults (2).csv'))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
#Results:
Error: SearchResults.csv - The process cannot access the file because it is being used by another process!
Error: SearchResults (1).csv - The process cannot access the file because it is being used by another process!
Error: SearchResults (2).csv - The process cannot access the file because it is being used by another process!
| [
"Using pathlib.glob to find all files, concatenate the csv files with a generator to excel. Finally delete csv files.\nimport contextlib\nfrom pathlib import Path\n\nimport pandas as pd\n\n\ndef concatenate_csvs(path: str) -> None:\n pd.concat(\n (pd.read_csv(x) for x in Path(f\"{path}/\").glob(\"SearchResults*.csv\")), ignore_index=True\n ).to_excel(f\"{path}/DB_1.xlsx\", index=False, sheet_name=\"sheetname\")\n\n with contextlib.suppress(PermissionError):\n [Path(x).unlink() for x in Path(f\"{path}/\").glob(\"SearchResults*.csv\")]\n\n\nconcatenate_csvs(\"/path/to/files\")\n\n",
"Unless you need to do line by line operations on your three .csv files (and it doesn't seem to be the case here), there is no need to use python's built-in funciton open with pandas.read_csv.\nTry this :\nimport pandas as pd\nimport os\n\ncsv_1 = 'SearchResults.csv'\ncsv_2 = 'SearchResults (1).csv'\ncsv_3 = 'SearchResults (2).csv'\n \n# merging three csv files\ndf = pd.concat(map(pd.read_csv,[csv_1,csv_2,csv_3]), ignore_index=True)\n \nwith pd.ExcelWriter('DB_1.xlsx', engine='xlsxwriter') as writer :\n #Exports csv files to excel sheet on DB_1.xlsx\n df.to_excel(writer, sheet_name='sheetname')\n\ntry:\n os.remove('SearchResults.csv')\n print(\"The file: {} is deleted!\".format('SearchResults.csv'))\nexcept OSError as e:\n print(\"Error: {} - {}!\".format(e.filename, e.strerror))\n\ntry:\n os.remove('SearchResults (1).csv')\n print(\"The file: {} is deleted!\".format('SearchResults (1).csv'))\nexcept OSError as e:\n print(\"Error: {} - {}!\".format(e.filename, e.strerror))\n \ntry:\n os.remove('SearchResults (2).csv')\n print(\"The file: {} is deleted!\".format('SearchResults (2).csv'))\nexcept OSError as e:\n print(\"Error: {} - {}!\".format(e.filename, e.strerror))\n\n"
] | [
0,
0
] | [] | [] | [
"operating_system",
"pandas",
"permissions",
"python"
] | stackoverflow_0074670286_operating_system_pandas_permissions_python.txt |
Q:
httpx.RemoteProtocolError: peer closed connection without sending complete message body
I am getting the above error despite setting the timeout to None for the httpx call. I am not sure what I am doing wrong.
from httpx import stream
with stream("GET", url, params=url_parameters, headers=headers, timeout=None) as streamed_response:
A:
I've got the same error when using httpx via openapi-client autogenerated client
response = httpx.request(verify=client.verify_ssl,**kwargs,)
It turned out in kwargs parameter headers contained wrong authorization token.
So basically in my case that error meant "authorization error".
You might want to check if what you sending in your parameters is correct too.
| httpx.RemoteProtocolError: peer closed connection without sending complete message body | I am getting the above error despite setting the timeout to None for the httpx call. I am not sure what I am doing wrong.
from httpx import stream
with stream("GET", url, params=url_parameters, headers=headers, timeout=None) as streamed_response:
| [
"I've got the same error when using httpx via openapi-client autogenerated client\nresponse = httpx.request(verify=client.verify_ssl,**kwargs,)\n\nIt turned out in kwargs parameter headers contained wrong authorization token.\nSo basically in my case that error meant \"authorization error\".\nYou might want to check if what you sending in your parameters is correct too.\n"
] | [
0
] | [] | [] | [
"httpx",
"python"
] | stackoverflow_0074153345_httpx_python.txt |
Q:
IF ELSE in robot framework [Keyword as a condition]
I just can't figure out how to map a keyword as a condition.
@keyword("Is the Closed Message Page Present")
def check_closedMsg_page(self):
result = self.CLOSED_TEXT.is_displayed
self.LOG(f"It returns {self.CLOSED_TEXT.is_displayed}")
return result
The above function returns a bool value either True or False.
"Is the Closed Message Page Present" is a keyword which I want to make condition. If the condition is true then it should execute the below two keywords else skip it.
IF Is the Closed Message Page Present = True
Then Login username password
And Close Browsers
END
I tried following:
IF Is the Closed Message Page Present == 'True'
Then Login username password
And Close Browsers
END
IF 'Is the Closed Message Page Present' == 'True'
Then Login username password
And Close Browsers
END
Is the Closed Message Page Present
IF True
Then Login username password
And Close Browsers
END
I am expecting the keyword (Is the Closed Message Page Present) to be condition which needs to be true to execute the other two statements or keywords.
A:
I'm still new to the framework, but the only simple method I found is to store the keyword return value to a local variable and use that in the IF statement.
*** Settings ***
Library SeleniumLibrary
Library ../stackoverflow.py
*** Test Cases ***
robot Example
${value} Is the Closed Message Page Present
IF ${value}
Login username password
Close Browser
END
*** Keywords ***
Login
[Arguments] ${username} ${password}
log 'Logs in to system'
stackoverflow.py returns a random True/False value
import random
from robot.api.deco import keyword
class stackoverflow:
@keyword("Is the Closed Message Page Present")
def check_closedMsg_page(self):
return random.choice([True, False])
There is an exhaustive list of conditional expressions that you could further use at https://robocorp.com/docs/languages-and-frameworks/robot-framework/conditional-execution
| IF ELSE in robot framework [Keyword as a condition] | I just can't figure out how to map a keyword as a condition.
@keyword("Is the Closed Message Page Present")
def check_closedMsg_page(self):
result = self.CLOSED_TEXT.is_displayed
self.LOG(f"It returns {self.CLOSED_TEXT.is_displayed}")
return result
The above function returns a bool value either True or False.
"Is the Closed Message Page Present" is a keyword which I want to make condition. If the condition is true then it should execute the below two keywords else skip it.
IF Is the Closed Message Page Present = True
Then Login username password
And Close Browsers
END
I tried following:
IF Is the Closed Message Page Present == 'True'
Then Login username password
And Close Browsers
END
IF 'Is the Closed Message Page Present' == 'True'
Then Login username password
And Close Browsers
END
Is the Closed Message Page Present
IF True
Then Login username password
And Close Browsers
END
I am expecting the keyword (Is the Closed Message Page Present) to be condition which needs to be true to execute the other two statements or keywords.
| [
"I'm still new to the framework, but the only simple method I found is to store the keyword return value to a local variable and use that in the IF statement.\n*** Settings ***\nLibrary SeleniumLibrary\nLibrary ../stackoverflow.py\n\n*** Test Cases ***\nrobot Example\n\n ${value} Is the Closed Message Page Present\n IF ${value}\n Login username password\n Close Browser\n END\n\n*** Keywords ***\nLogin\n [Arguments] ${username} ${password} \n log 'Logs in to system'\n\nstackoverflow.py returns a random True/False value\nimport random\nfrom robot.api.deco import keyword\n\nclass stackoverflow:\n @keyword(\"Is the Closed Message Page Present\")\n def check_closedMsg_page(self):\n return random.choice([True, False])\n\nThere is an exhaustive list of conditional expressions that you could further use at https://robocorp.com/docs/languages-and-frameworks/robot-framework/conditional-execution\n"
] | [
0
] | [] | [] | [
"python",
"robot",
"selenium"
] | stackoverflow_0074657581_python_robot_selenium.txt |
Q:
Not able to access a variable (created in a child frame) from the root window
I am trying to create an application where the user enters a directory name and it gets printed in the console. For this I have created 2 classes:
class FolderInputFrame(tk.Frame):
## child frame class
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self._widgets()
self.pack()
def _widgets(self):
self.directory = tk.StringVar()
buttonDir = tk.Button(self, text = 'Source Directory: ', command = self.browse_button)
buttonDir.pack(side = 'left', padx = 10, pady = 10)
dirEntry = tk.Entry(self, textvariable = self.directory, width = 70)
dirEntry.pack(side = 'left', padx = 10, pady = 10)
def browse_button(self):
dirname = filedialog.askdirectory(initialdir='/', title='Please select a directory')
self.directory.set(dirname)
print(self.directory.get()) ## directory string from child class
class MainWindow(tk.Tk):
## root class
def __init__(self):
tk.Tk.__init__(self)
self.folder_input_container = FolderInputFrame(self)
print(self.folder_input_container.directory.get()) ## directory string from root class
Now when I am trying to print the directory string from the 2 classes, the child class shows the appropriate directory entered, but the root class shows an empty output. I am confused why this is happening? I am fairly new to Tkinter, so any help is appreciated here.
I was expecting the strings from both root and child class should have been same after the button is pressed. I need to know how the flow of control is happening here.
A:
You need to access the data from the instance of the FolderInputFrame since that is the class that created the variable:
print(self.folder_input_container.directory.get())
You need to make sure you do this after the user has clicked the button. In your example you're attempting to print the value immediately after creating the instance of FolderInputFrame.
Use this modified version of MainWindow to see that the value has been updated. After selecting the directory, click the "Show Directory" button to have it print the value to the console.
class MainWindow(tk.Tk):
## root class
def __init__(self):
tk.Tk.__init__(self)
self.folder_input_container = FolderInputFrame(self)
button = tk.Button(self, text="Print Directory", command=self.print_directory)
button.pack()
def print_directory(self):
print(f"directory: {self.folder_input_container.directory.get()}")
| Not able to access a variable (created in a child frame) from the root window | I am trying to create an application where the user enters a directory name and it gets printed in the console. For this I have created 2 classes:
class FolderInputFrame(tk.Frame):
## child frame class
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self._widgets()
self.pack()
def _widgets(self):
self.directory = tk.StringVar()
buttonDir = tk.Button(self, text = 'Source Directory: ', command = self.browse_button)
buttonDir.pack(side = 'left', padx = 10, pady = 10)
dirEntry = tk.Entry(self, textvariable = self.directory, width = 70)
dirEntry.pack(side = 'left', padx = 10, pady = 10)
def browse_button(self):
dirname = filedialog.askdirectory(initialdir='/', title='Please select a directory')
self.directory.set(dirname)
print(self.directory.get()) ## directory string from child class
class MainWindow(tk.Tk):
## root class
def __init__(self):
tk.Tk.__init__(self)
self.folder_input_container = FolderInputFrame(self)
print(self.folder_input_container.directory.get()) ## directory string from root class
Now when I am trying to print the directory string from the 2 classes, the child class shows the appropriate directory entered, but the root class shows an empty output. I am confused why this is happening? I am fairly new to Tkinter, so any help is appreciated here.
I was expecting the strings from both root and child class should have been same after the button is pressed. I need to know how the flow of control is happening here.
| [
"You need to access the data from the instance of the FolderInputFrame since that is the class that created the variable:\nprint(self.folder_input_container.directory.get())\n\nYou need to make sure you do this after the user has clicked the button. In your example you're attempting to print the value immediately after creating the instance of FolderInputFrame.\nUse this modified version of MainWindow to see that the value has been updated. After selecting the directory, click the \"Show Directory\" button to have it print the value to the console.\nclass MainWindow(tk.Tk):\n ## root class\n def __init__(self):\n tk.Tk.__init__(self)\n self.folder_input_container = FolderInputFrame(self)\n button = tk.Button(self, text=\"Print Directory\", command=self.print_directory)\n button.pack()\n\n def print_directory(self):\n print(f\"directory: {self.folder_input_container.directory.get()}\")\n\n"
] | [
0
] | [] | [] | [
"oop",
"python",
"tkinter"
] | stackoverflow_0074669692_oop_python_tkinter.txt |
Q:
Iterate over list selecting multiple elements at a time in Python
I have a list, from which I would like to iterate over slices of a certain length, overlapping each other by the largest amount possible, for example:
>>> seq = 'ABCDEF'
>>> [''.join(x) for x in zip(seq, seq[1:], seq[2:])]
['ABC', 'BCD', 'CDE', 'DEF']
In other words, is there a shorthand for zip(seq, seq[1:], seq[2:]) where you can specify the length of each sub-sequence?
A:
Not an elegant solution, but this works:
seq = 'ABCDEF'
n=3
[seq[i:i+n] for i in range(0, len(seq)+1-n)]
A:
[seq[i:i+3] for i in range(len(seq)-2)] is the Python code for something similar.
The far more elegant and recommended version of this is to use the itertools library from Python (seriously, why do they not just include this function in the library?).
In this case, you would instead use something similar to the pairwise function provided in the documentation.
from itertools import tee
def tripletWise(iterable):
"s -> (s0,s1,s2), (s1,s2,s3), (s2,s3,s4), ..."
a, b, c = tee(iterable, 3)
next(b, None)
next(c, None)
next(c, None)
return zip(a, b)
[''.join(i) for i in tripletWise('ABCDEF')]
> ['ABC', 'BCD', 'CDE', 'DEF']
You can also create a more general function to chunk the list into however many elements you want to select at a time.
def nWise(iterable, n=2):
iterableList = tee(iterable, n)
for i in range(len(iterableList)):
for j in range(i):
next(iterableList[i], None)
return zip(*iterableList)
[''.join(i) for i in nWise('ABCDEF', 4)]
> ['ABCD', 'BCDE', 'CDEF']
A:
Use grouper() in the itertools examples. Specifically grouper(<iter>,3).
https://docs.python.org/3/library/itertools.html#itertools-recipes
Or, from the same page, another recommendation is installing more-itertools. Then you can use ichunked() or chunked().
https://pypi.org/project/more-itertools/
| Iterate over list selecting multiple elements at a time in Python | I have a list, from which I would like to iterate over slices of a certain length, overlapping each other by the largest amount possible, for example:
>>> seq = 'ABCDEF'
>>> [''.join(x) for x in zip(seq, seq[1:], seq[2:])]
['ABC', 'BCD', 'CDE', 'DEF']
In other words, is there a shorthand for zip(seq, seq[1:], seq[2:]) where you can specify the length of each sub-sequence?
| [
"Not an elegant solution, but this works:\nseq = 'ABCDEF'\nn=3\n[seq[i:i+n] for i in range(0, len(seq)+1-n)]\n\n",
"[seq[i:i+3] for i in range(len(seq)-2)] is the Python code for something similar.\nThe far more elegant and recommended version of this is to use the itertools library from Python (seriously, why do they not just include this function in the library?).\nIn this case, you would instead use something similar to the pairwise function provided in the documentation.\nfrom itertools import tee\ndef tripletWise(iterable):\n \"s -> (s0,s1,s2), (s1,s2,s3), (s2,s3,s4), ...\"\n a, b, c = tee(iterable, 3)\n next(b, None)\n next(c, None)\n next(c, None)\n return zip(a, b)\n\n[''.join(i) for i in tripletWise('ABCDEF')]\n> ['ABC', 'BCD', 'CDE', 'DEF']\n\nYou can also create a more general function to chunk the list into however many elements you want to select at a time.\ndef nWise(iterable, n=2):\n iterableList = tee(iterable, n)\n for i in range(len(iterableList)):\n for j in range(i):\n next(iterableList[i], None)\n return zip(*iterableList)\n\n[''.join(i) for i in nWise('ABCDEF', 4)]\n> ['ABCD', 'BCDE', 'CDEF']\n\n",
"Use grouper() in the itertools examples. Specifically grouper(<iter>,3).\nhttps://docs.python.org/3/library/itertools.html#itertools-recipes\nOr, from the same page, another recommendation is installing more-itertools. Then you can use ichunked() or chunked().\nhttps://pypi.org/project/more-itertools/\n"
] | [
4,
1,
0
] | [] | [] | [
"iteration",
"list",
"python",
"python_3.x",
"sequence"
] | stackoverflow_0044765896_iteration_list_python_python_3.x_sequence.txt |
Q:
Python how to read N number of lines at a time
I am writing a code to take an enormous textfile (several GB) N lines at a time, process that batch, and move onto the next N lines until I have completed the entire file. (I don't care if the last batch isn't the perfect size).
I have been reading about using itertools islice for this operation. I think I am halfway there:
from itertools import islice
N = 16
infile = open("my_very_large_text_file", "r")
lines_gen = islice(infile, N)
for lines in lines_gen:
...process my lines...
The trouble is that I would like to process the next batch of 16 lines, but I am missing something
A:
islice() can be used to get the next n items of an iterator. Thus, list(islice(f, n)) will return a list of the next n lines of the file f. Using this inside a loop will give you the file in chunks of n lines. At the end of the file, the list might be shorter, and finally the call will return an empty list.
from itertools import islice
with open(...) as f:
while True:
next_n_lines = list(islice(f, n))
if not next_n_lines:
break
# process next_n_lines
An alternative is to use the grouper pattern:
from itertools import zip_longest
with open(...) as f:
for next_n_lines in zip_longest(*[f] * n):
# process next_n_lines
A:
The question appears to presume that there is efficiency to be gained by reading an "enormous textfile" in blocks of N lines at a time. This adds an application layer of buffering over the already highly optimized stdio library, adds complexity, and probably buys you absolutely nothing.
Thus:
with open('my_very_large_text_file') as f:
for line in f:
process(line)
is probably superior to any alternative in time, space, complexity and readability.
See also Rob Pike's first two rules, Jackson's Two Rules, and PEP-20 The Zen of Python. If you really just wanted to play with islice you should have left out the large file stuff.
A:
Here is another way using groupby:
from itertools import count, groupby
N = 16
with open('test') as f:
for g, group in groupby(f, key=lambda _, c=count(): c.next()/N):
print list(group)
How it works:
Basically groupby() will group the lines by the return value of the key parameter and the key parameter is the lambda function lambda _, c=count(): c.next()/N and using the fact that the c argument will be bound to count() when the function will be defined so each time groupby() will call the lambda function and evaluate the return value to determine the grouper that will group the lines so :
# 1 iteration.
c.next() => 0
0 / 16 => 0
# 2 iteration.
c.next() => 1
1 / 16 => 0
...
# Start of the second grouper.
c.next() => 16
16/16 => 1
...
A:
Since the requirement was added that there be statistically uniform distribution of the lines selected from the file, I offer this simple approach.
"""randsamp - extract a random subset of n lines from a large file"""
import random
def scan_linepos(path):
"""return a list of seek offsets of the beginning of each line"""
linepos = []
offset = 0
with open(path) as inf:
# WARNING: CPython 2.7 file.tell() is not accurate on file.next()
for line in inf:
linepos.append(offset)
offset += len(line)
return linepos
def sample_lines(path, linepos, nsamp):
"""return nsamp lines from path where line offsets are in linepos"""
offsets = random.sample(linepos, nsamp)
offsets.sort() # this may make file reads more efficient
lines = []
with open(path) as inf:
for offset in offsets:
inf.seek(offset)
lines.append(inf.readline())
return lines
dataset = 'big_data.txt'
nsamp = 5
linepos = scan_linepos(dataset) # the scan only need be done once
lines = sample_lines(dataset, linepos, nsamp)
print 'selecting %d lines from a file of %d' % (nsamp, len(linepos))
print ''.join(lines)
I tested it on a mock data file of 3 million lines comprising 1.7GB on disk. The scan_linepos dominated the runtime taking about 20 seconds on my not-so-hot desktop.
Just to check the performance of sample_lines I used the timeit module as so
import timeit
t = timeit.Timer('sample_lines(dataset, linepos, nsamp)',
'from __main__ import sample_lines, dataset, linepos, nsamp')
trials = 10 ** 4
elapsed = t.timeit(number=trials)
print u'%dk trials in %.2f seconds, %.2fµs per trial' % (trials/1000,
elapsed, (elapsed/trials) * (10 ** 6))
For various values of nsamp; when nsamp was 100, a single sample_lines completed in 460µs and scaled linearly up to 10k samples at 47ms per call.
The natural next question is Random is barely random at all?, and the answer is "sub-cryptographic but certainly fine for bioinformatics".
A:
Used chunker function from What is the most “pythonic” way to iterate over a list in chunks?:
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
with open(filename) as f:
for lines in grouper(f, chunk_size, ""): #for every chunk_sized chunk
"""process lines like
lines[0], lines[1] , ... , lines[chunk_size-1]"""
A:
Assuming "batch" means to want to process all 16 recs at one time instead of individually, read the file one record at a time and update a counter; when the counter hits 16, process that group. interim_list = []
infile = open("my_very_large_text_file", "r")
ctr = 0
for rec in infile:
interim_list.append(rec)
ctr += 1
if ctr > 15:
process_list(interim_list)
interim_list = []
ctr = 0
the final group
process_list(interim_list)
A:
Another solution might be to create an iterator that yields lists of n elements:
def n_elements(n, it):
try:
while True:
yield [next(it) for j in range(0, n)]
except StopIteration:
return
with open(filename, 'rt') as f:
for n_lines in n_elements(n, f):
do_stuff(n_lines)
| Python how to read N number of lines at a time | I am writing a code to take an enormous textfile (several GB) N lines at a time, process that batch, and move onto the next N lines until I have completed the entire file. (I don't care if the last batch isn't the perfect size).
I have been reading about using itertools islice for this operation. I think I am halfway there:
from itertools import islice
N = 16
infile = open("my_very_large_text_file", "r")
lines_gen = islice(infile, N)
for lines in lines_gen:
...process my lines...
The trouble is that I would like to process the next batch of 16 lines, but I am missing something
| [
"islice() can be used to get the next n items of an iterator. Thus, list(islice(f, n)) will return a list of the next n lines of the file f. Using this inside a loop will give you the file in chunks of n lines. At the end of the file, the list might be shorter, and finally the call will return an empty list.\nfrom itertools import islice\nwith open(...) as f:\n while True:\n next_n_lines = list(islice(f, n))\n if not next_n_lines:\n break\n # process next_n_lines\n\nAn alternative is to use the grouper pattern:\nfrom itertools import zip_longest\nwith open(...) as f:\n for next_n_lines in zip_longest(*[f] * n):\n # process next_n_lines\n\n",
"The question appears to presume that there is efficiency to be gained by reading an \"enormous textfile\" in blocks of N lines at a time. This adds an application layer of buffering over the already highly optimized stdio library, adds complexity, and probably buys you absolutely nothing.\nThus:\nwith open('my_very_large_text_file') as f:\n for line in f:\n process(line)\n\nis probably superior to any alternative in time, space, complexity and readability.\nSee also Rob Pike's first two rules, Jackson's Two Rules, and PEP-20 The Zen of Python. If you really just wanted to play with islice you should have left out the large file stuff.\n",
"Here is another way using groupby:\nfrom itertools import count, groupby\n\nN = 16\nwith open('test') as f:\n for g, group in groupby(f, key=lambda _, c=count(): c.next()/N):\n print list(group)\n\nHow it works:\nBasically groupby() will group the lines by the return value of the key parameter and the key parameter is the lambda function lambda _, c=count(): c.next()/N and using the fact that the c argument will be bound to count() when the function will be defined so each time groupby() will call the lambda function and evaluate the return value to determine the grouper that will group the lines so :\n# 1 iteration.\nc.next() => 0\n0 / 16 => 0\n# 2 iteration.\nc.next() => 1\n1 / 16 => 0\n...\n# Start of the second grouper.\nc.next() => 16\n16/16 => 1 \n...\n\n",
"Since the requirement was added that there be statistically uniform distribution of the lines selected from the file, I offer this simple approach.\n\"\"\"randsamp - extract a random subset of n lines from a large file\"\"\"\n\nimport random\n\ndef scan_linepos(path):\n \"\"\"return a list of seek offsets of the beginning of each line\"\"\"\n linepos = []\n offset = 0\n with open(path) as inf: \n # WARNING: CPython 2.7 file.tell() is not accurate on file.next()\n for line in inf:\n linepos.append(offset)\n offset += len(line)\n return linepos\n\ndef sample_lines(path, linepos, nsamp):\n \"\"\"return nsamp lines from path where line offsets are in linepos\"\"\"\n offsets = random.sample(linepos, nsamp)\n offsets.sort() # this may make file reads more efficient\n\n lines = []\n with open(path) as inf:\n for offset in offsets:\n inf.seek(offset)\n lines.append(inf.readline())\n return lines\n\ndataset = 'big_data.txt'\nnsamp = 5\nlinepos = scan_linepos(dataset) # the scan only need be done once\n\nlines = sample_lines(dataset, linepos, nsamp)\nprint 'selecting %d lines from a file of %d' % (nsamp, len(linepos))\nprint ''.join(lines)\n\nI tested it on a mock data file of 3 million lines comprising 1.7GB on disk. The scan_linepos dominated the runtime taking about 20 seconds on my not-so-hot desktop. \nJust to check the performance of sample_lines I used the timeit module as so\nimport timeit\nt = timeit.Timer('sample_lines(dataset, linepos, nsamp)', \n 'from __main__ import sample_lines, dataset, linepos, nsamp')\ntrials = 10 ** 4\nelapsed = t.timeit(number=trials)\nprint u'%dk trials in %.2f seconds, %.2fµs per trial' % (trials/1000,\n elapsed, (elapsed/trials) * (10 ** 6))\n\nFor various values of nsamp; when nsamp was 100, a single sample_lines completed in 460µs and scaled linearly up to 10k samples at 47ms per call.\nThe natural next question is Random is barely random at all?, and the answer is \"sub-cryptographic but certainly fine for bioinformatics\".\n",
"Used chunker function from What is the most “pythonic” way to iterate over a list in chunks?:\nfrom itertools import izip_longest\n\ndef grouper(iterable, n, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(*args, fillvalue=fillvalue)\n\n\nwith open(filename) as f:\n for lines in grouper(f, chunk_size, \"\"): #for every chunk_sized chunk\n \"\"\"process lines like \n lines[0], lines[1] , ... , lines[chunk_size-1]\"\"\"\n\n",
"Assuming \"batch\" means to want to process all 16 recs at one time instead of individually, read the file one record at a time and update a counter; when the counter hits 16, process that group. interim_list = []\ninfile = open(\"my_very_large_text_file\", \"r\")\nctr = 0\nfor rec in infile:\n interim_list.append(rec)\n ctr += 1\n if ctr > 15:\n process_list(interim_list)\n interim_list = []\n ctr = 0\nthe final group\nprocess_list(interim_list)\n\n",
"Another solution might be to create an iterator that yields lists of n elements:\ndef n_elements(n, it):\n try:\n while True:\n yield [next(it) for j in range(0, n)]\n except StopIteration:\n return\n\nwith open(filename, 'rt') as f:\n for n_lines in n_elements(n, f):\n do_stuff(n_lines)\n\n\n"
] | [
76,
9,
3,
2,
1,
0,
0
] | [] | [] | [
"lines",
"python",
"python_itertools"
] | stackoverflow_0006335839_lines_python_python_itertools.txt |
Q:
How to re-apply all previous calculations in a pandas data frame on append
Let's say I have this data frame:
df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6]})
And let's say I define a new column like this:
df["C"] = df["A"] + df["B"]
then the C column will have the values [5, 7, 9].
However, let's say I append a new row with the values 4 for A and 7 for B, then the C column will have the values [5, 7, 9, NaN].
How can I define the columns that the calculation rule is automatically applied when something is added to the data frame? Or is there a "recalculate all" function of some sort?
A:
What distinguish Python from other programming languages is that it is interpreted rather than compiled. It means that the code is executed line by line.
So, in your case when you'll add a row at the end of the df, there will be no re-calculation.
df["C"] = df["A"] + df["B"] #executed firstly
df.loc[len(df.index)] = [4, 7, np.NaN] #executed secondly
print(df)
A B C
0 1.0 4.0 5.0
1 2.0 5.0 7.0
2 3.0 6.0 9.0
3 4.0 7.0 NaN
Unless you force the re-calculation yourself by adding the same line as before :
df["C"] = df["A"] + df["B"]
df.loc[len(df.index)] = [4, 7, np.NaN]
df["C"] = df["A"] + df["B"] # <------added here to re-calculate
print(df)
A B C
0 1.0 4.0 5.0
1 2.0 5.0 7.0
2 3.0 6.0 9.0
3 4.0 7.0 11.0
If you're using a notebook like Jupyter, you'll need to put df["C"] = df["A"] + df["B"] in a separate cell and re-run it after each row appended/added.
| How to re-apply all previous calculations in a pandas data frame on append | Let's say I have this data frame:
df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6]})
And let's say I define a new column like this:
df["C"] = df["A"] + df["B"]
then the C column will have the values [5, 7, 9].
However, let's say I append a new row with the values 4 for A and 7 for B, then the C column will have the values [5, 7, 9, NaN].
How can I define the columns that the calculation rule is automatically applied when something is added to the data frame? Or is there a "recalculate all" function of some sort?
| [
"What distinguish Python from other programming languages is that it is interpreted rather than compiled. It means that the code is executed line by line.\nSo, in your case when you'll add a row at the end of the df, there will be no re-calculation.\ndf[\"C\"] = df[\"A\"] + df[\"B\"] #executed firstly\n\ndf.loc[len(df.index)] = [4, 7, np.NaN] #executed secondly\n\nprint(df)\n A B C\n0 1.0 4.0 5.0\n1 2.0 5.0 7.0\n2 3.0 6.0 9.0\n3 4.0 7.0 NaN\n\nUnless you force the re-calculation yourself by adding the same line as before :\ndf[\"C\"] = df[\"A\"] + df[\"B\"]\n\ndf.loc[len(df.index)] = [4, 7, np.NaN]\n\ndf[\"C\"] = df[\"A\"] + df[\"B\"] # <------added here to re-calculate\n\nprint(df)\n A B C\n0 1.0 4.0 5.0\n1 2.0 5.0 7.0\n2 3.0 6.0 9.0\n3 4.0 7.0 11.0\n\nIf you're using a notebook like Jupyter, you'll need to put df[\"C\"] = df[\"A\"] + df[\"B\"] in a separate cell and re-run it after each row appended/added.\n"
] | [
0
] | [] | [] | [
"append",
"apply",
"pandas",
"python"
] | stackoverflow_0074670547_append_apply_pandas_python.txt |
Q:
Using lambda to define a function based on another: How do I keep my code generic?
I have some python code that defines a new function based on an old one. It looks like this
def myFunction(a: int, b: int, c: int):
# Do stuff
myNewFunction = lambda a, b: myFunction(a, b, 0)
My new function is the same as the old function, but sets the last argument to 0.
My question: Say I did not know the function took three arguments. Can I make the above solution more generic? An invalid solution with the right intention might be something like:
def myFunction(a: int, b: int, c: int):
# Do stuff
func_args = myFunction.__code__.co_varnames
func_args = func_args[:-1]
myNewFunction = lambda *func_args : myFunction(*func_args, 0)
A:
You're almost correct, you can use functools.partial this way(instead of lambda):
from functools import partial
def myFunction(a: int, b: int, c: int):
print(a, b, c)
last_param_name = myFunction.__code__.co_varnames[-1]
new_func = partial(myFunction, **{last_param_name: 0})
new_func(10, 20)
Technically partial is not a function it's a class but I don't think this is what you concern about.
A pure Python (roughly)equivalent of the original partial exists in documentation if you want it to be a function type:
def partial(func, /, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = {**keywords, **fkeywords}
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
| Using lambda to define a function based on another: How do I keep my code generic? | I have some python code that defines a new function based on an old one. It looks like this
def myFunction(a: int, b: int, c: int):
# Do stuff
myNewFunction = lambda a, b: myFunction(a, b, 0)
My new function is the same as the old function, but sets the last argument to 0.
My question: Say I did not know the function took three arguments. Can I make the above solution more generic? An invalid solution with the right intention might be something like:
def myFunction(a: int, b: int, c: int):
# Do stuff
func_args = myFunction.__code__.co_varnames
func_args = func_args[:-1]
myNewFunction = lambda *func_args : myFunction(*func_args, 0)
| [
"You're almost correct, you can use functools.partial this way(instead of lambda):\nfrom functools import partial\n\ndef myFunction(a: int, b: int, c: int):\n print(a, b, c)\n\nlast_param_name = myFunction.__code__.co_varnames[-1]\nnew_func = partial(myFunction, **{last_param_name: 0})\n\nnew_func(10, 20)\n\nTechnically partial is not a function it's a class but I don't think this is what you concern about.\nA pure Python (roughly)equivalent of the original partial exists in documentation if you want it to be a function type:\ndef partial(func, /, *args, **keywords):\n def newfunc(*fargs, **fkeywords):\n newkeywords = {**keywords, **fkeywords}\n return func(*args, *fargs, **newkeywords)\n newfunc.func = func\n newfunc.args = args\n newfunc.keywords = keywords\n return newfunc\n\n"
] | [
1
] | [] | [] | [
"lambda",
"python",
"python_3.x"
] | stackoverflow_0074670410_lambda_python_python_3.x.txt |
Q:
Why is Flask making me put @app.route("/interior.html") in route instead of @app.route("/interior")
I am building a website with a booking page that requires me to put the data into a database so I am using python Flask app.
I know that in the @app.route I am only supposed to put @app.route("/exterior") however, whenever I try it using this method I get 404 Page Not Found. Instead I have to put @app.route("/exterior.html"). This is the only way it will work. I believe I have all the correct libraries and I have defined everything correctly; but, it only works if I put .html in the @app.route.
I have researched @app.routes and it only tells me the correct method which I know is @app.route("/exterior"); however, the only thing that works is @app.route("/exterior.html"). If anyone can tell me why this is happening that would be appreciated.
Here is my code.
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from datetime import datetime
# Configure application - turn this file into a Flask application -
app = Flask(__name__)
# Ensure templates are auto-reloaded -
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///bookings.db")
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
return render_template("/index.html")
@app.route("/index.html")
def indexpage():
return render_template("/index.html")
@app.route("/exterior.html")
def exterior():
return render_template("exterior.html")
@app.route("/interior")
def interior():
return render_template("interior.html")
if __name__ == 'main':
app.run(debug = True)
As you can see this is resulting me having to use two routes to load my index page. Once for when I initially run flask and again, so I am able to link to the pages in my navbar.
It's also not the correct method and it bothers me that I am not able to do it correctly. Please advise.
Here is my file directory:
project
static
pics
styles.css
templates
index.html
interior.html
exterior.html
about.html
gallery.html
layout.html
booknow.html
app.py
bookings.db
README.md
unsure why app.py and bookings are not before static and templates and alphabetically that would make more sense; however, this is how it is displayed.
A:
I copied your code and made some minor syntax fixes. below is working as normal. perhaps you could copy this and start adding back some of your functionality and see where it goes wrong.
here is the directory structure:
test_app/
app.py
templates/
interior.html
exterior.html
index.html
and here is app.py:
import os
# from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from datetime import datetime
# Configure application - turn this file into a Flask application -
app = Flask(__name__)
# Ensure templates are auto-reloaded -
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
# db = SQL("sqlite:///bookings.db")
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
return render_template("index.html")
@app.route("/index/")
def indexpage():
return render_template("index.html")
@app.route("/exterior/")
def exterior():
return render_template("exterior.html")
@app.route("/interior/")
def interior():
return render_template("interior.html")
if __name__ == '__main__':
app.run(debug = True)
this work normally for me. what about you?
| Why is Flask making me put @app.route("/interior.html") in route instead of @app.route("/interior") | I am building a website with a booking page that requires me to put the data into a database so I am using python Flask app.
I know that in the @app.route I am only supposed to put @app.route("/exterior") however, whenever I try it using this method I get 404 Page Not Found. Instead I have to put @app.route("/exterior.html"). This is the only way it will work. I believe I have all the correct libraries and I have defined everything correctly; but, it only works if I put .html in the @app.route.
I have researched @app.routes and it only tells me the correct method which I know is @app.route("/exterior"); however, the only thing that works is @app.route("/exterior.html"). If anyone can tell me why this is happening that would be appreciated.
Here is my code.
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from datetime import datetime
# Configure application - turn this file into a Flask application -
app = Flask(__name__)
# Ensure templates are auto-reloaded -
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///bookings.db")
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
return render_template("/index.html")
@app.route("/index.html")
def indexpage():
return render_template("/index.html")
@app.route("/exterior.html")
def exterior():
return render_template("exterior.html")
@app.route("/interior")
def interior():
return render_template("interior.html")
if __name__ == 'main':
app.run(debug = True)
As you can see this is resulting me having to use two routes to load my index page. Once for when I initially run flask and again, so I am able to link to the pages in my navbar.
It's also not the correct method and it bothers me that I am not able to do it correctly. Please advise.
Here is my file directory:
project
static
pics
styles.css
templates
index.html
interior.html
exterior.html
about.html
gallery.html
layout.html
booknow.html
app.py
bookings.db
README.md
unsure why app.py and bookings are not before static and templates and alphabetically that would make more sense; however, this is how it is displayed.
| [
"I copied your code and made some minor syntax fixes. below is working as normal. perhaps you could copy this and start adding back some of your functionality and see where it goes wrong.\nhere is the directory structure:\ntest_app/\n app.py\n templates/\n interior.html\n exterior.html\n index.html\n\nand here is app.py:\nimport os\n\n# from cs50 import SQL\nfrom flask import Flask, flash, jsonify, redirect, render_template, request, session\nfrom datetime import datetime\n\n# Configure application - turn this file into a Flask application -\napp = Flask(__name__)\n\n# Ensure templates are auto-reloaded -\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\n# Configure CS50 Library to use SQLite database\n# db = SQL(\"sqlite:///bookings.db\")\n\n\[email protected]_request\ndef after_request(response):\n \"\"\"Ensure responses aren't cached\"\"\"\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\[email protected](\"/\")\ndef index():\n return render_template(\"index.html\")\n\[email protected](\"/index/\")\ndef indexpage():\n return render_template(\"index.html\")\n\[email protected](\"/exterior/\")\ndef exterior():\n return render_template(\"exterior.html\")\n\n\[email protected](\"/interior/\")\ndef interior():\n return render_template(\"interior.html\")\n\nif __name__ == '__main__':\n app.run(debug = True)\n\nthis work normally for me. what about you?\n"
] | [
0
] | [] | [] | [
"flask",
"html",
"python"
] | stackoverflow_0074499442_flask_html_python.txt |
Q:
How to delete a django JWT token?
I am using the Django rest framework JSON Web token API that is found here on github (https://github.com/GetBlimp/django-rest-framework-jwt/tree/master/).
I can successfully create tokens and use them to call protected REST APis. However, there are certain cases where I would like to delete a specific token before its expiry time. So I thought to do this with a view like:
class Logout(APIView):
permission_classes = (IsAuthenticated, )
authentication_classes = (JSONWebTokenAuthentication, )
def post(self, request):
# simply delete the token to force a login
request.auth.delete() # This will not work
return Response(status=status.HTTP_200_OK)
The request.auth is simply a string object. So, this is of course, not going to work but I was not sure how I can clear the underlying token.
EDIT
Reading more about this, it seems that I do not need to do anything as nothing is ever stored on the server side with JWT. So just closing the application and regenerating the token on the next login is enough. Is that correct?
A:
The biggest disadvantage of JWT is that because the server does not save the session state, it is not possible to abolish a token or change the token's permissions during use. That is, once the JWT is signed, it will remain in effect until it expires, unless the server deploys additional logic.
So, you cannot invalidate the token even you create a new token or refresh it. Simply way to logout is remove the token from the client.
A:
Yes, it's correct to say that JWT tokens are not stored in the database. What you want, though, is to invalidate a token based on user activity, which doesn't seem to be possible ATM.
So, you can do what you suggested in your question, or redirect the user to some token refreshing endpoint, or even manually create a new token.
A:
Add this in Admin.py
class OutstandingTokenAdmin(token_blacklist.admin.OutstandingTokenAdmin):
def has_delete_permission(self, *args, **kwargs):
return True # or whatever logic you want
admin.site.unregister(token_blacklist.models.OutstandingToken)
admin.site.register(token_blacklist.models.OutstandingToken, OutstandingTokenAdmin)
A:
from rest_framework_simplejwt.token_blacklist.admin import OutstandingTokenAdmin
from rest_framework_simplejwt.token_blacklist.models import OutstandingToken
class OutstandingTokenAdmin(OutstandingTokenAdmin):
def has_delete_permission(self, *args, **kwargs):
return True # or whatever logic you want
def get_actions(self, request):
actions = super(OutstandingTokenAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
admin.site.unregister(OutstandingToken)
admin.site.register(OutstandingToken, OutstandingTokenAdmin)
| How to delete a django JWT token? | I am using the Django rest framework JSON Web token API that is found here on github (https://github.com/GetBlimp/django-rest-framework-jwt/tree/master/).
I can successfully create tokens and use them to call protected REST APis. However, there are certain cases where I would like to delete a specific token before its expiry time. So I thought to do this with a view like:
class Logout(APIView):
permission_classes = (IsAuthenticated, )
authentication_classes = (JSONWebTokenAuthentication, )
def post(self, request):
# simply delete the token to force a login
request.auth.delete() # This will not work
return Response(status=status.HTTP_200_OK)
The request.auth is simply a string object. So, this is of course, not going to work but I was not sure how I can clear the underlying token.
EDIT
Reading more about this, it seems that I do not need to do anything as nothing is ever stored on the server side with JWT. So just closing the application and regenerating the token on the next login is enough. Is that correct?
| [
"The biggest disadvantage of JWT is that because the server does not save the session state, it is not possible to abolish a token or change the token's permissions during use. That is, once the JWT is signed, it will remain in effect until it expires, unless the server deploys additional logic. \n So, you cannot invalidate the token even you create a new token or refresh it. Simply way to logout is remove the token from the client.\n",
"Yes, it's correct to say that JWT tokens are not stored in the database. What you want, though, is to invalidate a token based on user activity, which doesn't seem to be possible ATM.\nSo, you can do what you suggested in your question, or redirect the user to some token refreshing endpoint, or even manually create a new token.\n",
"Add this in Admin.py\nclass OutstandingTokenAdmin(token_blacklist.admin.OutstandingTokenAdmin):\n def has_delete_permission(self, *args, **kwargs):\n return True # or whatever logic you want\n\nadmin.site.unregister(token_blacklist.models.OutstandingToken)\nadmin.site.register(token_blacklist.models.OutstandingToken, OutstandingTokenAdmin)\n\n",
"from rest_framework_simplejwt.token_blacklist.admin import OutstandingTokenAdmin\nfrom rest_framework_simplejwt.token_blacklist.models import OutstandingToken\nclass OutstandingTokenAdmin(OutstandingTokenAdmin):\ndef has_delete_permission(self, *args, **kwargs):\nreturn True # or whatever logic you want\ndef get_actions(self, request):\n actions = super(OutstandingTokenAdmin, self).get_actions(request)\n if 'delete_selected' in actions:\n del actions['delete_selected']\n return actions\n\nadmin.site.unregister(OutstandingToken)\nadmin.site.register(OutstandingToken, OutstandingTokenAdmin)\n"
] | [
9,
7,
2,
0
] | [] | [] | [
"django",
"jwt",
"python",
"rest"
] | stackoverflow_0040604877_django_jwt_python_rest.txt |
Q:
set df to value between tuple
i would like to set a df value between two values x_lim(0,2) to True.
I would like to get a df that looks like this:
x | y | z
0 | 7 | True
1 | 3 | True
2 | 4 | True
3 | 8 | False
i tried :
def set_label(df, x_lim, y_lim, variable):
for index, row in df.iterrows():
for i in range(x_lim[0],x_lim[1]):
df['Label'] = variable.get()
print(df)
could anyone help me to solve this problem ?
A:
Here is one way to do it:
import pandas as pd
# Create a dataframe with sample data
df = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})
# Set the 'z' column to True if the value of 'x' is between 0 and 2 (inclusive)
df['z'] = df['x'].between(0, 2, inclusive=True)
# Print the resulting dataframe
print(df)
This will give you the following dataframe:
x y z
0 0 7 True
1 1 3 True
2 2 4 True
3 3 8 False
Hope this helps!
A:
Yes, you can use the loc method to create a new column in your DataFrame that has the values you want. Here's one way to do it:
def set_label(df, x_lim, y_lim, variable):
df['Label'] = False # create a new column with default value of False
df.loc[(df['x'] >= x_lim[0]) & (df['x'] <= x_lim[1]), 'Label'] = variable.get()
# set the values in the Label column to True where x is between x_lim[0] and x_lim[1]
return df
This function takes the DataFrame df, the tuple x_lim with the minimum and maximum values for the x column, and a variable that represents the value to set for the Label column. It creates a new column Label with default value of False, and then uses the loc method to set the values in the Label column to True where the x column is between x_lim[0] and x_lim[1]. Finally, it returns the modified DataFrame.
You can use this function like this:
# create a sample DataFrame
df = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})
# set the label column to True where x is between 0 and 2
df = set_label(df, (0, 2), None, True)
print(df)
This will output the following DataFrame:
x y Label
0 0 7 True
1 1 3 True
2 2 4 True
3 3 8 False
I hope this helps! Let me know if you have any other questions.
| set df to value between tuple | i would like to set a df value between two values x_lim(0,2) to True.
I would like to get a df that looks like this:
x | y | z
0 | 7 | True
1 | 3 | True
2 | 4 | True
3 | 8 | False
i tried :
def set_label(df, x_lim, y_lim, variable):
for index, row in df.iterrows():
for i in range(x_lim[0],x_lim[1]):
df['Label'] = variable.get()
print(df)
could anyone help me to solve this problem ?
| [
"Here is one way to do it:\nimport pandas as pd\n\n# Create a dataframe with sample data\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# Set the 'z' column to True if the value of 'x' is between 0 and 2 (inclusive)\ndf['z'] = df['x'].between(0, 2, inclusive=True)\n\n# Print the resulting dataframe\nprint(df)\n\nThis will give you the following dataframe:\n x y z\n0 0 7 True\n1 1 3 True\n2 2 4 True\n3 3 8 False\n\nHope this helps!\n",
"Yes, you can use the loc method to create a new column in your DataFrame that has the values you want. Here's one way to do it:\ndef set_label(df, x_lim, y_lim, variable):\n df['Label'] = False # create a new column with default value of False\n df.loc[(df['x'] >= x_lim[0]) & (df['x'] <= x_lim[1]), 'Label'] = variable.get()\n # set the values in the Label column to True where x is between x_lim[0] and x_lim[1]\n return df\n\nThis function takes the DataFrame df, the tuple x_lim with the minimum and maximum values for the x column, and a variable that represents the value to set for the Label column. It creates a new column Label with default value of False, and then uses the loc method to set the values in the Label column to True where the x column is between x_lim[0] and x_lim[1]. Finally, it returns the modified DataFrame.\nYou can use this function like this:\n# create a sample DataFrame\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# set the label column to True where x is between 0 and 2\ndf = set_label(df, (0, 2), None, True)\n\nprint(df)\n\nThis will output the following DataFrame:\n x y Label\n0 0 7 True\n1 1 3 True\n2 2 4 True\n3 3 8 False\n\nI hope this helps! Let me know if you have any other questions.\n"
] | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074670641_pandas_python.txt |
Q:
Bot is not waiting for the message
I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.
Here's the function:
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
Here's where I call the function:
await bot.wait_for('message', check=check, timeout=60)
Here's the full command:
@bot.slash_command()
@discord.ext.commands.cooldown(1,60, discord.ext.commands.BucketType.user)
async def buy(message, type: str, amount:Optional[int]):
if amount == None:
amount = 1
if amount < 0:
await message.respond("You cannot buy negative amount of accounts")
member = message.author
con = sqlite3.connect("db.sqlite")
c = con.cursor()
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
elif type == "spotify" or "crunchyroll":
c.execute("SELECT price FROM spotify")
spotiprice = c.fetchall()
spotprice = spotiprice[0][0]
newspot = spotprice*amount
spotytax = await tax(args=newspot)
print(spotiprice[0][0])
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(newspot + spotytax) in message.content
except IndexError:
return False
if type == "netflix":
c.execute('SELECT *, COUNT(*) AS "count" FROM netflix GROUP BY price')
netamount= c.fetchall()
print(netamount[1])
if netamount[0][3] < amount:
await message.respond(f"We do not have this amount of accounts in the stock")
else:
c.execute("SELECT price FROM netflix ")
netfprice = c.fetchall()
netprice = netfprice[0][0]
newnet = netprice*amount
withtax = await tax(args=newnet)
embed = discord.Embed(title="transfer",description=f"Please transfer :{newnet + withtax}")
embed.add_field(name=f"c <@994347081294684240> {newnet + withtax}",value="**Copy paste the message for no error**")
embed.set_footer(text=f"Sidtho Host. | Requested by - {message.author}")
print("Sent embed, Waiting for receiving the credits")
await message.respond(embed=embed)
await bot.wait_for('message', check=check, timeout=60)
c.execute("SELECT email, password FROM netflix")
netres = c.fetchmany(size=amount)
# print(netres)
embed = discord.Embed(title=f"حساب {type}", description="")
embed.add_field(name="Sidtho Host.",value=" ",inline=False)
for thisamount in netres:
try:
email = thisamount[0]
password= thisamount[1]
embed.add_field(name=f"Email: {email}", value=f"Password: {password}", inline=False)
# print(f"The email is {email} \n The password is {password}
except TypeError as err:
print(f"Gave A TypeError. Where {err} ")
await member.send(embed=embed)
c.execute("DELETE FROM netflix WHERE email=? AND password=?",(email, password))
There is no traceback So no error.
Please note that the check function is a Function, not a command.
and the await bot.wait_for is on a command.
Please note too that type is a value that the user will give to the bot, and its not the python built.
A:
In your code, you wrote await message.respond(...).
There isn't a respond() function in both discord.py and pycord, as far as I know. Try changing it to reply(...) and see if it works.
A:
async def buy(message, type: str, amount:Optional[int]):
#type here the stuff that u want make before the check
def check(m):
return m.mentions[0].id == 994347081294684240 and m.author.id == 282859044593598464 and int(nettax + netfprice) in m.content
try:
response = await client.wait_for('message', check=check, timeout=30.0)
except:
#here u can send a message when the time is done
message.send("timeout")
return
so yeah it should look like this u take the response and run any checks on or save to db.
| Bot is not waiting for the message | I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.
Here's the function:
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
Here's where I call the function:
await bot.wait_for('message', check=check, timeout=60)
Here's the full command:
@bot.slash_command()
@discord.ext.commands.cooldown(1,60, discord.ext.commands.BucketType.user)
async def buy(message, type: str, amount:Optional[int]):
if amount == None:
amount = 1
if amount < 0:
await message.respond("You cannot buy negative amount of accounts")
member = message.author
con = sqlite3.connect("db.sqlite")
c = con.cursor()
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()
netprice= neprice[0][0]
netfprice = netprice*amount
nettax = await tax(args=netfprice)
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(nettax + netfprice) in message.content
except IndexError:
return False
elif type == "spotify" or "crunchyroll":
c.execute("SELECT price FROM spotify")
spotiprice = c.fetchall()
spotprice = spotiprice[0][0]
newspot = spotprice*amount
spotytax = await tax(args=newspot)
print(spotiprice[0][0])
try:
return message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and int(newspot + spotytax) in message.content
except IndexError:
return False
if type == "netflix":
c.execute('SELECT *, COUNT(*) AS "count" FROM netflix GROUP BY price')
netamount= c.fetchall()
print(netamount[1])
if netamount[0][3] < amount:
await message.respond(f"We do not have this amount of accounts in the stock")
else:
c.execute("SELECT price FROM netflix ")
netfprice = c.fetchall()
netprice = netfprice[0][0]
newnet = netprice*amount
withtax = await tax(args=newnet)
embed = discord.Embed(title="transfer",description=f"Please transfer :{newnet + withtax}")
embed.add_field(name=f"c <@994347081294684240> {newnet + withtax}",value="**Copy paste the message for no error**")
embed.set_footer(text=f"Sidtho Host. | Requested by - {message.author}")
print("Sent embed, Waiting for receiving the credits")
await message.respond(embed=embed)
await bot.wait_for('message', check=check, timeout=60)
c.execute("SELECT email, password FROM netflix")
netres = c.fetchmany(size=amount)
# print(netres)
embed = discord.Embed(title=f"حساب {type}", description="")
embed.add_field(name="Sidtho Host.",value=" ",inline=False)
for thisamount in netres:
try:
email = thisamount[0]
password= thisamount[1]
embed.add_field(name=f"Email: {email}", value=f"Password: {password}", inline=False)
# print(f"The email is {email} \n The password is {password}
except TypeError as err:
print(f"Gave A TypeError. Where {err} ")
await member.send(embed=embed)
c.execute("DELETE FROM netflix WHERE email=? AND password=?",(email, password))
There is no traceback So no error.
Please note that the check function is a Function, not a command.
and the await bot.wait_for is on a command.
Please note too that type is a value that the user will give to the bot, and its not the python built.
| [
"In your code, you wrote await message.respond(...).\nThere isn't a respond() function in both discord.py and pycord, as far as I know. Try changing it to reply(...) and see if it works.\n",
"async def buy(message, type: str, amount:Optional[int]):\n #type here the stuff that u want make before the check\n def check(m):\n return m.mentions[0].id == 994347081294684240 and m.author.id == 282859044593598464 and int(nettax + netfprice) in m.content \n try:\n response = await client.wait_for('message', check=check, timeout=30.0)\n except:\n #here u can send a message when the time is done\n message.send(\"timeout\")\n return\n \n\n\nso yeah it should look like this u take the response and run any checks on or save to db.\n\n"
] | [
0,
0
] | [] | [] | [
"discord.py",
"pycord",
"python"
] | stackoverflow_0074659035_discord.py_pycord_python.txt |
Q:
How do I make it stop storing everything in the first element of the list?
I am trying to have each line be stored in a different element of the list. The text file is as follows...
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
I am trying to have 244, 576, etc. be in ID. And "Large Cake Pan","Assorted Sprinkles", etc. in Name. You get the idea, but it's storing everything in ID, and I don't know how to make it store the information in its corresponding element.
Here is my code so far:
import Inventory
def process_inventory(filename, inventory_dict):
inventory_dict = {}
inventory_file = open(filename, "r")
for line in inventory_file:
line = line.split('\n')
ID = line[0]
Name = line[1]
Quantity = line[2]
Price = line[3]
my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)
inventory_dict[ID] = my_inventory
inventory_file.close()
return inventory_dict
def main():
inventory1={}
process_inventory("Inventory.txt", inventory1)
A:
In the code you've provided, you're overwriting the inventory_dict parameter with an empty dictionary on the second line of the process_inventory function. This means that the dictionary that you pass to the function as an argument won't be used or updated in the function.
To fix this, you should remove the line inventory_dict = {}, and instead use the inventory_dict parameter directly. This will ensure that the function updates the dictionary that is passed to it as an argument.
Additionally, you're splitting the line on the '\n' character, which is not present in the data. Instead, you should split the line on the space character, ' ', so that you can separate the ID, name, quantity, and price values.
Here's how you can modify the process_inventory function to fix these issues:
def process_inventory(filename, inventory_dict):
inventory_file = open(filename, "r")
for line in inventory_file:
# Split the line on spaces to get the ID, name, quantity, and price values
values = line.split(' ')
ID = values[0]
Name = values[1]
Quantity = values[2]
Price = values[3]
my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)
inventory_dict[ID] = my_inventory
inventory_file.close()
return inventory_dict
With these changes, each line will be processed and added to the inventory_dict dictionary with the ID as the key and the Inventory object as the value.
Note: There is no Inventory class defined in the code you've provided, so it's not clear how the Inventory objects are supposed to be created. You may need to adjust this part of the code depending on how the Inventory class is defined.
| How do I make it stop storing everything in the first element of the list? | I am trying to have each line be stored in a different element of the list. The text file is as follows...
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
I am trying to have 244, 576, etc. be in ID. And "Large Cake Pan","Assorted Sprinkles", etc. in Name. You get the idea, but it's storing everything in ID, and I don't know how to make it store the information in its corresponding element.
Here is my code so far:
import Inventory
def process_inventory(filename, inventory_dict):
inventory_dict = {}
inventory_file = open(filename, "r")
for line in inventory_file:
line = line.split('\n')
ID = line[0]
Name = line[1]
Quantity = line[2]
Price = line[3]
my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)
inventory_dict[ID] = my_inventory
inventory_file.close()
return inventory_dict
def main():
inventory1={}
process_inventory("Inventory.txt", inventory1)
| [
"In the code you've provided, you're overwriting the inventory_dict parameter with an empty dictionary on the second line of the process_inventory function. This means that the dictionary that you pass to the function as an argument won't be used or updated in the function.\nTo fix this, you should remove the line inventory_dict = {}, and instead use the inventory_dict parameter directly. This will ensure that the function updates the dictionary that is passed to it as an argument.\nAdditionally, you're splitting the line on the '\\n' character, which is not present in the data. Instead, you should split the line on the space character, ' ', so that you can separate the ID, name, quantity, and price values.\nHere's how you can modify the process_inventory function to fix these issues:\ndef process_inventory(filename, inventory_dict):\n inventory_file = open(filename, \"r\")\n for line in inventory_file:\n # Split the line on spaces to get the ID, name, quantity, and price values\n values = line.split(' ')\n ID = values[0]\n Name = values[1]\n Quantity = values[2]\n Price = values[3]\n my_inventory = Inventory.Inventory(ID, Name, Quantity, Price)\n inventory_dict[ID] = my_inventory\n inventory_file.close()\n return inventory_dict\n\nWith these changes, each line will be processed and added to the inventory_dict dictionary with the ID as the key and the Inventory object as the value.\nNote: There is no Inventory class defined in the code you've provided, so it's not clear how the Inventory objects are supposed to be created. You may need to adjust this part of the code depending on how the Inventory class is defined.\n"
] | [
0
] | [] | [] | [
"dictionary",
"file",
"list",
"python"
] | stackoverflow_0074670666_dictionary_file_list_python.txt |
Q:
JavaScript is not executed in tracking form
I'm doing an e-commerce website for school and got the task to implement an order tracking system to display the status history of the order. I used a template for this, and half of the code is working. In the views.py file I fetch the information form the database and put it in json format.
However in my html file there is a js script that is supposed to display the iformation from the database and that is not working.
I unfortunately do not have any previous experience with web development, so I'm lost as to why it doesn't work because in the video that used the template it worked.
If someone could help me that would be fantastic as we have to hand the project in in two days.
PS.:
When I put in the ref code and email, it just gives back the HttpResponse with the json. I'm not sure what to do with the HttpResponse though. How does it interact with the script in the html file?
I put
jQuery.noConflict();
at the start of the script as I thought maybe the bootstrap js was overshadowing my script. It didn't do anything though.
Here is my views.py function:
def tracking(request):
if request.method == "POST":
ref_code = request.POST.get('ref_code', '')
email = request.POST.get('email', '')
try:
order = Order.objects.filter(ref_code=ref_code, email=email)
if len(order) > 0:
update = OrderUpdate.objects.filter(ref_code=ref_code)
updates = []
for item in update:
updates.append(
{'text': item.update_desc, 'time': item.timestamp})
response = json.dumps(updates, default=str)
return HttpResponse(response)
else:
return HttpResponse('Please enter a valid ref code and email address.')
finally:
print()
return render(request, 'order_tracking.html')
Here is the script from the order_tracking html file:
<script>
jQuery.noConflict();
$('#trackingForm').submit(function(event) {
$('#items').empty();
var formData = {
'ref_code': $('input[name=ref_code]').val(),
'email': $('input[name=email]').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
};
print(ref_code)
$.ajax({
type: 'POST',
url: '/order-tracking/',
data: formData,
encode: true
})
.done(function(data) {
console.log(data)
updates = JSON.parse(data);
if (updates.length > 0 & updates != {}) {
for (i = 0; i < updates.length; i++) {
let text = updates[i]['text'];
let time = updates[i]['time'];
mystr = `
<li class="list-group-item d-flex justify-content-between align-items-center">
${text}
<span class="badge badge-primary badge-pill">${time}</span>
</li>`
$('#items').append(mystr);
}
} else {
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
Sorry, We are not able to fetch this ref code and email. Make sure to type correct ref code and email</li>`
$('#items').append(mystr);
}
});
event.preventDefault();
});
</script>
And this is the rest of the html file, I'm not sure if it's relevant:
{% block content %}
<div class="container tracking">
<div class="col my-4">
<h2> Enter Your Order ID and Email address to track your order </h2>
<form method="post" action="#" id="trackingForm">{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputname">Ref Code</label>
<input type="text" class="form-control" id="ref_code" name="ref_code" placeholder="Ref Code">
</div>
<div class="form-group col-md-6">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
<button type="submit" class="btn btn-primary">Track Order</button>
</div>
</div>
<div class="col my-4">
<h2>Your Order Status:</h2>
<div class="my-4">
<ul class="list-group" id="items">
</ul>
</div>
</div>
</div>
{% endblock content %}
A:
There are a few potential issues with your code:
You are not rendering the JSON data in the HTML template, so the information from the database is not being displayed on the page. You will need to pass the data from the database to the HTML template and then use it to populate the elements on the page.
The JavaScript code is not being executed, as it is not within a document ready function. This means that it will not run when the page loads. You will need to wrap your code in a document ready function, like this:
$(document).ready(function() {
// your code here
});
You are using jQuery's .noConflict() function, which is meant to be used when multiple libraries are being used on the same page. This may be causing issues with the code, as it is not necessary in this case. You can remove the .noConflict() call and just use $ as the shorthand for jQuery.
The print(ref_code) line in your code is not being executed, as it is not within a function. This may be causing issues with the code, as it is not being called. You will need to move this line of code into a function, like this:
function printRefCode() {
print(ref_code);
}
The $.ajax() call is not being executed, as it is not within a function. This may be causing issues with the code, as it is not being called. You will need to move this line of code into a function, like this:
function submitForm() {
$.ajax({
type: 'POST',
url: '/order-tracking/',
data: formData,
encode: true
});
}
I hope this helps you out! And good luck on the assignment!
| JavaScript is not executed in tracking form | I'm doing an e-commerce website for school and got the task to implement an order tracking system to display the status history of the order. I used a template for this, and half of the code is working. In the views.py file I fetch the information form the database and put it in json format.
However in my html file there is a js script that is supposed to display the iformation from the database and that is not working.
I unfortunately do not have any previous experience with web development, so I'm lost as to why it doesn't work because in the video that used the template it worked.
If someone could help me that would be fantastic as we have to hand the project in in two days.
PS.:
When I put in the ref code and email, it just gives back the HttpResponse with the json. I'm not sure what to do with the HttpResponse though. How does it interact with the script in the html file?
I put
jQuery.noConflict();
at the start of the script as I thought maybe the bootstrap js was overshadowing my script. It didn't do anything though.
Here is my views.py function:
def tracking(request):
if request.method == "POST":
ref_code = request.POST.get('ref_code', '')
email = request.POST.get('email', '')
try:
order = Order.objects.filter(ref_code=ref_code, email=email)
if len(order) > 0:
update = OrderUpdate.objects.filter(ref_code=ref_code)
updates = []
for item in update:
updates.append(
{'text': item.update_desc, 'time': item.timestamp})
response = json.dumps(updates, default=str)
return HttpResponse(response)
else:
return HttpResponse('Please enter a valid ref code and email address.')
finally:
print()
return render(request, 'order_tracking.html')
Here is the script from the order_tracking html file:
<script>
jQuery.noConflict();
$('#trackingForm').submit(function(event) {
$('#items').empty();
var formData = {
'ref_code': $('input[name=ref_code]').val(),
'email': $('input[name=email]').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
};
print(ref_code)
$.ajax({
type: 'POST',
url: '/order-tracking/',
data: formData,
encode: true
})
.done(function(data) {
console.log(data)
updates = JSON.parse(data);
if (updates.length > 0 & updates != {}) {
for (i = 0; i < updates.length; i++) {
let text = updates[i]['text'];
let time = updates[i]['time'];
mystr = `
<li class="list-group-item d-flex justify-content-between align-items-center">
${text}
<span class="badge badge-primary badge-pill">${time}</span>
</li>`
$('#items').append(mystr);
}
} else {
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
Sorry, We are not able to fetch this ref code and email. Make sure to type correct ref code and email</li>`
$('#items').append(mystr);
}
});
event.preventDefault();
});
</script>
And this is the rest of the html file, I'm not sure if it's relevant:
{% block content %}
<div class="container tracking">
<div class="col my-4">
<h2> Enter Your Order ID and Email address to track your order </h2>
<form method="post" action="#" id="trackingForm">{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputname">Ref Code</label>
<input type="text" class="form-control" id="ref_code" name="ref_code" placeholder="Ref Code">
</div>
<div class="form-group col-md-6">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
<button type="submit" class="btn btn-primary">Track Order</button>
</div>
</div>
<div class="col my-4">
<h2>Your Order Status:</h2>
<div class="my-4">
<ul class="list-group" id="items">
</ul>
</div>
</div>
</div>
{% endblock content %}
| [
"There are a few potential issues with your code:\nYou are not rendering the JSON data in the HTML template, so the information from the database is not being displayed on the page. You will need to pass the data from the database to the HTML template and then use it to populate the elements on the page.\nThe JavaScript code is not being executed, as it is not within a document ready function. This means that it will not run when the page loads. You will need to wrap your code in a document ready function, like this:\n$(document).ready(function() {\n // your code here\n});\n\nYou are using jQuery's .noConflict() function, which is meant to be used when multiple libraries are being used on the same page. This may be causing issues with the code, as it is not necessary in this case. You can remove the .noConflict() call and just use $ as the shorthand for jQuery.\nThe print(ref_code) line in your code is not being executed, as it is not within a function. This may be causing issues with the code, as it is not being called. You will need to move this line of code into a function, like this:\nfunction printRefCode() {\n print(ref_code);\n}\n\nThe $.ajax() call is not being executed, as it is not within a function. This may be causing issues with the code, as it is not being called. You will need to move this line of code into a function, like this:\nfunction submitForm() {\n $.ajax({\n type: 'POST',\n url: '/order-tracking/',\n data: formData,\n encode: true\n });\n}\n\nI hope this helps you out! And good luck on the assignment!\n"
] | [
0
] | [] | [] | [
"ajax",
"javascript",
"jquery",
"python"
] | stackoverflow_0074667191_ajax_javascript_jquery_python.txt |
Q:
How to convert uint8 in brackets to (r, g, b) value
Hey guys i found my self stuck on this. I am making an obs spotify app that shows you album cover, name of the artist, and now i would like to add average color output but i need it in rgb.
this is the average code with this output: [112.62674316 103.23660889 98.91593262]
src_img = cv2.imread('icon.jpeg')
average_color_row = np.average(src_img, axis=0)
average_color = np.average(average_color_row, axis=0)
print(average_color)
d_img = np.ones((312,312,3), dtype=np.uint8)
d_img[:,:] = average_color
And i would like it to be converted to (122, 103, 98) yeah and im not also shure if thats right :)
Thanks for help
Tried converting with cv2
and of course searching the internet for alternatives
A:
It looks like the code you posted is using the NumPy library to calculate the average color of an image. The output you're seeing, [112.62674316 103.23660889 98.91593262], is an array of floating point values representing the average values of the red, green, and blue channels of the image, respectively.
To convert this array to a tuple of integers, you can use the NumPy round function to round each value to the nearest integer, and then use the astype function to convert the resulting array to a tuple of integers. Here's how you could do that:
# Calculate the average color of the image
src_img = cv2.imread('icon.jpeg')
average_color_row = np.average(src_img, axis=0)
average_color = np.average(average_color_row, axis=0)
# Round the average color values to the nearest integer
average_color = np.round(average_color)
# Convert the rounded values to a tuple of integers
average_color = average_color.astype(np.int)
# Print the resulting tuple
print(average_color)
This should give you the output you're looking for: (122, 103, 98).
| How to convert uint8 in brackets to (r, g, b) value | Hey guys i found my self stuck on this. I am making an obs spotify app that shows you album cover, name of the artist, and now i would like to add average color output but i need it in rgb.
this is the average code with this output: [112.62674316 103.23660889 98.91593262]
src_img = cv2.imread('icon.jpeg')
average_color_row = np.average(src_img, axis=0)
average_color = np.average(average_color_row, axis=0)
print(average_color)
d_img = np.ones((312,312,3), dtype=np.uint8)
d_img[:,:] = average_color
And i would like it to be converted to (122, 103, 98) yeah and im not also shure if thats right :)
Thanks for help
Tried converting with cv2
and of course searching the internet for alternatives
| [
"It looks like the code you posted is using the NumPy library to calculate the average color of an image. The output you're seeing, [112.62674316 103.23660889 98.91593262], is an array of floating point values representing the average values of the red, green, and blue channels of the image, respectively.\nTo convert this array to a tuple of integers, you can use the NumPy round function to round each value to the nearest integer, and then use the astype function to convert the resulting array to a tuple of integers. Here's how you could do that:\n# Calculate the average color of the image\nsrc_img = cv2.imread('icon.jpeg')\naverage_color_row = np.average(src_img, axis=0)\naverage_color = np.average(average_color_row, axis=0)\n\n# Round the average color values to the nearest integer\naverage_color = np.round(average_color)\n\n# Convert the rounded values to a tuple of integers\naverage_color = average_color.astype(np.int)\n\n# Print the resulting tuple\nprint(average_color)\n\nThis should give you the output you're looking for: (122, 103, 98).\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074670693_numpy_python.txt |
Q:
How can i use .kv file in different folders?
I don't know how to use .kv file so i just want to summary example. For example let we have 2 folders.
These folders: src and design.
src folder contain: main.py
design folder contain: main.kv
I want to know just simple example in this situation. How can i access from main.py file to main.kv file. I researched but i didn't understand very well. Please just give me a simple example.
A:
you can use the Builder object to load all of the .kv files you want.
# useful for creating paths from multiple parts
from pathlib import Path, PurePath
#
from kivy.lang import Builder
# load_file can be called multiple times
Builder.load_file(str(PurePath("c:/", "users", "public", "my_lib.kv")))
Builder.load_file(str(PurePath("c:/", "users", "public", "my_wigdet.kv")))
I don't know the reason but in at least one of my apps, I had to load the one .kv file for the main app in a different way.
main_gui_app = App() # substitute your own app creation..
main_gui_app.kv_file = str(Path(*your_path, "main_app.kv"))
main_qui_app.run()
| How can i use .kv file in different folders? | I don't know how to use .kv file so i just want to summary example. For example let we have 2 folders.
These folders: src and design.
src folder contain: main.py
design folder contain: main.kv
I want to know just simple example in this situation. How can i access from main.py file to main.kv file. I researched but i didn't understand very well. Please just give me a simple example.
| [
"you can use the Builder object to load all of the .kv files you want.\n # useful for creating paths from multiple parts\n from pathlib import Path, PurePath\n #\n from kivy.lang import Builder\n # load_file can be called multiple times\n Builder.load_file(str(PurePath(\"c:/\", \"users\", \"public\", \"my_lib.kv\")))\n Builder.load_file(str(PurePath(\"c:/\", \"users\", \"public\", \"my_wigdet.kv\")))\n\nI don't know the reason but in at least one of my apps, I had to load the one .kv file for the main app in a different way.\nmain_gui_app = App() # substitute your own app creation..\nmain_gui_app.kv_file = str(Path(*your_path, \"main_app.kv\"))\nmain_qui_app.run()\n\n"
] | [
0
] | [] | [] | [
"kivy",
"kivy_language",
"python"
] | stackoverflow_0074667825_kivy_kivy_language_python.txt |
Q:
Clean way to send data struct from python to arduino?
I'm working on a robot and I'd like to somehow send a command using pySerial to the arduino.
The command would look like {MOVE, 60, 70} or {REQUEST_DATA}, where I'd have the arduino read in the first value, if it's "MOVE" then it drives some motors with speed 60 and 70, and if it's "REQUEST_DATA" it would respond with some data like battery status, gps location etc.
Sending this as a string of characters and then parsing is really a huge pain! I've tried days (!frustration!) without it working properly. Is there a way to serialize a data structure like {'MOVE', 70, 40}, send the bytes to the arduino and reconstruct into a struct there? (Using struct.pack() maybe? But I don't yet know how to "unpack" in the arduino).
I've looked at serial communication on arduino and people seem to just do it the 'frustrating' way - sending single chars. Plus all talk about sending struct from arduino to python, and not the other way round.
A:
There are a number of ways to tackle this problem, and the best solution depends on exactly what data you're sending back and forth.
The simplest solution is to represent commands a single bytes (e.g., M for MOVE or R for REQUEST_DATA), because this way you only need to read a single byte on the arduino side to determine the command. Once you know that, you should know how much additional data you need to read in order to get the necessary parameters.
For example, here's a simple program that understands two commands:
A command to move to a given position
A command to turn the built-in LED on or off
The code looks like this:
#define CMD_MOVE 'M'
#define CMD_LED 'L'
struct Position {
int8_t xpos, ypos;
};
struct LEDState {
byte state;
};
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
// We need this so our Python code knows when the arduino is
// ready to receive data.
Serial.println("READY");
}
void loop() {
char cmd;
size_t nb;
if (Serial.available()) {
cmd = Serial.read();
switch (cmd) {
case CMD_MOVE:
struct Position pos;
nb = Serial.readBytes((char *)&pos, sizeof(struct Position));
Serial.print("Moving to position ");
Serial.print(pos.xpos);
Serial.print(",");
Serial.println(pos.ypos);
break;
case CMD_LED:
struct LEDState led;
nb = Serial.readBytes((char *)&led, sizeof(struct LEDState));
if (led.state) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
Serial.print("LED is ");
Serial.println(led.state ? "on" : "off");
break;
}
}
}
A fragment of Python code that interacts with the above might look like this (assuming that port is a serial.Serial object):
print("waiting for arduino...")
line=b""
while not b"READY" in line:
line = port.readline()
port.write(struct.pack('bbb', ord('M'), 10, -10))
res = port.readline()
print(res)
for i in range(10):
port.write(struct.pack('bb', ord('L'), i%2))
res = port.readline()
print(res)
time.sleep(0.5)
port.write(struct.pack('bbb', ord('M'), -10, 10))
res = port.readline()
print(res)
Running the above Python code, with the Arduino code loaded on my Uno, produces:
waiting for arduino...
b'Moving to position -10,10\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'LED is off\r\n'
b'LED is on\r\n'
b'Moving to position 10,-10\r\n'
This is simple to implement and doesn't require much in the way of decoding on the Arduino side.
For more complex situations, you may want to investigate more complex serialization solutions: for example, you can send JSON to the arduino and use something like https://arduinojson.org/ to deserialize it on the Arduino side, but that's going to be a much more complex solution.
In most cases, the speed at which this works is going to be limited by the speed of the serial port: the default speed of 9600bps is relatively slow, and you're going to notice that with larger amounts of data. Using higher serial port speeds will make things noticeably faster: I'm too lazy to look up the max. speed supported by the Arduino, but my UNO works at least as fast as 115200bps.
| Clean way to send data struct from python to arduino? | I'm working on a robot and I'd like to somehow send a command using pySerial to the arduino.
The command would look like {MOVE, 60, 70} or {REQUEST_DATA}, where I'd have the arduino read in the first value, if it's "MOVE" then it drives some motors with speed 60 and 70, and if it's "REQUEST_DATA" it would respond with some data like battery status, gps location etc.
Sending this as a string of characters and then parsing is really a huge pain! I've tried days (!frustration!) without it working properly. Is there a way to serialize a data structure like {'MOVE', 70, 40}, send the bytes to the arduino and reconstruct into a struct there? (Using struct.pack() maybe? But I don't yet know how to "unpack" in the arduino).
I've looked at serial communication on arduino and people seem to just do it the 'frustrating' way - sending single chars. Plus all talk about sending struct from arduino to python, and not the other way round.
| [
"There are a number of ways to tackle this problem, and the best solution depends on exactly what data you're sending back and forth.\nThe simplest solution is to represent commands a single bytes (e.g., M for MOVE or R for REQUEST_DATA), because this way you only need to read a single byte on the arduino side to determine the command. Once you know that, you should know how much additional data you need to read in order to get the necessary parameters.\nFor example, here's a simple program that understands two commands:\n\nA command to move to a given position\nA command to turn the built-in LED on or off\n\nThe code looks like this:\n#define CMD_MOVE 'M'\n#define CMD_LED 'L'\n\nstruct Position {\n int8_t xpos, ypos;\n};\n\nstruct LEDState {\n byte state;\n};\n\nvoid setup() {\n Serial.begin(9600);\n pinMode(LED_BUILTIN, OUTPUT);\n\n // We need this so our Python code knows when the arduino is\n // ready to receive data.\n Serial.println(\"READY\");\n}\n\nvoid loop() {\n char cmd;\n size_t nb;\n\n if (Serial.available()) {\n cmd = Serial.read();\n switch (cmd) {\n case CMD_MOVE:\n struct Position pos;\n nb = Serial.readBytes((char *)&pos, sizeof(struct Position));\n Serial.print(\"Moving to position \");\n Serial.print(pos.xpos);\n Serial.print(\",\");\n Serial.println(pos.ypos);\n break;\n case CMD_LED:\n struct LEDState led;\n nb = Serial.readBytes((char *)&led, sizeof(struct LEDState));\n if (led.state) {\n digitalWrite(LED_BUILTIN, HIGH);\n } else {\n digitalWrite(LED_BUILTIN, LOW);\n }\n Serial.print(\"LED is \");\n Serial.println(led.state ? \"on\" : \"off\");\n\n break;\n }\n }\n}\n\nA fragment of Python code that interacts with the above might look like this (assuming that port is a serial.Serial object):\nprint(\"waiting for arduino...\")\nline=b\"\"\nwhile not b\"READY\" in line:\n line = port.readline()\n\nport.write(struct.pack('bbb', ord('M'), 10, -10))\nres = port.readline()\nprint(res)\n\nfor i in range(10):\n port.write(struct.pack('bb', ord('L'), i%2))\n res = port.readline()\n print(res)\n time.sleep(0.5)\n\nport.write(struct.pack('bbb', ord('M'), -10, 10))\nres = port.readline()\nprint(res)\n\nRunning the above Python code, with the Arduino code loaded on my Uno, produces:\nwaiting for arduino...\nb'Moving to position -10,10\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'LED is off\\r\\n'\nb'LED is on\\r\\n'\nb'Moving to position 10,-10\\r\\n'\n\nThis is simple to implement and doesn't require much in the way of decoding on the Arduino side.\nFor more complex situations, you may want to investigate more complex serialization solutions: for example, you can send JSON to the arduino and use something like https://arduinojson.org/ to deserialize it on the Arduino side, but that's going to be a much more complex solution.\n\nIn most cases, the speed at which this works is going to be limited by the speed of the serial port: the default speed of 9600bps is relatively slow, and you're going to notice that with larger amounts of data. Using higher serial port speeds will make things noticeably faster: I'm too lazy to look up the max. speed supported by the Arduino, but my UNO works at least as fast as 115200bps.\n"
] | [
1
] | [] | [] | [
"arduino",
"pyserial",
"python",
"serial_communication"
] | stackoverflow_0074669524_arduino_pyserial_python_serial_communication.txt |
Q:
How can I make the user input another password if it's not strong enough?
Right now with what I have, even if the password meets all the criteria it prints "Weak password try again!". It allows for another user input but it doesn't break and print "Strong password" if it is strong.
Code:
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
break
print("Strong password")
else:
print(input("Weak password, try again: "))
A:
while True:
passwordName = input("Password ? ")
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
print("Strong password")
break
else:
print("Weak password, try again")
| How can I make the user input another password if it's not strong enough? | Right now with what I have, even if the password meets all the criteria it prints "Weak password try again!". It allows for another user input but it doesn't break and print "Strong password" if it is strong.
Code:
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
break
print("Strong password")
else:
print(input("Weak password, try again: "))
| [
"while True:\n passwordName = input(\"Password ? \")\n if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):\n print(\"Strong password\")\n break\n\n else:\n print(\"Weak password, try again\")\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074670610_python.txt |
Q:
Custom Sorting gglot2 in python
I am working on ggplt visualization, which plotting countries total expenditure from the highest to the lowest. Since there are many small values, I am aggregating several small categories into the "other" category. I am having trouble finding a way to move the "Other" Category to the end and keeping the rest sorted from in descending order
`
ggplot(df_sorted, aes(x = 'reorder(customer_country, Total_Expenditure, fun=sum)', y = 'Total_Expenditure', fill='Total_Expenditure'))\
+ geom_bar(stat="identity")\
+ scale_x_discrete()\
+ coord_flip()\
+scale_fill_cmap(cmap_name="RdYlGn")
`
enter image description here
Have Category Other at the bottom of the bar chart
A:
In general, you can custom sort your dataframe outside ggplot (just using some pandas) and no reordering inside the plot aesthetics will be necessary.
The code below demonstrates this for the diamonds dataset that comes with plotline, where one factor level ('Premium') is moved to the bottom while all others remain sorted.
Side note: Please include (at least a subset) of your actual dataframe in your next question for a fully reproducible example, or demonstrate the question/problem with a dataset provided by one of the libraries.
custom dataframe sorting
there is probably a more elegant way, but the important
from plotnine.data import diamonds
import pandas as pd
# this takes the job of reorder(.., fun=sum) and creates a sorted list of the factor
df = diamonds.groupby('cut', as_index=False).aggregate({'carat': 'sum'})
sorted_levels = df.sort_values('carat')['cut']
# custom reordering of the factor level of interest,
# here 'Premium' is moved to one end while the rest remains ordered
sorted_custom = ['Premium'] + [l for l in sorted_levels if not l == 'Premium']
# reorder dataframe based on these factor levels
df['cut'] = pd.Categorical(df['cut'], sorted_custom)
df = df.sort_values('cut')
plot (without further sorting)
from plotnine import ggplot, aes, geom_bar, scale_x_discrete, coord_flip, scale_fill_cmap
(
ggplot(df, aes(x = 'cut', y = 'carat', fill='carat'))\
+ geom_bar(stat='identity')\
+ scale_x_discrete()\
+ coord_flip()\
+ scale_fill_cmap(cmap_name="RdYlGn")
)
| Custom Sorting gglot2 in python | I am working on ggplt visualization, which plotting countries total expenditure from the highest to the lowest. Since there are many small values, I am aggregating several small categories into the "other" category. I am having trouble finding a way to move the "Other" Category to the end and keeping the rest sorted from in descending order
`
ggplot(df_sorted, aes(x = 'reorder(customer_country, Total_Expenditure, fun=sum)', y = 'Total_Expenditure', fill='Total_Expenditure'))\
+ geom_bar(stat="identity")\
+ scale_x_discrete()\
+ coord_flip()\
+scale_fill_cmap(cmap_name="RdYlGn")
`
enter image description here
Have Category Other at the bottom of the bar chart
| [
"In general, you can custom sort your dataframe outside ggplot (just using some pandas) and no reordering inside the plot aesthetics will be necessary.\nThe code below demonstrates this for the diamonds dataset that comes with plotline, where one factor level ('Premium') is moved to the bottom while all others remain sorted.\nSide note: Please include (at least a subset) of your actual dataframe in your next question for a fully reproducible example, or demonstrate the question/problem with a dataset provided by one of the libraries.\ncustom dataframe sorting\nthere is probably a more elegant way, but the important\nfrom plotnine.data import diamonds\nimport pandas as pd\n\n# this takes the job of reorder(.., fun=sum) and creates a sorted list of the factor\ndf = diamonds.groupby('cut', as_index=False).aggregate({'carat': 'sum'})\nsorted_levels = df.sort_values('carat')['cut']\n\n# custom reordering of the factor level of interest, \n# here 'Premium' is moved to one end while the rest remains ordered\nsorted_custom = ['Premium'] + [l for l in sorted_levels if not l == 'Premium']\n\n# reorder dataframe based on these factor levels\ndf['cut'] = pd.Categorical(df['cut'], sorted_custom)\ndf = df.sort_values('cut')\n\nplot (without further sorting)\n\nfrom plotnine import ggplot, aes, geom_bar, scale_x_discrete, coord_flip, scale_fill_cmap\n(\n ggplot(df, aes(x = 'cut', y = 'carat', fill='carat'))\\\n + geom_bar(stat='identity')\\\n + scale_x_discrete()\\\n + coord_flip()\\\n + scale_fill_cmap(cmap_name=\"RdYlGn\")\n)\n\n\n"
] | [
0
] | [] | [] | [
"ggplot2",
"plotnine",
"python"
] | stackoverflow_0074668827_ggplot2_plotnine_python.txt |
Q:
meaning of double star in pandas dataframe construstor
I want to know what is the meaning of double star in the following pandas dataframe constructor '
If i delete it, then complier raises an error:
Mixing dicts with non-Series may lead to ambiguous ordering.
bus_summary = pd.DataFrame(**{'columns': ['business id column', 'latitude', 'longitude'],
'data': {'business id column': {'50%': 75685.0, 'max': 102705.0, 'min': 19.0},
'latitude': {'50%': -9999.0, 'max': 37.824494, 'min': -9999.0},
'longitude': {'50%': -9999.0,
'max': 0.0,
'min': -9999.0}},
'index': ['min', '50%', 'max']})
I want to know what is the meaning of double star in the following pandas dataframe constructor
A:
The double star (**) is used in the pandas dataframe constructor to indicate that the argument being passed is a dictionary containing key-value pairs. This is commonly used as a shorthand way to pass a dictionary as an argument to a function or method. In this case, the double star allows the dictionary containing the data for the dataframe to be passed as an argument to the pandas dataframe constructor without having to explicitly unpack the dictionary.
| meaning of double star in pandas dataframe construstor | I want to know what is the meaning of double star in the following pandas dataframe constructor '
If i delete it, then complier raises an error:
Mixing dicts with non-Series may lead to ambiguous ordering.
bus_summary = pd.DataFrame(**{'columns': ['business id column', 'latitude', 'longitude'],
'data': {'business id column': {'50%': 75685.0, 'max': 102705.0, 'min': 19.0},
'latitude': {'50%': -9999.0, 'max': 37.824494, 'min': -9999.0},
'longitude': {'50%': -9999.0,
'max': 0.0,
'min': -9999.0}},
'index': ['min', '50%', 'max']})
I want to know what is the meaning of double star in the following pandas dataframe constructor
| [
"The double star (**) is used in the pandas dataframe constructor to indicate that the argument being passed is a dictionary containing key-value pairs. This is commonly used as a shorthand way to pass a dictionary as an argument to a function or method. In this case, the double star allows the dictionary containing the data for the dataframe to be passed as an argument to the pandas dataframe constructor without having to explicitly unpack the dictionary.\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074670749_pandas_python.txt |
Q:
Matplotlib in Rmarkdown/RStudio fails when calling LaTeX on `\$` with Anaconda
Problem description
I am having to use Anaconda on Windows, and am trying to write an RMarkdown document, knitted into a pdf, where within the RMarkdown I am using some Python snippets. However, when I try make matplotlib use LaTeX (with the rc.params) I find it does not render but hits an error I cannot understand nor fix. The offending lines are
mpl.rcParams.update({"text.usetex": True})
...
plt.title(r'Some Latex with symbol \$')
It is LaTeX trying to interpret the \$ which is throwing issues. As far as I can tell this should be correctly escaped. If I remove the \$ everything works as expected, (or if I replace it with e.g. $e=mc^2$).
The error message
Quitting from lines 31-34 (example.Rmd)
Error in py_call_impl(callable, dots$args, dots$keywords) :
RuntimeError: Evaluation error: KeyError: b'tcrm1200'
Detailed traceback:
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\pyplot.py", line 722, in savefig
res = fig.savefig(*args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py", line 2180, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 88, in print_figure
super().print_figure(*args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backend_bases.py", line 2082, in print_figure
**kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2503, in print_pdf
self.figure.draw(renderer)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py"
Calls: <Anonymous> ... py_capture_output -> force -> <Anonymous> -> py_call_impl
Execution halted
MWE
The following is a .Rmd file running on Rstudio 1.2.5001 (should be using Python 3.7 with Conda3, but I'm not so sure how to dig out the specifics on Windows...).
---
output: pdf_document
---
```{r}
library(reticulate)
```
```{python, echo=FALSE, include=FALSE}
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\Users\Harry\Anaconda3\Library\plugins\platforms'
```
```{python, echo=FALSE, include=FALSE}
import matplotlib as mpl
import matplotlib.pyplot as plt
# Setting some default plotting features to give nicer plots. This can be commented out for beginners.
rc_fonts = {
"text.usetex": True,
'text.latex.preview': True, # Gives correct legend alignment.
'mathtext.default': 'regular',
'figure.figsize': (6, 4),
"font.family": "serif",
"font.serif": "computer modern roman",
}
mpl.rcParams.update(rc_fonts)
```
```{python}
plt.plot([0, 2, 1, 4])
plt.title(r'Some Latex with symbol \$')
plt.show()
```
A:
It looks like the error is occurring when matplotlib is trying to save the figure as a pdf. The specific error is a KeyError with the key b'tcrm1200', which is related to the font matplotlib is trying to use for rendering the LaTeX text. The b prefix indicates that the key is a byte string, rather than a regular string.
One potential solution is to explicitly set the font to use for rendering the LaTeX text. You can do this by adding the following lines before the mpl.rcParams.update(rc_fonts) call:
mpl.rcParams['text.latex.preamble'] = r'\usepackage{tgheros}' # Use helvetica font
mpl.rcParams['font.family'] = 'sans-serif' # Use sans-serif font
mpl.rcParams['font.sans-serif'] = 'Helvetica'
This should solve the KeyError by explicitly setting the font matplotlib should use for rendering the LaTeX text.
| Matplotlib in Rmarkdown/RStudio fails when calling LaTeX on `\$` with Anaconda | Problem description
I am having to use Anaconda on Windows, and am trying to write an RMarkdown document, knitted into a pdf, where within the RMarkdown I am using some Python snippets. However, when I try make matplotlib use LaTeX (with the rc.params) I find it does not render but hits an error I cannot understand nor fix. The offending lines are
mpl.rcParams.update({"text.usetex": True})
...
plt.title(r'Some Latex with symbol \$')
It is LaTeX trying to interpret the \$ which is throwing issues. As far as I can tell this should be correctly escaped. If I remove the \$ everything works as expected, (or if I replace it with e.g. $e=mc^2$).
The error message
Quitting from lines 31-34 (example.Rmd)
Error in py_call_impl(callable, dots$args, dots$keywords) :
RuntimeError: Evaluation error: KeyError: b'tcrm1200'
Detailed traceback:
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\pyplot.py", line 722, in savefig
res = fig.savefig(*args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py", line 2180, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 88, in print_figure
super().print_figure(*args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backend_bases.py", line 2082, in print_figure
**kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\backends\backend_pdf.py", line 2503, in print_pdf
self.figure.draw(renderer)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\Harry\ANACON~1\lib\site-packages\matplotlib\figure.py"
Calls: <Anonymous> ... py_capture_output -> force -> <Anonymous> -> py_call_impl
Execution halted
MWE
The following is a .Rmd file running on Rstudio 1.2.5001 (should be using Python 3.7 with Conda3, but I'm not so sure how to dig out the specifics on Windows...).
---
output: pdf_document
---
```{r}
library(reticulate)
```
```{python, echo=FALSE, include=FALSE}
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\Users\Harry\Anaconda3\Library\plugins\platforms'
```
```{python, echo=FALSE, include=FALSE}
import matplotlib as mpl
import matplotlib.pyplot as plt
# Setting some default plotting features to give nicer plots. This can be commented out for beginners.
rc_fonts = {
"text.usetex": True,
'text.latex.preview': True, # Gives correct legend alignment.
'mathtext.default': 'regular',
'figure.figsize': (6, 4),
"font.family": "serif",
"font.serif": "computer modern roman",
}
mpl.rcParams.update(rc_fonts)
```
```{python}
plt.plot([0, 2, 1, 4])
plt.title(r'Some Latex with symbol \$')
plt.show()
```
| [
"It looks like the error is occurring when matplotlib is trying to save the figure as a pdf. The specific error is a KeyError with the key b'tcrm1200', which is related to the font matplotlib is trying to use for rendering the LaTeX text. The b prefix indicates that the key is a byte string, rather than a regular string.\nOne potential solution is to explicitly set the font to use for rendering the LaTeX text. You can do this by adding the following lines before the mpl.rcParams.update(rc_fonts) call:\nmpl.rcParams['text.latex.preamble'] = r'\\usepackage{tgheros}' # Use helvetica font\nmpl.rcParams['font.family'] = 'sans-serif' # Use sans-serif font\nmpl.rcParams['font.sans-serif'] = 'Helvetica'\n\nThis should solve the KeyError by explicitly setting the font matplotlib should use for rendering the LaTeX text.\n"
] | [
0
] | [
"Just remove the backslash! The string is already protected in single quote format.\nplt.title(r'Some Latex with symbol $')\n\n",
"I think u should type in text in 'markdown' section of JupyterNotebook in Ananconda, type the python code in the 'codes' section of the notebook too and finally save it as PDF via LaTeX in the JupyterNotebook. This will solve your problems individually and give u the output I think u r looking for.\n"
] | [
-2,
-4
] | [
"latex",
"matplotlib",
"python",
"r",
"r_markdown"
] | stackoverflow_0058502671_latex_matplotlib_python_r_r_markdown.txt |
Q:
Why do i keep getting an undefined variable error message in python?
So I keep getting error messages for cost_delivery not being defined, but the rest of the cost__ variables are ok, and theres no difference to how I've coded them? I am including my code below - any help would be appreciated!
price = float(input("Please enter the price of the package: "))
distance = float(input("Please enter the distance of delivery in kms: "))
air = 0.36
freight = 0.25
travel = input("Would you like to send your package via air or freight? ")
if travel == 'air':
cost_travel = air * distance
elif travel == 'frieght':
cost_travel = freight * distance
else:
print("Error. Enter either air or frieght.")
full_insurance = 50
lim_insurance = 25
insurance = input("Would you like full insurance or partial insurance?")
if insurance == 'full insurance':
cost_insurance = full_insurance
elif insurance == 'partial insurance':
cost_insurance = lim_insurance
else:
print("Error. Either enter full insurance or partial insurance.")
inc_gift = 15
no_gift = 0
gift = input("Would you like to include gift wrapping?")
if gift == 'yes':
cost_gift = inc_gift
elif gift == 'no':
cost_gift = no_gift
else:
print("Either enter yes or no.")
priority_delivery = 100
standard_delivery = 20
delivery = input("Would you like priority or standard delivery?")
if delivery == 'priority':
cost_delivery == priority_delivery
elif delivery == 'standard':
cost_delivery == standard_delivery
total_cost = cost_travel + cost_insurance + cost_gift + cost_delivery
print(total_cost)
I tried to define cost_delivery = 0 under standard and priority delivery definitions, but it resulted in delivery cost not being included at all in the final calculation.
I am very new to python so any suggestions would be helpful!!
A:
in below section
delivery = input("Would you like priority or standard delivery?")
if delivery == 'priority':
cost_delivery == priority_delivery
elif delivery == 'standard':
cost_delivery == standard_delivery
== is used to check if two object have same value.
since cost_delivery is not defined above in code and you are comparing it here in if .. elif condition, you are geeting this error.
you code should be
delivery = input("Would you like priority or standard delivery?")
if delivery == 'priority':
cost_delivery = priority_delivery
elif delivery == 'standard':
cost_delivery = standard_delivery
| Why do i keep getting an undefined variable error message in python? | So I keep getting error messages for cost_delivery not being defined, but the rest of the cost__ variables are ok, and theres no difference to how I've coded them? I am including my code below - any help would be appreciated!
price = float(input("Please enter the price of the package: "))
distance = float(input("Please enter the distance of delivery in kms: "))
air = 0.36
freight = 0.25
travel = input("Would you like to send your package via air or freight? ")
if travel == 'air':
cost_travel = air * distance
elif travel == 'frieght':
cost_travel = freight * distance
else:
print("Error. Enter either air or frieght.")
full_insurance = 50
lim_insurance = 25
insurance = input("Would you like full insurance or partial insurance?")
if insurance == 'full insurance':
cost_insurance = full_insurance
elif insurance == 'partial insurance':
cost_insurance = lim_insurance
else:
print("Error. Either enter full insurance or partial insurance.")
inc_gift = 15
no_gift = 0
gift = input("Would you like to include gift wrapping?")
if gift == 'yes':
cost_gift = inc_gift
elif gift == 'no':
cost_gift = no_gift
else:
print("Either enter yes or no.")
priority_delivery = 100
standard_delivery = 20
delivery = input("Would you like priority or standard delivery?")
if delivery == 'priority':
cost_delivery == priority_delivery
elif delivery == 'standard':
cost_delivery == standard_delivery
total_cost = cost_travel + cost_insurance + cost_gift + cost_delivery
print(total_cost)
I tried to define cost_delivery = 0 under standard and priority delivery definitions, but it resulted in delivery cost not being included at all in the final calculation.
I am very new to python so any suggestions would be helpful!!
| [
"in below section\ndelivery = input(\"Would you like priority or standard delivery?\")\nif delivery == 'priority':\n cost_delivery == priority_delivery\nelif delivery == 'standard':\n cost_delivery == standard_delivery\n\n\n== is used to check if two object have same value.\nsince cost_delivery is not defined above in code and you are comparing it here in if .. elif condition, you are geeting this error.\nyou code should be\ndelivery = input(\"Would you like priority or standard delivery?\")\nif delivery == 'priority':\n cost_delivery = priority_delivery\nelif delivery == 'standard':\n cost_delivery = standard_delivery\n\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x",
"undefined"
] | stackoverflow_0074670753_python_python_3.x_undefined.txt |
Q:
Django add element to dynamic form
Is there a way to add image element for each input in form?
I need to have an image alongside each input from form. I created this sample form and model that works the same way as in my code. The result I'd like to get is this.
Sample form code
class CreateProfileForm(forms.ModelForm):
fieldsets = [
("Fieldset 1", {'fields': [
'first_name', 'last_name'
]}),
("Fieldset 2", {'fields': [
'address', 'phone'
]}),
]
class Meta:
model = Profile
fields = '__all__'
Sample model code
class Profile(models.Model):
# FIELDSET 1
first_name = models.CharField(max_length=50, verbose_name="First name")
last_name = models.CharField(max_length=50, verbose_name="Last name")
# FIELDSET 2
address = models.CharField(max_length=50, verbose_name="Address")
last_name = models.EmailField(verbose_name="Email")
The view
def create_profile(request):
form = CreateProfileForm()
return render(request, 'form.html', {'form': form})
The template with the form
{% load forms_fieldset static %}
<div class="form data-form">
<form>
{{ form|fieldset:'#000080' }}
<div class="form-group">
<button name="upload" type="submit">Create</button>
</div>
</form>
</div>
A:
To add an image element for each input in a form, you can use the as_table method on the form in your template to render the form fields as an HTML table. Each input will be rendered as a table row, and you can add an img element to each row to display the image.
Here is an example of how you could do this in your template:
<div class="form data-form">
<form>
{% for fieldset in form.fieldsets %}
<fieldset style="border-color: #000080;">
<legend style="color: #000080;">{{ fieldset.legend }}</legend>
<table>
{% for field in fieldset %}
<tr>
<td><img src="{{ field.image_url }}" alt="{{ field.label }}" /></td>
<td>{{ field }}</td>
<td>{{ field.help_text }}</td>
</tr>
{% endfor %}
</table>
</fieldset>
{% endfor %}
<div class="form-group">
<button name="upload" type="submit">Create</button>
</div>
</form>
</div>
In the code above, I have used the as_table method on the form to render the form fields as an HTML table.
| Django add element to dynamic form | Is there a way to add image element for each input in form?
I need to have an image alongside each input from form. I created this sample form and model that works the same way as in my code. The result I'd like to get is this.
Sample form code
class CreateProfileForm(forms.ModelForm):
fieldsets = [
("Fieldset 1", {'fields': [
'first_name', 'last_name'
]}),
("Fieldset 2", {'fields': [
'address', 'phone'
]}),
]
class Meta:
model = Profile
fields = '__all__'
Sample model code
class Profile(models.Model):
# FIELDSET 1
first_name = models.CharField(max_length=50, verbose_name="First name")
last_name = models.CharField(max_length=50, verbose_name="Last name")
# FIELDSET 2
address = models.CharField(max_length=50, verbose_name="Address")
last_name = models.EmailField(verbose_name="Email")
The view
def create_profile(request):
form = CreateProfileForm()
return render(request, 'form.html', {'form': form})
The template with the form
{% load forms_fieldset static %}
<div class="form data-form">
<form>
{{ form|fieldset:'#000080' }}
<div class="form-group">
<button name="upload" type="submit">Create</button>
</div>
</form>
</div>
| [
"To add an image element for each input in a form, you can use the as_table method on the form in your template to render the form fields as an HTML table. Each input will be rendered as a table row, and you can add an img element to each row to display the image.\nHere is an example of how you could do this in your template:\n<div class=\"form data-form\">\n <form>\n {% for fieldset in form.fieldsets %}\n <fieldset style=\"border-color: #000080;\">\n <legend style=\"color: #000080;\">{{ fieldset.legend }}</legend>\n <table>\n {% for field in fieldset %}\n <tr>\n <td><img src=\"{{ field.image_url }}\" alt=\"{{ field.label }}\" /></td>\n <td>{{ field }}</td>\n <td>{{ field.help_text }}</td>\n </tr>\n {% endfor %}\n </table>\n </fieldset>\n {% endfor %}\n\n <div class=\"form-group\">\n <button name=\"upload\" type=\"submit\">Create</button>\n </div>\n </form>\n</div>\n\nIn the code above, I have used the as_table method on the form to render the form fields as an HTML table.\n"
] | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_templates",
"python"
] | stackoverflow_0074670825_django_django_forms_django_models_django_templates_python.txt |
Q:
get my instagram follower list with selenium
I'm beginner on programming. I trying get my Instagram follower list but i have just 12 follower. I tried firstly click to box and scroll down but it didn't work.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
url= "https://www.instagram.com/"
driver.get(url)
time.sleep(1)
kullaniciAdiGir = driver.find_element(By.XPATH, "//*[@id='loginForm']/div/div[1]/div/label/input"")
kullaniciAdiGir.send_keys("USERNAME")
sifreGir = driver.find_element(By.XPATH, "//input[@name='password']")
sifreGir.send_keys("PASS")
girisButonu = driver.find_element(By.XPATH, "//*[@id='loginForm']/div/div[3]/button/div").click()
time.sleep(5)
driver.get(url="https://www.instagram.com/USERNAME/")
time.sleep(3)
kutucuk= driver.get(url="https://www.instagram.com/USERNAME/followers/")
time.sleep(5)
box =driver.find_element(By.XPATH, "//div[@class='xs83m0k xl56j7k x1iy3rx x1n2onr6 x1sy10c2 x1h5jrl4 xieb3on xmn8rco x1hfn5x7 x13wlyjk x1v7wizp x1l0w46t xa3vuyk xw8ag78']")
box.click()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
takipciler = driver.find_elements(By.CSS_SELECTOR, "._ab8y._ab94._ab97._ab9f._ab9k._ab9p._abcm")
for takipci in takipciler:
print(takipci.text)
time.sleep(10)
How can i fix it? How can scroll down in box? Thanks
A:
You can select multiple elements with this.
#get all followers
followers = driver.find_elements(By.CSS_SELECTOR, "._ab8y._ab94._ab97._ab9f._ab9k._ab9p._abcm")
# loop each follower
for user in followers:
#do something here.
Using css selectors, in my opinion, is much easier.
Also note I used find_elemets not find_element, as the latter only returns a single result.
As the data is loaded dynamically, you will, infact have to scroll to make the site load more results. Then compare what you have agaisnt whats loaded. Probably execute some javascrtipt like scroll into view on the last element in that container etc.
or take a look here for an alternative solution
https://www.folkstalk.com/2022/10/how-to-get-a-list-of-followers-on-instagram-python-with-code-examples.html
or look at instragrams API, probably something in there for getting your followers.
| get my instagram follower list with selenium | I'm beginner on programming. I trying get my Instagram follower list but i have just 12 follower. I tried firstly click to box and scroll down but it didn't work.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
url= "https://www.instagram.com/"
driver.get(url)
time.sleep(1)
kullaniciAdiGir = driver.find_element(By.XPATH, "//*[@id='loginForm']/div/div[1]/div/label/input"")
kullaniciAdiGir.send_keys("USERNAME")
sifreGir = driver.find_element(By.XPATH, "//input[@name='password']")
sifreGir.send_keys("PASS")
girisButonu = driver.find_element(By.XPATH, "//*[@id='loginForm']/div/div[3]/button/div").click()
time.sleep(5)
driver.get(url="https://www.instagram.com/USERNAME/")
time.sleep(3)
kutucuk= driver.get(url="https://www.instagram.com/USERNAME/followers/")
time.sleep(5)
box =driver.find_element(By.XPATH, "//div[@class='xs83m0k xl56j7k x1iy3rx x1n2onr6 x1sy10c2 x1h5jrl4 xieb3on xmn8rco x1hfn5x7 x13wlyjk x1v7wizp x1l0w46t xa3vuyk xw8ag78']")
box.click()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
takipciler = driver.find_elements(By.CSS_SELECTOR, "._ab8y._ab94._ab97._ab9f._ab9k._ab9p._abcm")
for takipci in takipciler:
print(takipci.text)
time.sleep(10)
How can i fix it? How can scroll down in box? Thanks
| [
"You can select multiple elements with this.\n#get all followers\nfollowers = driver.find_elements(By.CSS_SELECTOR, \"._ab8y._ab94._ab97._ab9f._ab9k._ab9p._abcm\")\n# loop each follower\nfor user in followers:\n #do something here.\n\nUsing css selectors, in my opinion, is much easier.\nAlso note I used find_elemets not find_element, as the latter only returns a single result.\nAs the data is loaded dynamically, you will, infact have to scroll to make the site load more results. Then compare what you have agaisnt whats loaded. Probably execute some javascrtipt like scroll into view on the last element in that container etc.\nor take a look here for an alternative solution\nhttps://www.folkstalk.com/2022/10/how-to-get-a-list-of-followers-on-instagram-python-with-code-examples.html\nor look at instragrams API, probably something in there for getting your followers.\n"
] | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074670747_python_selenium.txt |
Q:
Python and Pandas - Distances with latitude and longitude
I am trying compare distances between points (in this case fake people) in longitudes and latitudes.
I can import the data, then convert the lat and long data to radians and get the following output with pandas:
lat long
name
Veronica Session 0.200081 0.246723
Lynne Donahoo 0.775020 -1.437292
Debbie Hanley 0.260559 -1.594263
Lisandra Earls 1.203430 -2.425601
Sybil Leef -0.029293 0.592702
From there i am trying to compare different points and get the distance between them.
I came across a post that seemed to be of use (https://stackoverflow.com/a/40453439/15001056) but I am unable to get this working for my data set.
Any help in calculating the distance between points would be appreciated. Idealy id like to expand and optimise the route once the distance function is working.
A:
I used the function in the answer you linked and it worked fine. Can't confirm that the distance is in the unit you need though.
df['dist'] = \
haversine(df.lat.shift(), df.long.shift(),
df.loc[1:, 'lat'], df.loc[1:, 'long'], to_radians=False)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Veronica Session 0.200081 0.246723 NaN
Lynne Donahoo 0.775020 -1.437292 9625.250626
Debbie Hanley 0.260559 -1.594263 3385.893020
Lisandra Earls 1.203430 -2.425601 6859.234096
Sybil Leef -0.029293 0.592702 12515.848878
| Python and Pandas - Distances with latitude and longitude | I am trying compare distances between points (in this case fake people) in longitudes and latitudes.
I can import the data, then convert the lat and long data to radians and get the following output with pandas:
lat long
name
Veronica Session 0.200081 0.246723
Lynne Donahoo 0.775020 -1.437292
Debbie Hanley 0.260559 -1.594263
Lisandra Earls 1.203430 -2.425601
Sybil Leef -0.029293 0.592702
From there i am trying to compare different points and get the distance between them.
I came across a post that seemed to be of use (https://stackoverflow.com/a/40453439/15001056) but I am unable to get this working for my data set.
Any help in calculating the distance between points would be appreciated. Idealy id like to expand and optimise the route once the distance function is working.
| [
"I used the function in the answer you linked and it worked fine. Can't confirm that the distance is in the unit you need though.\ndf['dist'] = \\\nhaversine(df.lat.shift(), df.long.shift(),\n df.loc[1:, 'lat'], df.loc[1:, 'long'], to_radians=False)\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nVeronica Session 0.200081 0.246723 NaN\nLynne Donahoo 0.775020 -1.437292 9625.250626\nDebbie Hanley 0.260559 -1.594263 3385.893020\nLisandra Earls 1.203430 -2.425601 6859.234096\nSybil Leef -0.029293 0.592702 12515.848878\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python",
"traveling_salesman"
] | stackoverflow_0074670372_pandas_python_traveling_salesman.txt |
Q:
How do i have the if statement become effective after the 30 seconds
I want the if statement working after the 30 seconds but that isn't the case right now. I heard people recommend threading but that's just way too complicated for me.
import os
import time
print('your computer will be shutdown if you dont play my game or if you lose it')
shutdown = input("What is 12 times 13? you have 30 seconds.")
time.sleep(30)
if shutdown == '156':
exit()
elif shutdown == '':
print('you didnt even try') and os.system("shutdown /s /t 1")
else:
os.system("shutdown /s /t 1")
I tried threading already but that is really complicated and I'm expecting to print you didn't even try and shutdown after the 30 seconds if you didn't input anything
A:
I recommend to use threads because it makes the thing much easier here. Try this:
import threading
import time
user_input = ""
ANSWER_TIME = 30
def time_over():
match user_input:
case '156':
exit(0)
case '':
print('you didnt even try')
os.system("shutdown /s /t 1")
case _:
os.system("shutdown /s /t 1")
exit_timer = threading.Timer(ANSWER_TIME, time_over)
print('your computer will be shutdown if you dont play my game or if you lose it')
exit_timer.start()
user_input = input("What is 12 times 13? you have 30 seconds.")
Note that I replaced the if-else statements with match-cases, which are IMHO more readable. I also replaced your and statement (if you want to execute two statements, just write them below each other).
A:
I would use inputimeout
https://pypi.org/project/inputimeout/
from inputimeout import inputimeout, TimeoutOccurred
import os
if __name__ == "__main__":
print('your computer will be shutdown if you dont play my game or if you lose it')
try:
answer = inputimeout(prompt="What is 12 times 13? you have 30 seconds.", timeout=30)
except TimeoutOccurred:
os.system("shutdown /s /t 1")
if answer == '':
print('you didnt even try')
os.system("shutdown /s /t 1")
| How do i have the if statement become effective after the 30 seconds | I want the if statement working after the 30 seconds but that isn't the case right now. I heard people recommend threading but that's just way too complicated for me.
import os
import time
print('your computer will be shutdown if you dont play my game or if you lose it')
shutdown = input("What is 12 times 13? you have 30 seconds.")
time.sleep(30)
if shutdown == '156':
exit()
elif shutdown == '':
print('you didnt even try') and os.system("shutdown /s /t 1")
else:
os.system("shutdown /s /t 1")
I tried threading already but that is really complicated and I'm expecting to print you didn't even try and shutdown after the 30 seconds if you didn't input anything
| [
"I recommend to use threads because it makes the thing much easier here. Try this:\nimport threading\nimport time\n\nuser_input = \"\"\nANSWER_TIME = 30\n\ndef time_over():\n match user_input:\n case '156':\n exit(0)\n case '':\n print('you didnt even try')\n os.system(\"shutdown /s /t 1\")\n case _:\n os.system(\"shutdown /s /t 1\")\n\nexit_timer = threading.Timer(ANSWER_TIME, time_over)\nprint('your computer will be shutdown if you dont play my game or if you lose it')\nexit_timer.start()\n\nuser_input = input(\"What is 12 times 13? you have 30 seconds.\")\n\n\nNote that I replaced the if-else statements with match-cases, which are IMHO more readable. I also replaced your and statement (if you want to execute two statements, just write them below each other).\n",
"I would use inputimeout\nhttps://pypi.org/project/inputimeout/\nfrom inputimeout import inputimeout, TimeoutOccurred\nimport os\n\nif __name__ == \"__main__\":\n print('your computer will be shutdown if you dont play my game or if you lose it')\n try:\n answer = inputimeout(prompt=\"What is 12 times 13? you have 30 seconds.\", timeout=30)\n except TimeoutOccurred:\n os.system(\"shutdown /s /t 1\")\n if answer == '':\n print('you didnt even try')\n os.system(\"shutdown /s /t 1\")\n\n"
] | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0074670704_python.txt |
Q:
python datetime.time extract from DB
i've got data extracted by pandas d=pd.read_sql(query, conn)
from DB which looks like this:
day
start
stop
2022-01-01
06:45:27
14:34:24
when i want to import it to array
start=np.asarray(d['start'])
it looks like this:
array([datetime.time(6, 45, 27)])
i want it to look it like
array([06:45:27])
is there a simple way to parse this?
because for days i did something like: day=np.asarray(d['Day'], dtype='datetime64[D]')
so it changed from
array([datetime.date(2022, 1, 1)])
to:
array(['2022-01-01'])
A:
You can use the strftime method to convert the time objects to strings with a specific format. For example, to convert the time object to a string in the format "HH:MM:SS", you can do the following:
import numpy as np
# Create a sample array of datetime.time objects
time_array = np.array([datetime.time(6, 45, 27)])
# Use the strftime method to convert the time objects to strings
formatted_time_array = np.array([time.strftime("%H:%M:%S") for time in
time_array])
# Print the formatted time array
print(formatted_time_array) # Output: ["06:45:27"]
| python datetime.time extract from DB | i've got data extracted by pandas d=pd.read_sql(query, conn)
from DB which looks like this:
day
start
stop
2022-01-01
06:45:27
14:34:24
when i want to import it to array
start=np.asarray(d['start'])
it looks like this:
array([datetime.time(6, 45, 27)])
i want it to look it like
array([06:45:27])
is there a simple way to parse this?
because for days i did something like: day=np.asarray(d['Day'], dtype='datetime64[D]')
so it changed from
array([datetime.date(2022, 1, 1)])
to:
array(['2022-01-01'])
| [
"You can use the strftime method to convert the time objects to strings with a specific format. For example, to convert the time object to a string in the format \"HH:MM:SS\", you can do the following:\nimport numpy as np\n# Create a sample array of datetime.time objects\ntime_array = np.array([datetime.time(6, 45, 27)])\n\n# Use the strftime method to convert the time objects to strings\nformatted_time_array = np.array([time.strftime(\"%H:%M:%S\") for time in \ntime_array])\n\n# Print the formatted time array\nprint(formatted_time_array) # Output: [\"06:45:27\"]\n\n"
] | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074670821_numpy_pandas_python.txt |
Q:
how to specify log format for supervisor stdout log?
I have a process configured in supervisor as below. The module itself have its own logger in code. Normally we do not care the stdout_logfile.
But today I found there are some exception info in stdout_logfile (not captured by the logger in code). I want to know when did those exception happened. But the stdout_logfile did not have timestamp for each line. It seems have no format at all.
So how can we config format for stdout_logfile in supervisor?
[program:my_process]
environment=ENV=test
command=python my_process.py
directory=/home/me/
autostart=true
startretries=3
stopsignal=INT
stopwaitsecs=10
redirect_stderr=true
stdout_logfile=/home/me/logs/my_process.stdout
A:
in my case i solved this problem by using
stderr_logfile=/home/root/project/logfile_err.log
this scripts
| how to specify log format for supervisor stdout log? | I have a process configured in supervisor as below. The module itself have its own logger in code. Normally we do not care the stdout_logfile.
But today I found there are some exception info in stdout_logfile (not captured by the logger in code). I want to know when did those exception happened. But the stdout_logfile did not have timestamp for each line. It seems have no format at all.
So how can we config format for stdout_logfile in supervisor?
[program:my_process]
environment=ENV=test
command=python my_process.py
directory=/home/me/
autostart=true
startretries=3
stopsignal=INT
stopwaitsecs=10
redirect_stderr=true
stdout_logfile=/home/me/logs/my_process.stdout
| [
"in my case i solved this problem by using\nstderr_logfile=/home/root/project/logfile_err.log\n\nthis scripts\n"
] | [
0
] | [] | [] | [
"python",
"supervisord"
] | stackoverflow_0070705507_python_supervisord.txt |